bada development guide for android developer modified final
DESCRIPTION
Bada Development Guide for Android Developer Modified FinalTRANSCRIPT
Samsung Electronics
10/7/2011
Rev 1.0b
bada development guide for Android
developers
Android Developer’s Guide for bada
2
1. Introducing bada Platform for Android Developers ................................................... 4
1.1 The bada Ecosystem .......................................................................................... 4
1.2 Development Tools and Environment ................................................................ 6
1.3 bada C++ vs. Android Java ............................................................................... 7
1.4 bada Phones ...................................................................................................... 8
1.5 Android Phones .................................................................................................. 9
2. The Basic Architecture and UI comparison between bada and Android ................. 12
2.1 Open API Framework ....................................................................................... 15
2.2 Comparison of UI Controls ............................................................................... 20
2.3 The Lifecycle of bada and Android Applications ............................................... 29
2.4 Application Interface Design ............................................................................. 37
2.5 UI Design Tool for Developer’s Convenience ................................................... 38
2.6 Threads ............................................................................................................ 39
2.7 Multitasking ...................................................................................................... 43
3. Event Handling System comparison between bada and Android ............................ 44
3.1 Event Handling in Android and bada ................................................................ 44
3.2 Low Level Touch Events .................................................................................. 48
3.3 Screen Orientation Handling ............................................................................ 50
3.4 Animation ......................................................................................................... 51
3.5 Event Injector ................................................................................................... 52
4. Data Types comparison between bada and Android .............................................. 55
4.1 Primitive Data Types ........................................................................................ 55
4.2 Wrapper Classes for Primitive Types ............................................................... 55
4.3 String Classes .................................................................................................. 56
4.4 String Tokenizing .............................................................................................. 58
4.5 Date and Time Classes .................................................................................... 58
4.6 Collection Classes ............................................................................................ 60
4.7 Data Types comparison between bada and Android ........................................ 62
4.8 Button Controls ................................................................................................. 63
4.9 List Controls ..................................................................................................... 65
4.10 Slider Control ................................................................................................ 72
4.11 Text Input Controls ........................................................................................ 73
4.12 ColorPicker Control ....................................................................................... 75
4.13 DatePicker and TimePicker Controls ............................................................ 77
4.14 Animation Control .......................................................................................... 80
5. Input and Output(I/O) of bada for Android developers ............................................ 82
5.1 Osp::Io Namespace .......................................................................................... 82
5.2 Directories ........................................................................................................ 83
5.3 Files .................................................................................................................. 85
5.4 Databases ........................................................................................................ 86
Android Developer’s Guide for bada
3
6. Graphics of bada for Android developers ................................................................ 88
6.1 bada’s Graphics Support Environment ............................................................. 88
6.2 Images .............................................................................................................. 91
6.3 2D Graphics ..................................................................................................... 91
7. Multimedia of bada for Android developers ............................................................. 94
7.1 Audio and Video ............................................................................................... 97
7.2 Camera ............................................................................................................. 99
8. Communication of bada for Android developers ................................................... 105
8.1 Networking (The Osp::Net Namespace) ......................................................... 105
8.2 Web Services ................................................................................................. 109
8.3 Telephony Services ........................................................................................ 111
8.4 Messaging Services (SMS/MMS/Email) ......................................................... 112
9. Location Based Service of bada for Android developers ...................................... 117
9.1 Location Namespace ...................................................................................... 118
9.2 Location Services ........................................................................................... 120
10. UIX of bada for Android developers ................................................................... 124
10.1 bada's Sensors............................................................................................ 124
10.2 Osp::Uix Namespace .................................................................................. 125
10.3 SensorManager ........................................................................................... 126
10.4 Device Motions ............................................................................................ 127
11. Packaging selling application in bada for Android developers ........................... 130
11.1 Registering Developers ............................................................................... 131
11.2 Issuing Application IDs ................................................................................ 131
11.3 Configuring the Privileged API for the Application ....................................... 133
11.4 Creating the manifest.xml file ...................................................................... 134
11.5 Extracting an App from Eclipse ................................................................... 134
11.6 Registering with Samsung Apps ................................................................. 135
11.7 Using Mobile Devices .................................................................................. 138
Android Developer’s Guide for bada
4
1. Introducing bada Platform for Android Developers
bada is a mobile platform for smart phones developed by Samsung Electronics. Samsung
Electronics introduced a plan for a new mobile platform called bada, for smart phones on
October 10, 2009. bada, which means 'ocean' or 'sea', suggests that bada provides an ocean-
like space for both developers and users: a wide space which contains various kinds of
applications and entertainment as well as a mysterious space which offers limitless fun and
excitement.
Samsung Electronics launched the bada platform in London in December, 2009 followed by the
introduction of Wave, a smart phone based on the bada platform at the MWC (Mobile World
Congress) in February, 2010, in Barcelona, Spain.
bada is an open mobile platform, with key features that are easier to use compared to other
phones or smart phones, such as downloading and installing applications/using features, a
powerful internet service feature, and an innovative smart phone UI. bada also supports
TouchWiz 3.0, which is also used in Samsung mobile phones, allowing existing Samsung
mobile phone users to use it easily.
1.1 The bada Ecosystem
The mobile ecosystem provides an environment where providers, developers and consumers
can interact with each other from the development to the distribution of applications; it provides
a developer support site run by the platform provider, a system for application registration-
approval-distribution processes, and a market place where end users can properly download
applications.
Development environments and references are provided on Google's developer site
(developer.android.com) as a means to support the development of Android applications, and
the applications are distributed to the Android market through a publishing site:
http://market.android.com/publish.
Android Developer’s Guide for bada
5
In Google's Android application market, no pre-approval is required, though registration is
needed for distribution. Developers need to register as developers (cost $25/year) with a
Google account and sell their products through a published site. Non-free applications can be
sold after configuring the bank information.
Applications which may create social or legal problems can be deleted immediately from
phones by a kill-switch function. However, the weak point is that applications which are
purchased and installed from a 3rd party market cannot be regulated.
However, they can be easily distributed through markets run by carriers of each country. Usually,
the revenue share model is 70/30 (developer/carrier). When applications are registered, they go
through an approval process to ensure compliance with the regulations of each country and
they use DRM (Digital rights management) to protect applications.
bada supports developers through the Samsung bada developer site (developer.bada.com) and
supports selling applications through the SamsungApps application market and SamsungApps
seller sites.
Figure 1.1 bada Echo System
The Samsung Apps website opened by Samsung Electronics on September 14, 2009, has
registered a total number of 20 000 applications, including 5000 bada applications by the end of
2010.
Android Developer’s Guide for bada
6
In February 2011, about 8000 bada applications were registered. This site also supports selling
applications in over 120 countries worldwide and supports selling Android applications, other
mobile applications and Samsung Electronics TV applications as well as bada applications.
The profit of the applications sales is shared 70:30 the same as for Android. In order for bada
applications to be registered for sales, they need to be approved by SamsungApps, which takes
less than 7 working days.
In addition, the verification result shows the video screen with the result report so that the
developer (developer company) can directly identify where the verification was interrupted.
Figure 1.2 bada’s video report
1.2 Development Tools and Environment
bada's SDK provides various tools in an integrated manner through the widely used Eclipse IDE
so that users can easily access the development environment.
SDK Integrated IDE: Eclipse CDT / bada (C/C++ Development Tools)
• Standard C++ and STL are supported through the bada C++ framework.
• The bada Web Framework: Supports html5, java script and WAC 2.0
• The bada Emulator: Provides an environment where developers can immediately test a
bada application after the development.
• Thousands of Eclipse features: svn / git plug-in, UML plug-in, etc.
Android Developer’s Guide for bada
7
The bada IDE provides a development environment for both the host machine and the target
board with one installation. In addition, it provides the IDE of the Eclipse open software so that
Java developers can easily adapt to the C++ development environment.
bada Development Environment Android Development
Environment
Development
Language
C++ Java language on Dalvik
Development Tool The IDE and bada SDK on the basis
of the Eclipse CDT
The Eclipse IDE and Android SDK
C/C++ support through the Eclipse
ADT plug-in NDK.
UI Development
Tool
bada IDE's UI Builder Layout Editor and xml
Other Development
Tools
bada Emulator (bada 1.x provides
Simulator)
Event Injector
Tool-chain
Memory usage checker
Android Emulator (on the basis of
QEMU)
adb, draw9patch, hierachiviewer
Since the bada SDK provides an IDE using Eclipse which is the same as that of Android,
Android developers can easily approach the bada development environment. In addition,
powerful bada C++ development references and documents are provided.
1.3 bada C++ vs. Android Java
Android applications use Java, an OOP (Object Oriented Programming) language. The
concepts and terminologies are common among OOP languages.
For example, as single inheritance and multiple interface implementations are supported in the
Android platform, the bada platform also allows single inheritance and multiple interface
implementations. These similarities in the development environments make it easier for Android
developers to develop for the bada platform.
Android Developer’s Guide for bada
8
The following is a comparison of Java on Android and C++ on bada from the viewpoint of the
computer language used on each platform.
Java on Android Comparison Item C++ on bada
package
E.g. package
com.samsung.bada
The way to identify and classify
classes on the basis of their
functions.
Namespace
E.g. using the Osp::App
namespace
.java The file extension of the Java
source file.
.h, .cpp
Object class inheritance Single inheritance is supported
and implementation through an
interface is supported.
Object class
However, a few classes do not
inherit an Object.
interface keyword Interface abstract class
public MyClass() Constructor 2-Phase Construction
E.g. ArrayList* pArr = new
ArrList();
pArr->Construct()
null or Garbage collection Destructor For user-created objects,
manual memory deallocation is
required using an instruction
such as "delete".
1.4 bada Phones
The Wave (S8500) was first introduced in 2010 at the MWC, and sales started in March 2010
offering bada developers a popular smart phone market.
Figure1.3 Wave II
Wave phones can be classified into
the high-end smart phone market
already on the Korea market, and
phone market are the Wave 525,
new model with a resolution of 320
market in the near future.
Figure1.4 bada
High
Model Wave (S8500),
Processor Faster than 1GHz
(ARM CORTEX
Screen/LCD 3.3” / 3.7” WVGA
Super AMOLED
3D
Acceleration OpenGL
Camera 5.0 Megapixels
Rear-facing
Sensor
GPS, WPS,
proximity sensor,
inclinometer,
Video HD(720p) Video
playing
Haptic UI Vibrations
1.5 Android Phones
Android Developer’s Guide for
into two categories. 480 x 800 high resolution models
market are called Wave, the first high resolution model,
and 240 x 400 low resolution models aimed at the
525, Wave 533, Wave 575, Wave 578 and Wave 723
320 x 480 with bada 2.0 is planned to be introduced
bada Platform – Wave 525, 533, 578 and 723
High-End Mid/Low-End
(S8500), Wave II etc. Wave 525, Wave 533, Wave
578, Wave 723
1GHz
CORTEX-A8 1GHz etc.)
ARM 9/ ARM
(ARM9 312 Mhz
WVGA (480x800)
AMOLED / Super Clear LCD
3.2” WQVGA (240x400)
TFT
OpenGL ES 1.1 / 2.0 N/A
Megapixels
facing camera
3.0 Megapixels
Rear-facing camera
magnetic sensor,
sensor, accelerometer,
inclinometer, etc.
Accelerometer, GPS,
Video recording and
playing MPEG4, H.263,
Vibrations Vibrations (a Haptic UI
Android Developer’s Guide for bada
9
models aimed at
model, and Wave II,
the low-end smart
723 models. A
introduced to the
End
Wave 575, Wave
723 etc.
ARM 11
Mhz etc.)
(240x400)
Megapixels
camera
GPS, WPS, NFC
H.263, H.264
is not supported)
Android Developer’s Guide for bada
10
Google Inc. acquired Android Inc. in 2005 followed by the creation of the Open Handset Alliance.
As a first step to enter the market, HTC introduced the G1 phone (HTC Dream) for development
purposes in November 2008. Today, about 310 Android phone models are manufactured by
various manufacturers and Android phones are sold every day (as of June 2011).
OS Major Terminals Features
1.0 SDK
The first Android phone for
developers. A.
Qwerty keyboard is
supported. HTC G1 HTC Magic
1.5
Cupcake
Live folder
Home screen widget
HTC Hero Motorola
Cliq
Samsung
Galaxy
1.6
Donuts
TTS (Text to Speech) Is
supported.
A Quick Search Box is
supported.
The battery power
consumption of each
application can be
measured.
Motorola
Devour
LG-LU-
2300
SonyEricsson
X10
2.0 / 2.1
Éclair
Multi account and
integrated email.
SMS and MMS search.
Multi-touch.
Bluetooth 2.1
Nexus One Samsung
Galaxy S
LG SU950/
KU9500
2.2
Froyo
HTC Desire
2.3
Gingerbr
ead
`Nexus
3.0
Honeyco
mb
Motorola
Xoom
Figure
Android Developer’s Guide for
Exchange
reinforced.
Installing
the external
supported.
Tethering
Auto
Chrome
Desire HTC Desire HD
Text
Selection
reinforced.
NFC`Nexus S Samsung
Galaxy S2
The
PC.
Motorola
Samsung Galaxy
Tab 10.1
Figure1.5 Android OS & Phone
Android Developer’s Guide for bada
11
Exchange support
reinforced.
Installing applications onto
external memory is
supported.
Tethering is supported.
Auto market update.
Chrome v8 JS engine
Text Copy&Paste and
Selection functions are
reinforced.
NFC is supported.
first Android for Tablet
2. The Basic Architecture and UI comparison between
bada and Android
bada consists of a Device layer
interoperating with various external
Figure 2.1 The Architecture of the bada operating system
Android Developer’s Guide for
The Basic Architecture and UI comparison between
bada and Android
layer that provides HAL for hardware devices, a Service
external services and a Framework layer, on the basis
The Architecture of the bada operating system
Android Developer’s Guide for bada
12
The Basic Architecture and UI comparison between
Service layer for
basis of the Kernel.
Android Developer’s Guide for bada
13
The architecture of the framework of the Android platform is as follows.
Figure 2.2 The Architecture of the Android operating system (source: developer.android.com)
Although 1:1 a comparison is difficult, the layers of each operating system can be compared as
follows:
Android
OS Layer Function bada OS layer
Application
Framework
Various applications and
widgets Open API Framework
Libraries
The low level libraries of Android
developed with
C/C++.
Service layer
Hal Hardware interface Device layer
Kernel Linux kernel 2.6.x kernel
Mobile developers develop user Interfaces through the Application framework that interacts with
users rather than the lower layers, and call the hardware and Kernel API functions provided by
the framework to complete the program logic.
Android Developer’s Guide for bada
14
Android Developer’s Guide for bada
15
2.1 Open API Framework
The Open API Framework can be classified into three parts as the following figure shows.
Framework
Basic Features User Interactive
Feature
Service orientated
features
Osp::App Osp::Graphics Osp::Commerce
Osp::Io Osp::Media Osp::Locations
Osp::Locales Osp::Ui Osp::Messaging
Osp::Net Osp::Uix Osp::Social
Osp::Security Osp::Web Osp::Ads
Osp::System
Osp::Telephony
Osp::Text
Service
Device
Kernel
A. Basic features
The basic features part defines the most primitive classes of the bada platform.
bada Description Android
Osp::App The App namespace contains
the classes for the application
development, including
application life-cycle
management, the usage of the
The classes of the Manager package
related to basic components such as
android.appActivity and View.
Android Developer’s Guide for bada
16
functionality exported by other
applications through
AppControl, and access to the
application registry and
resources. Samsung bada also
provides various macros for
debugging purposes.
Osp::Base The Base namespace contains
classes and interfaces around
which the entire bada system is
built. The main features of the
namespace include basic data
types, collections, runtime
libraries and various utilities.
The String classes provided by the
java.lang package, the data structure
classes provided by the
java.lang.thread and Java's base
collection class and the system
environment classes provided by
Android.os.
Osp::Io The Io namespace allows the
application to receive data from
users and other programs,
process it, and return the result.
Thus, the Io namespace is an
interface between the system
and the application.
This class provides the data stream and
serialization functions through the
java.io package and system input and
output functions for the file system.
Osp::Locales The Locales namespace
contains the classes
representing a specific cultural
region (locale) and the classes
for manipulating and formatting
locale-sensitive information,
such as dates, times, numbers,
and time zones.
The java.util.locale, java.lang.String and
java.util.Date/Calendar classes for text
display, locate and localization.
Osp::Net The Net namespace helps
access the data communication
capabilities of bada. This
namespace is responsible for
On the basis of the java.net package,
android.net and org.apache packages
support various Internet protocols.
Short range communication is
Android Developer’s Guide for bada
17
managing connections and
accounts, and maintaining IP
addresses and connections to
the system through Bluetooth,
Hypertext Transfer Protocol
(HTTP), Near Field
Communication (NFC), Sockets,
and Wi-Fi. It also provides
methods for retrieving
information about a specific host
from the Internet Domain Name
System (DNS).
supported by the android.bluetooth and
android.net.nfc packages.
Osp::Security The Security namespace
contains classes for managing
certificates, cryptographic keys,
signatures, and for generating
pseudo-random numbers.
The java.security package that is the
security framework
Osp::System The System namespace
provides system management
features, such as system time,
alarm, vibrator, power, and
device management. It also
provides the system, setting and
runtime information.
The System related manager class
provided by the android.os package
and system monitoring through
BroadcastReceiver.
Osp::Telephony This namespace provides
classes and methods that
enable an application to access
the telephony capabilities of the
device, such as the call facility
(call information and status),
network query services and the
SIM module.
The telephony and text message
related classes provided by the
android.telephony package.
Osp::Text The Text namespace contains The java.lang.String and text related
Android Developer’s Guide for bada
18
the Encoding class, which is the
base class for encoding and
decoding many character
encodings, such as UTF-8,
UCS-2, Latin-1, GSM, and
ASCII. It also contains the
Decoder and Encoder classes
for converting text blocks.
classes and
java.text.Format class are provided.
B. bada user Interactive features
The bada Framework provides the following name spaces to arrange Form-based UI controls,
handle events, process graphics and to handle devices such as a camera.
Android Developer’s Guide for bada
19
bada Description Android
Osp::Graphics The Graphics namespace
provides 2D graphics, text, and
images. It also provides Bitmap,
Font, and Color to enhance the
rendered graphics.
android.graphics,
android.graphics.drawable and
android.graphics.drawable.shapes
Osp::Media The Media namespace defines
the interfaces and classes that let
the application integrate audio,
video, and image processing
functions easily.
Classes included are the
android.media, android.graphics and
android.hardware.Camera packages.
Osp::Ui The Ui namespace is used to
construct graphical user
interfaces (UI). It contains classes
and interfaces for handling UI-
related events. it has 2 sub-
namespaces: Osp::Ui::Controls
and Osp::Ui::Animations
The UI controls the classes of the
android.view and android.widget
packages that construct the basic
android UI components.
Osp::Uix The Uix namespace contains
classes and interfaces for the UI
extension services as face
detection and recognition, device
sensor input and motion
detection, and speech recognition
and synthesis.
The sensor class provided by
android.hardware and
android.os.Vibrator.
Osp::Web The Web namespace contains
classes and interfaces for
browsing, tracking the browsing
history, downloading web content,
and manipulating JSON
documents.
The internet browser function provided
by android.webkit and org.json.
C. Service oriented features
Android Developer’s Guide for bada
20
The functions for services that can be provided using the bada platform server, SNS (Social
Network Service) and LBS (Location Based Service) are provided.
bada Description Android
Osp::Commerce::Store The Commerce::Store namespace
handles commerce-related services,
such as retrieving item and purchase
information, and purchasing items from
Samsung Apps.
n/a
Osp::Locations
This class is for acquiring the positions
of local and remote devices. It provides
useful functionalities, such as area
(zone) monitoring, location tracing, and
triggering. This namespace also has
classes and interfaces for creating,
storing, and searching for landmarks
on the local device and the remote
location server
The Core Location,
MapKit and Mapview
classes.
Osp::Messaging
The scope of the Messaging
namespace accesses the messaging
capabilities of the device.
android.telephony.SmsM
essage,
android.provider.CallLog
Osp::Social
The Social namespace provides
various classes to manage the
personal data, address book and
calendar of the user. The Services
sub-namespace provides the methods
for sharing and interacting with other
users.
Android.provider.Contact
s
Osp::Ads
You can publish advertisements in
your applications. request ads from
the Samsung ad server.
External library; AdMob
2.2 Comparison of UI Controls
Android Developer’s Guide for bada
21
Android arranges viewing components with View and ViewGroup. For the arrangement, android
uses the concept of a layout which is an extension of ViewGroup.
Figure 2.3 The Android Layout (source: developer.android.com)
bada 2.0 can include Controls through the Osp::Ui::Containers and provides a layout function
through the Layout classes.
Android Developer’s Guide for bada
22
2.4 bada's UI Hierarchy
Some of the UI components are common for mobile platforms but some are unique. Therefore,
we have listed and compared the UI controls of bada that are similar to those of the Android
widget in the table below.
Android bada UI Control Description
android.View Osp::Ui::CustomControlBase The base class of all
UI controls.
android.widget.Button Osp::Ui::Controls::Buttons &
IActionEventListener
Creates the user
input button and
handles button
events.
android.widget.SeekBar Osp::Ui::Controls::Slider &
Osp::Ui::IAdjustmentEventListener i
OnCreateContextMenu()
registerForContextMenu()
Osp::Ui::Controls::ContextMenu
Osp::Ui::IActionEventListener
android.widget.DatePicker
Osp::Ui::Controls::DatePicker
Osp::Ui::IDateChangeEventListener
android.widget.TimePicker
Osp::Ui::Controls::TimePicker
Osp::Ui::ITimeChangeEventListener
android.widget.EditText Osp::Ui::Controls::EditArea
Osp::Ui::Controls::EditField
Android Developer’s Guide for
Osp::Ui::Controls::ContextMenu
Osp::Ui::IActionEventListener
This is displayed
the screen
menu of
UI control.
Osp::Ui::Controls::DatePicker &
Osp::Ui::IDateChangeEventListener
The control
enables
current date.
Osp::Ui::Controls::TimePicker &
Osp::Ui::ITimeChangeEventListener
The control
enables
date and
Unlike android,
EditDate
EditTime
provided
changed
be handled.
Osp::Ui::Controls::EditArea
Osp::Ui::Controls::EditField
The control
entering
EditArea
Android Developer’s Guide for bada
23
displayed on
screen like a sub
of the selected
control.
control that
selecting the
date.
control that
selecting the
and time.
android, the
EditDate and
EditTime items are
provided so that the
changed value can
handled.
control enables
entering text. The
EditArea enables
android.widget.LinearLayout Osp::Ui::HorizontalBoxLayout,
Osp::Ui::VerticalBoxLayout
android.widget.RelativeLayout Osp::Ui::RelativeLayout
android.widget.Gallery
Osp::Ui::Controls::Gallery
Osp::Ui::Controls::IGalleryEventList
ener
Osp::Ui::Controls::IGalleryItemProvi
der
android's on-screen keyboard. Osp::Ui::Controls::Keypad
Osp::Ui::IActionEventListener
Android Developer’s Guide for
users to
multiple
The Edit
enables
enter only
Osp::Ui::HorizontalBoxLayout,
Osp::Ui::VerticalBoxLayout
The layout
that can
controls
or vertically
screen.
Osp::Ui::RelativeLayout
The layout
that can
controls
screen on
of the relative
distance
controls.
Osp::Ui::Controls::Gallery
Osp::Ui::Controls::IGalleryEventList
ener
Osp::Ui::Controls::IGalleryItemProvi
der
A view that
items in
locked, horizontally
scrolling
users to
list by flicking.
Osp::Ui::Controls::Keypad
Osp::Ui::IActionEventListener
This is the
keyboard
Android Developer’s Guide for bada
24
to enter
lines.
EditField
users to
only one line.
ayout container
can arrange
horizontally
vertically on the
ayout container
can arrange
on the
on the basis
relative
distance from other
controls.
that shows
a center-
horizontally
scrolling list so that
to scroll image
flicking.
the input
keyboard that is
Android Developer’s Guide for bada
25
Osp::Ui::ITextEventListener
displayed on the
entire screen. This is
displayed when you
enter text in EditArea
or EditFiled.
android.widget.TextView Osp::Ui::Controls::Label Text display label
android.widget.ListView, Osp::Ui::Controls::ListViews
Osp::Ui::Controls::IListViewItemEve
ntListener
Osp::Ui::Controls::Gr
oupedListView
displays items as a
group.
Osp::Ui::Controls::Ico
nListView icon and
image.
android.widget.AlertDialog Osp::Ui::Controls::MessageBox
This is used to
display a warning or
alarm message to
users.
android.widget.AlertDialog Osp::Ui::Controls::Popup This displays a
popup message such
as a warning
message.
Android Developer’s Guide for bada
26
android.widget.ProgressBar Osp::Ui::Controls::Progress
The Progress class
displays the progress
of a lengthy
operation in a
progress bar.
android.widget.AutoCompletio
nTextView
Osp::Ui::Controls::SearchBar
Osp::Ui::Controls::ISearchBarEvent
Listener,
The control that
provides a text input
field and button and
shows the search
result for the entered
keyword.
This is similar to
android.widget.TabWidget.
Osp::Ui::Controls::TabBars
Osp::Ui::IActionEventListener
The horizontal menu
UI control that
consists of a
horizontal tab menu
bar and shows the
contents of the
Android Developer’s Guide for bada
27
selected tab below
the tab.
andrid.widget.EditText Osp::Ui::Controls::TextBox An text input field UI
control that is used to
provide lots of text.
And the following is the unique UI Framework of bada that android developers should
understand.
bada UI Control Description Android
Osp::Ui::Controls::Form The window screen on
which the UI controls are
allocated and displayed.
The indicator bar, header,
footer, and UI controls are
displayed. The form can
also function as
containers.
This is similar to the
deco view that sets the
layout in the window.
Osp::Ui::Controls::Frame
This control shows bada's
window and one or more
forms. One of the
functions of a container.
This is similar to
android.view.ViewGroup.
Osp::Ui::IColorChangeEventListener
This control enables the
user to configure the RGB
values.
The color is configured
by a combination of the
three SlideBars.
Android Developer’s Guide for bada
28
Osp::Ui::Controls::DateTimePicker
Osp::Ui::ITimeChangeEventListener
The control that enables
selecting the date and
time.
Developers should use
DatePicker and
TimerPicker by
combining them.
Osp::Ui::Controls::ExpandableEditAr
ea
This control automatically
adjusts the edit area as
the number of entered text
lines.
Developers can simulate
this function by adjusting
the EditText property.
Osp::Ui::Controls::Flash The control that can play
a Flash content.
n/a
Osp::Ui::Controls::Headers The control that enables
locating the UI controls at
the top of the screen.
By specifying the Gravity
property of the Layout,
you can use it like
Header.
Osp::Ui::Controls::Footers This control displays a
multi-purpose area at the
bottom of the screen
By specifying the Gravity
property of the Layout,
you can use it like
Footer.
Osp::Ui::Controls::OverlayRegion
This is the overlay surface
used for playing a video or
a camera preview. It
shows an image or Ui
control on the
corresponding form.
n/a. Android provides a
method to overlay the
layout using
Framelayout.
Android Developer’s Guide for bada
29
Osp::Ui::Controls::Panel UI
This is the rectangular
area of the area occupied
by the control.
Osp::Ui::Controls::ScrollP
anel is the panel that
automatically shows a
scroll bar. The panels can
also function as
containers.
This is similar to
Android.widget.ScrollVie
w.
2.3 The Lifecycle of bada and Android Applications
To start an Android application, you have to implement the Activity class. You can execute the
Service or BroadcastReceiver background process that does not have a UI, though this section
only describes an Activity. The following figure shows the lifecycle for Android and bada
applications.
Android Activity's Life Cycle bada App's Life Cycle
Figure 2.5 The Lifecycle of Android (source: applications
A. Initialization of an Android
To start an Android application, you
performs the role of the starting point
AndroidManifest.xml file of the basic
Android Developer’s Guide for
The Lifecycle of Android (source: developer.android.com) and bada
Android application
you have to register a class that inherits the activity
point to the AndroidManifest.xml file. The following
basic Android template, the HelloWorld project.
Android - AndroidManifest.xml
Android Developer’s Guide for bada
30
developer.android.com) and bada
activity that
following is the
AndroidManifest.xml
Android Developer’s Guide for bada
31
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samsung.hello"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="3" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloWorldActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In the AndroidManifest.xml file, the onCreate() method of the Activity class for which the action
of the intent-filter is android.intent.action.MAIN and the category is LAUNCHER is called and it
executes the application.
B. Initialization of a bada application
A bada application is initialized as the OspMain function in the xxxEntry.cpp file is called. The
OspMain() function is the starting point of a bada application just like the main() function in the C
language. The onCreate() method that inherits the Activity (Service, BroadcastReceiver) does
the same thing in Android.
The major methods corresponding to each life cycle stage of bada and Android are briefly
compared below. Android provides more detailed life time stages.
Android Developer’s Guide for bada
32
Android Activity's Life
Cycle
bada's Life Cycle Description
Activity.onStart()
Activity.onCreate()
OnAppInitializing( ) When an application is initialized.
Activity.onStop()
Activity.Destroy()
OnAppTerminating( ) When an application is
terminated.
Activity.onResume() OnForeground( ) When an application is switched
to foreground mode.
Activity.onPause() OnBackground( ) When an application is switched
to background mode.
PowerManager OnScreenOn( ) When the screen is turned on.
OnScreenOff( ) When the screen is turned off.
You can figure out the bada life cycle more easily by creating the HelloWorld application using a
basic template and viewing the files.
For a bada application, you can control the resources and controls of the bada application
through the following major classes provided in the Osp::App namespace.
Class Function
Application
This is in charge of the lifecycle of all applications. This provides the base
class to create an application, handles the initialization and termination of
an application, and handles system events.
AppResource This is the resource used by an application that is in charge of
localization.
AppRegistry This provides the function to load the application execution status and to
load and save the contents being used by the application.
C. Starting an Android application
In Android, an Activity that is registered to AndroidManifest executes the life time method that is
provided by the Activity according to the life cycle stage. The onCreate() method attaches the
Android Developer’s Guide for bada
33
View of the Activity to the Android phone screen. Using the setContentsView(R.layout.main)
method, you can display the screen UI controls that will be described In the following section.
Android - HelloWorld.java
public class HelloWorldActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onClick(View arg0) {
finish();
}
}
D. Starting a bada application
In the bada platform, the HelloWorld class created in the HelloEntry.cpp which is the application
starting point, provides the CreateInstance( ) method that handles basic application operations.
In the HelloWorld.h file, you will be able to view the following source code.
bada - HelloWorld.h
#ifndef _HELLOWORLD_H_
#define _HELLOWORLD_H_
#include<FApp.h>
#include<FBase.h>
#include<FSystem.h>
Android Developer’s Guide for bada
34
#include<FUi.h>
/**
* The [HelloWorld] application must inherit from the Application class
* which provides the basic features necessary to define an application.
*/
classHelloWorld :
public Osp::App::Application,
public Osp::System::IScreenEventListener
{
public:
// The [HelloWorld] application must have a factory method that creates an instance of
itself.
static Osp::App::Application* CreateInstance(void);
public:
HelloWorld();
~HelloWorld();
public:
// Called when the application is initializing.
boolOnAppInitializing(Osp::App::AppRegistry& appRegistry);
// Called when the application is initializing.
boolOnAppTerminating(Osp::App::AppRegistry& appRegistry, bool forcedTermination
= false);
// Called when the application's frame moves to the top of the screen.
voidOnForeground(void);
// Called when this application's frame is moved from the top of the screen to the
background.
voidOnBackground(void);
// Called when there is insufficient system memory to run the application any further.
voidOnLowMemory(void);
// Called when the battery level changes.
voidOnBatteryLevelChanged(Osp::System::BatteryLevel batteryLevel);
Android Developer’s Guide for bada
35
// Called when the screen turns on.
voidOnScreenOn (void);
// Called when the screen turns off.
voidOnScreenOff (void);
};
#endif
If the actual application life cycle begins as the CreateInstance() function is called in the
instance of the HelloWorld class, the OnAppInitialize(), OnForground() and OnTerminate()
functions are called in this order.
The above HelloWorld class inherits the Osp::App::Application class. This is similar to inheriting
the Activity class in Android. In addition, bada provides single inheritance and multiple interface
implementations like the object oriented concept of Java (unlike C++). Therefore, all user events
that inherit the Osp::App::Application and interact with the user are declared and implemented
as Interfaces.
E. Android application UI
The onCreate() method reads the setContentsView(R.layout.main) layout xml and displays the
screen UIs. In the following table, the left pane shows the Android's res/layout/main.xml layout
definition file and the right pane shows the result that is displayed on the screen.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
Android Developer’s Guide for bada
36
/>
</LinearLayout>
F. The bada application UI
bada provides Controls to arrange them on a Form. To view how to handle the UI Form in the
HelloWorld project, see the Form1 class. The Form1 class has the OnInitializing( ) and
OnTerminating( ) methods and virtual methods such as OnActionPerformed( ) that inherit the
Osp::Ui::IActionEventListener interface. Using these event handlers, a bada application can
handle events.
bada - Form1.h
#ifndef _FORM1_H_
#define _FORM1_H_
#include <FBase.h>
#include <FUi.h>
class Form1 :
public Osp::Ui::Controls::Form,
public Osp::Ui::IActionEventListener
{
// Construction
public:
Form1(void);
virtual ~Form1(void);
bool Initialize(void);
// Implementation
protected:
static const int ID_BUTTON_OK = 101;
Osp::Ui::Controls::Button *__pButtonOk;
Android Developer’s Guide for bada
37
public:
virtual result OnInitializing(void);
virtual result OnTerminating(void);
virtual void OnActionPerformed(const Osp::Ui::Control& source, int actionId);
};
#endif //_FORM1_H_
The method that is implemented by re-defining a virtual method to perform the necessary
initialization processes and is called when a Form is initialized is the OnInitializing( ) method. In
general, the OnInitializing( ) method performs the initialization for a Form. The termination of a
Form is processed in the OnTerminating( ) method.
G. User event handling
Android handles user events using an event listener. bada also uses terms and mechanisms
similar to those of Android.
Android bada Description
android.view.OnClickListen
er
Osp::Ui::IActionEventListener Notifiesbasic events
android.view.OrientationEv
entListener
Osp::Ui::IOrientationEventListene
r
Notifies screen
orientation change
events
android.view.OnTouchEve
ntListener
Osp::Ui::ITouchEventListener Notifies user touch
events
android.view.OnFocusCha
ngeListener
Osp::Ui::IFocusEventListener Notifies focus events
2.4 Application Interface Design
Android Developer’s Guide for bada
38
bada UI controls handle touch events in a similar way to Android and provide various event
listener interfaces. In addition, multi-touch and gestures such as tap, double tap and drag &
drop are supported.
2.5 UI Design Tool for Developer’s Convenience
bada and Android provide the development environment to design UI components on the basis
of xml. The following table compares the screen size and UI design methods related to UIs.
Function bada Android
UI design tools UI Builder Layout editor
Supported
screen
resolutions
320x480, 240x400, 480x800 2.7~10.1" screen
240x300 ~ 1280x800
Features UI Builder manages xml
resources .
include, merge and fragments are
supported.
UI type Form XML
C++ code
layout xml
View, ViewGroup classes
Android Developer’s Guide for bada
39
XML resources
The xml resources provided by the res folder in Android are layout, menu, color, drawable,
dimensions, string-array and string. And the folder has sub folders considering localization (e.g.
values-kr/string.xml).
In bada, xml resources are managed through the UI Builder. You can create a Form and
manage resources such as menus and strings through the UI Builder. Of course, you can
access or add the resources in the source code.
2.6 Threads
Sometimes an application should perform multiple jobs at the same time. For example, a text
editor needs to save the document periodically while performing editor functions and it needs a
new technique other than multitasking. In this case, multithreading is used.
Android supports multitasking through multithreading. This is supported through Java’s
traditional thread support classes, the java.lang.Thread and Runnable interfaces. In addition,
developers can use C or C++ using NDK (Native Development Kit), and pthread (POSIX) in the
standard C library is also available.
bada’s thread is supported by the Runtime namespace. Since bada 2.x, pthread (POSIX Thread)
in the standard C library which is widely used in UNIX and Linux is also provided so that
developers can create and synchronize threads according to the standard method in UNIX.
Android Developer’s Guide for bada
40
Figure 2.6 The bada’s Runtime Namespace
The timer provided by the Runtime namespace is provided by the Timer class that handles the
jobs that are to be executed periodically. To handle periodic jobs, you can use the
Osp::Base::Runtime::ITimerEventListener.
class TimerApp : public ITimerEventListener
{
\\
};
ITimerEventListener has the OnTimerExpired(Timer &timer) event handler. If you run the timer,
the event handler is called according to the configured period of time. Then, you can execute
your selected job in the event handler.
void TimerApp::OnTimerExpired(Timer& timer)
{
...
timer.Start(1000);
}
To handle threads in bada, you can use the Thread class. IRunnable is the base class of a
thread. bada provides 2 types of threads. One is an Event Driven Thread that is executed by
events or asynchronous calls to the listener and the other is a Worker thread.
Android Developer’s Guide for bada
41
To use threads in bada, define a class that inherits the Thread or IRunnable class.
class ATask: public Object, public IRunnable {
\\.
void* Run( void ) { /* a thread job */ }
\\.
};
You have to implement the OnStart(), Run() and OnStop() methods for the class above.
\\.
Thread* thread = new Thread;
ATask* task = new ATask;
thread->Construct( *task );
thread->Start(); // starting thread
\\.
You implement a Worker class, inherit the Thread and specify the THREAD_TYPE_WORKER
option when constructing the thread.
class AThread : public Thread {
\\.
// Constructor
result Construct(void) {
return Thread::Construct(THREAD_TYPE_WORKER);
}
// test if the thread can run, and return
bool OnStart(void) { .......... return true; }
// finalize thread
void OnStop(void) { ... }
// main thread body
void* Run(void) {
Android Developer’s Guide for bada
42
// Infinite loop will be terminated by calling Exit()
// or heavy job that returns
return null;
}
\\.
};
To create a Timer Event Driven Thread, specify the class to inherit the ITimerEventListener
interface and specify THREAD_TYPE_EVENT_DRIVEN when constructing the thread.
class AThread : public Thread, public ITimerEventListener {
\\.
// Constructing the thread as an event driven one
result Construct(void) { return
Thread::Construct(THREAD_TYPE_EVENT_DRIVEN); }
// Registering a timer at on start
bool OnStart(void) {
Timer timer;
timer.Construct(*this);
timer.Start(10);
return true;
}
void OnStop(void) { timer.Cancel(); } // Asynchronous function
void OnTimerExpired( Timer& timer ) {
timer->Start(10);
\\.
}
};
bada also provides a synchronization mechanism. When you use multithreading, a mechanism
to restrict access to shared resources by threads is required. You can prevent a shared
Android Developer’s Guide for bada
43
resource from being changed by another thread using synchronization mechanisms such as a
semaphore.
The representative synchronization method is semaphore. Semaphore was developed by
Edsger Wybe Dijkstra. If you specify the number of threads to allow access as an argument
when you construct a semaphore object, the number of threads that can access the resource is
restricted. In bada, you can use a semaphore using the Semaphore class.
Mutex is a synchronization mechanism to prevent simultaneous resource access competition
between threads. Mutex can be regarded as a special case of semaphore with a counter value
of 1 so that only one thread is allowed to access the resource at a time. In bada, you can use
Mutex using the Mutex class.
Monitor is a binary lock that prevents multiple threads from changing the same resource object
and manages a Critical Section. bada provides the Monitor class so that you can use the
Monitor synchronization mechanism.
2.7 Multitasking
Android supports multitasking from version 1.0, and the multitasking feature is Android's main
strength. High quality applications can be created with multitasking features such as an Alarm
using a Service or BroadcastReceiver functions. An Activity’s status can also be stored
according to the activity’s lifecycle, allowing the multitasking of several activities easily.
bada supports multi tasking from bada 2.0. In bada, although users can run multiple applications
at the same time, only one application runs in the Foreground. To use the multitasking feature in
background mode, you have to configure the multitasking function for bada applications.
Multitasking has a very close relationship with memory use. The multitasking of applications
may stop if the user presses the Stop key or the memory becomes full.
Android Developer’s Guide for bada
44
3. Event Handling System comparison between bada and
Android
3.1 Event Handling in Android and bada
In the Android platform, developers develop widgets on the screen using the Java language on
the Dalvik virtual machine. For this reason, Android is using an advanced event handling
mechanism on the Java Swing. User events are used to handle user's actions by implementing
an event listener. The event listener is registered to the system message queue of the Android
system which is called a Looper, and if a user action occurs, the corresponding event message
is removed from the message queue and the event is handled in the method implemented as
EventListner.
The bada platform also provides an event handling system like other platforms. The bada
platform also handles events using an event listener.
Since bada's event listener interface consists of pure virtual functions, you have to inherit the
Listener interface and implement the event handler method. This is very similar to the
implementation of the interface in Android. As described above, since bada supports single
inheritance and multiple implementation, you have to inherit the Application of Osp::App and
implement and use the listener that is declared as an interface.
You may experience the user event handling in the screen controls as similar to that in Android.
In Android, to handle the user events of widgets, events are entrusted to the event listeners
such as OnClickListener and OnTouchListener. This Android's event handling mechanism can
be handled using event listeners like bada.
For example, you can use the IActionEventListener event listener for a Button. For a List, you
can use the IItemEventListener event listener. You can register these event listeners to each
control.
An Android widget is generally used to show information to users or to fetch information
configured for the current control. As shown below, if there is a Button widget in the layout, you
can use this widget as an object in the Java code in Android.
<?xml version="1.0" encoding="utf-8"?>
Android Developer’s Guide for bada
45
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
<Button android:text="Button"
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"></Button>
</LinearLayout>
// The code to get the widget ID button1 in res/layout/main.xml file.
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
bada also provides a similar concept. You can use the controls added in the UI Builder in the
source code using the GetControl( ) method of the Osp::Ui::Container class. To distinguish the
controls added to the form and bring them to the source code, unique IDs for the controls that
have been added in the UI Builder are necessary. You can set the ID using the Properties tab of
the UI Builder.
For example, let’s create a code to locate a label and change the string on the label in the UI
Builder.
First, locate the label on a Form in the UI Builder.
Figure
After arranging the Label on the
as shown below. Through the “(Name)”
in the source code.
In the figure above, the “(Name)”
several important naming rules: Form
start with IDC_(ID of Control). String
described later.
Using the properties, you can refer
Label *pLabel = static_cast<Label*>(GetControl(L"IDC_LABEL1"));
if(pLabel != null) {
pLabel->SetText(L"OOPS!!");
Android Developer’s Guide for
Figure 3.1 Label located on a Form
Form, you can see the “(Name)” property in the
“(Name)” property, you can refer to the controls of
Figure 3.2 (Name) Property
“(Name)” property is set to IDC_LABEL1. In the bada platform,
Form names start with IDF_(ID of Form) and control
String names start with IDS_(the ID of the String)
refer to a control in the Form in the source code as
bada – Form1.cpp
static_cast<Label*>(GetControl(L"IDC_LABEL1"));
SetText(L"OOPS!!");
Android Developer’s Guide for bada
46
the Properties tab
of the UI Builder
platform, there are
control names
which will be
as shown below.
Form1.cpp
Android Developer’s Guide for bada
47
RequestRedraw();
}
In the source code above, the GetControl( ) method that is described above is used to access
the Label control arranged in the UI Builder and the (Name) “IDC_LABEL1” of the UI Builder is
used as an argument for the GetControl( ) method. The bada platform also uses Unicode for
Strings internally like Android. In Android, ASCII code char types are treated as integer types
and a string is enclosed with """ to distinguish its type. In the bada platform, the ASCII code and
Unicode are distinguished by attaching the "L" prefix in front of """. Strings with the “L” prefix can
be handled by bada’s String class.
If the Label control is not Null, you can set the string for the Label using the SetText( ) method.
Android uses the “set + property_name” notation for the set method for a property and “get +
property_name” for the get method for a property.
Whereas Android uses the “set/get + property name” notation for the set/get method, the bada
platform uses the “Set/Get + property name” notation that starts with a capital letter.
The bada platform uses the GetText( ) method to get the text string from the Label control and
uses the SetText( ) method to set the text string. Since the bada platform has a consistent
naming method to access properties, if you know the property name, you can easily analogize
the corresponding method name.
In the bada platform, even if a text string is set for a label, the text string is not immediately
displayed on the screen unlike in Android. So there is a need to refresh the screen. To refresh
the screen, the RequestRedraw( ) or Draw( ) and Show() methods should be called. The reason
for this is that refreshing the screen overloads the embedded system or mobile device.
Therefore, if there is more than just screen related code, the screen is refreshed only once after
the completion of this type of code in bada. However, you can manually refresh the screen by
calling the RequestRedraw( ) method.
Each control has a unique individual event handler. This information will be described in detail in
bada’s Controls in the next chapter.
Android Developer’s Guide for bada
48
3.2 Low Level Touch Events
Whereas Android handles events using a message queue (event queue) that is managed by a
Looper, the bada platform also provides a similar event handling system.
Figure 3.3 Android's Looper and MessageQueue (source: Google IO of 2008)
The most important events from among these events are screen touch events. Screen touch
events are the most basic functions for interactions between users and mobile phones and are
the most important functions that should be provided by every mobile platform.
In Android, if the screen is touched, the class that implements the Activity.onTouchEvent and
View.OnTouchListener interfaces provides one screen touch related method and the
MotionEvent class provides 5 touch action modes.
Method Description
MotionEvent.ACTION_DOWN; This is called when a touch event
occurs on the screen.
MotionEvent.ACTION_UP This is called when the finger is
removed from the screen (when the
touch has ended.)
MotionEvent.ACTION_MOVE This is called when a user touches the
screen and moves their finger while
touching the screen.
MotionEvent.ACTION_CANCEL This is called when the touch is
Android Developer’s Guide for bada
49
cancelled by the system.
MotionEvent.ACTION_OUTSIDE This is called when the touch moves
outside the widget.
The bada platform also provides the Osp::Ui::ITouchEventListener event listener so that touch
events can be handled like in Android. The ITouchEventListener provides the following virtual
functions.
Android bada Description
N/A OnTouchDoublePressed This is called when the user
touches twice
consecutively.
View.OnFocusChangeListener OnTouchFocusIn This is called when the
focus is obtained.
View.OnFocusChageListener OnTouchFocusOut This is called when the
focus is lost.
N/A OnTouchLongPressed This is called when the user
touches and holds for a
long time.
View.OnTouchListener OnTouchMoved This is called when the user
touches and then moves.
View.OnTouchListener OnTouchPressed This is called when the user
touches.
View.OnTouchListener OnTouchReleased This is called when the user
releases the touch.
Since the above virtual functions basically process events, they return void type data and
provide the parameters for the control that generates the event (const Osp::Ui::Control &source),
the location of the touch (const Osp::Graphics::Point ¤tPosition), and information about
the touch event (const Osp::Ui::TouchEventInfo &touchInfo) that occurred.
Android Developer’s Guide for bada
50
3.3 Screen Orientation Handling
Since users can rotate the screen of a mobile device unlike the screen of a desktop computer, a
platform should provide a function to handle the screen orientation.
In Android, you can define whether the rotation function is supported or not and the rotation
setting is in the AndroidManifest.xml file. In addition, you can detect the physical orientation
change using OrientationEventListener(Context context) that detects whether the screen
orientation has been changed using the sensor in an Activity. The
OrientationEventListener.canDetectOrientation() method evaluates whether the screen
orientation can be changed using the sensor and the
OrientaionEventListener.onOrientationChanged() method detects the changed orientation.
In the bada platform, like in Android, to provide the rotation function to a Form, you can
configure the orientation to be supported in the UI Builder. If you select a form in the UI Builder
and view the setting, you will be able to find the Orientation Mode property. Using this property,
you can configure the basic settings for the orientation of the form and fix the orientation.
Figure 3.4 Form orientation related property (Orientation Mode)
In addition to supporting the orientation function for a form, the functions to move the controls on
the form are necessary.
In addition, like for Android, the bada platform provides a similar screen orientation event
listener that runs on the basis of the sensor hardware in the bada platform, and you can use the
Osp::Ui::IOrientationEventListener event listener and the OnOrientationChanged( ) virtual
function.
Android Developer’s Guide for bada
51
The OnOrientationChanged( ) virtual function uses the 2 parameters of the control that called
the event (const Osp::Ui::Control &source) and the information about the rotation information
(Osp::Ui::OrientationStatus orientationStatus). In the bada platform, you can figure out the
direction of the orientation through the Osp::Ui::OrientationStatus method. The detailed usage is
described below.
In Android, the int argument of the OrientationEventListener.onOrientationChanged(int) method
delivers a value between 0 and 359 so that the rotation can be identified on the basis of the
value.
3.4 Animation
The animation automatically processes the movement of a Control. Only if you set the first and
last steps of a multiple step (key frame) animation, are all the other steps automatically
generated.
Figure 3.5 Animation
Android adds various effects to a View using the animation function. For animations, the frame-
by-frame method that displays an image on the screen periodically and the tweend-animation
method that moves, resizes and rotates an image on the screen are used. They are provided in
the android.animation package.
bada 2.0 provides the Osp::Ui::Animations namespace to process animations. bada’s animation
has 3 components. The three components are the Start value, the Key value, which is the key
property value for the animation, and the End value. Using the following key property values, to
control the animation time and interpolation.
Android Developer’s Guide for bada
52
Property Value Description
ANIMATION_INTERPOLATO
R_LINEAR
The interpolation speed is constant.
ANIMATION_INTERPOLATO
R_DISCRETE
The acceleration is changed discretely
ANIMATION_INTERPOLATO
R_EASE_IN
It starts slow and then becomes faster.
ANIMATION_INTERPOLATO
R_EASE_OUT
It starts faster and becomes slower at the end.
ANIMATION_INTERPOLATO
R_EASE_IN_OUT
It starts slow, becomes faster and then becomes slower
at the end.
ANIMATION_INTERPOLATO
R_BEZIER
It supports acceleration in the form of a Bezier curve.
Figure 3.6 bada’s Animation Interpolation Acceleration
3.5 Event Injector
Android provides an emulator so that developers can test and run applications. The bada
platform also provides functions to run a developed application. The bada SDK 1.x version
provides a simulator and the bada SDK 2.0 version provides an emulator so that developers can
test the application functions in an environment that is more similar to the target device.
Android Developer’s Guide for bada
53
Although the Android emulator provides basic functions to test applications and simulate
rotations and memory full situations through DDMS provided by the ADT plug, it does not
provide functions to test the camera or the GPS sensor in more detail.
Figure 3.7 Calling the Event Injector in the simulator
bada IDE’s emulator provides an event injector so that developers can test the camera using
the PC’s USB web cam and the test sensors in detail.
To test an event in bada, right-click on the emulator to open the popup menu, and select Event
Injector from the popup menu. The Event Injector window will appear.
Figure 3.8 Event Injector
Android Developer’s Guide for bada
54
The Event Injector window provides tabs where developers can test Call, Network, Messaging,
Sensor and Device events.
The direct testing sensor functioning in a terminal takes a long time in particular.
However, using an Event Injector, you can save a considerable amount of testing time and
perform more sophisticated tests because developers can specify a sensor value directly (e.g.
33.1” of rotation).
4. Data Types comparison
4.1 Primitive Data Types
Since bada basically uses C++ uses,
along with standard C/C++ libraries
that the data can have a unique size
4.2 Wrapper Classes for Primitive Types
In general, bada’s classes inherit
generally included in the Osp::Base
primitive data types can be implemented
types and the corresponding classes.
Figure
Android Developer’s Guide for
Data Types comparison between bada and Android
Primitive Data Types
uses, you can use the primitive date types of the
along with standard C/C++ libraries. bada provides the more detailed primitive data
size in each platform.
Wrapper Classes for Primitive Types
inherit bada’s base class, the Object class. Base classes
Osp::Base namespace. In this type of object oriented languages,
implemented as classes with wrapper class that connects
classes.
Figure 4.1 bada’s Primitive Data Types
Android Developer’s Guide for bada
55
between bada and Android
the C++ language
data types so
classes are
languages, the
connects primitive
Android Developer’s Guide for bada
56
Although character type data in general can be processed using the char data type of the C
language, you can use the wrapper class for the primitive type mchar, the Character class. The
Character class provides methods to handle Unicode.
bada provides the Number class to handle numeric data. The major classes that inherit this
class are as follows.
Class Description
Double The wrapper class for the primitive type signed double.
Float The wrapper class for the primitive type signed float.
LongLong The wrapper class for the primitive type signed longlong.
Long The wrapper class for the primitive type signed long.
Integer The wrapper class for the primitive type signed integer.
Short The wrapper class for the primitive type signed short.
Int8 The wrapper class for the primitive type signed char.
Using these classes, you can handle data more easily than when you use the primitive data
types of the C language.
4.3 String Classes
In general, the C language handles character strings using a char type array or pointer.
However, the char* type has problems in handling multi-languages for localization. To solve this
problem, Java provides the java.lang.String class so that strings can be defined as an
enumeration of the codes that are defined in a character set.
The String class enables saving and modifying Unicode character strings. A String object has a
size of 16 bytes by default and can be expanded up to 232-1 characters.
To handle the String data type, you can use the classes provided by the string class of
Osp::Base::Util namespace of bada. The StringUtil class provides various string processing
functions so that developers can handle strings more easily. The StringTokenizer class provides
string analysis functions.
Android Developer’s Guide for bada
57
Android String class bada String class
Meaning Unicode character string A mutable sequence of 16bit Unicode
characters
Create String
From character
char data[] = {'a', 'b', 'c'};
String str = new String(data);
// From a C string
char *pStr = "ABC";
String str(pStr);
From string
String str = new String(“Test”);
String str = “one,two,three”;
// From a Unicode string
String str1(L"test");
String str = L” one,two,three”;
From another
string
Strig str = “test”;
String str2 = new String(str);
// From another string
String* str2;
str2= "Hello";
String str3(str2);
From Unicode
String str = “\u0041”; // A
// From Unicode characters
mchar chr = L‘A’;
String str4(chr);
From Arrays
String[] aStr = {“One”, “Two”,
“Three” };
// String array
String aStr[3] = {“One”, “Two”,
“Three” };
initializing a
String
String str = new String(“test”);
String str(L"test");
append String str += “ String”; str.Append(L" String"));
to Upper case
letters
str.toUpperCase(); str.ToUpper();
to Lower case
letter
str.toLowerCate(); str.ToLower();
insert string n/a str.Insert(L" abc", 0);
Android Developer’s Guide for bada
58
rim the space str.trim(); str.Trim();
replace string str.replace(“one”, “One”);
mchar chr1 = ‘L’t;
mchar chr2 = ‘L’u;
str.Replace(chr1, chr2);
reverse n/a str.Reverse();
substract subStr = str.substring(7,4); String subStr;
clear str = “”; str.SubString(7, 4, subStr);
str.Clear(); // ""
4.4 String Tokenizing
Android generally uses the java.lang.StringTokenizer class to break a string down (tokenize). In
addition, the String.split() method provides the same function. bada provides the
Osp::Base::Utility::StringTokenizer class so that developers can handle strings more easily.
Android String tokenizer bada String tokenizer
String str = “Android/bada”;
StringTokenizer st = new
StringTokenizer(str, “/”);
while(st.hasMoreTokens()) {
String token = st.nextToken();
}
String str(L"Android/Bada");
String delim(L"/");
StringTokenizer st(str, delim);
int count = st.GetTokenCount();
String token;
while(st.HasMoreTokens()) {
st.GetNextToken(token);
}
4.5 Date and Time Classes
Android's java.util.Date class supports the Gregorian calendar and returns the date and time on
the basis of the milliseconds from 00:00:00.000, January 1, 1970 (GMT). For the date, the
Android Developer’s Guide for bada
59
Gregorian calendar is supported. The Java.util.GreogorianCalendar class provides the actual
date and time for the currently configured locale. You can acquire a specific date and time
using the corresponding fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR.
bada provides the DateTime class for handling date related data types. The DateTime class is
used to process the date and time from January 1, AD 1 00:00:00 to December 31, AD 9999
23:59:59. The DateTime returns a human readable date directly: hours, minutes, seconds, day,
month, year, and so on. In addition, when the time needs to be calculated in seconds, the
TimeSpan class displays the time in milliseconds.
The Osp::Locales::TimeZone and Osp::Locales::Calendar classes enables applications to
calculate the date and time. Each field of the Calendar is defined in Osp::Locales::TimeField as
the Enum type so that developers can get the values of each field using the Calendar-
>GetTimeField() method. In addition, just like Java, Osp::Locales::GregorianCalendar provides
a calendar that can be used worldwide.
Using the date and time classes, you can easily calculate the date and time.
• Convert between a DateTime instance and a Calendar instance
• Compare 2 Calendar instances
• Get part or all of a date or time
• Do date and time arithmetic
The source code examples to get the current date and time in Android and bada are listed
below.
Android
bada
Current
Date
Setting
Calendar cal =
Calendar.getInstance();
cal.get(Calendar.YEAR);
cal.get(Calendar.MONTH);
cal.get(Calendar.DATE);
DateTime CurDateTime;
SystemTime::GetCurrentTime(CurDateTime);
_pCal = Calendar::CreateInstanceN();
_pCal->SetTime(CurDateTime);
_pCal->GetTimeField(TIME_FIELD_YEAR);
_pCal->GetTimeField(TIME_FIELD_MONTH);
_pCal>GetTimeField(TIME_FIELD_DAY_OF_
Android Developer’s Guide for bada
60
cal.get(Calendar.AM_PM);
cal.get(Calendar.HOUR);
cal.get(Calendar.MINUTE);
cal.get(Calendar.SECOND);
MONTH
);
pCal>GetTimeField(TIME_FIELD_AM_PM);
pCal>GetTimeField(TIME_FIELD_HOUR);
pCal>GetTimeField(TIME_FIELD_MINUTE);
pCal>GetTimeField(TIME_FIELD_SECOND);
Specific
Date
Specificatio
ns
Calendar cal = new
GregorianCalendar(2011,10,1);
_pCal->SetTime(2011,10,1);
TimeZone TimeZone tz =
TimeZone.getTimeZone("America
/Los_Angeles");
Cal.setTimeZone(tz);
TimeZone timeZone(60, L"Europe/Paris");
_pCal->SetTimeZone( timeZone);
4.6 Collection Classes
To handle multiple data items, you can define and use an array in the traditional way. However,
array data type is difficult to add or delete data dynamically. The classes used to resolve this
problem are called Collection classes. Android provides such collection data handling functions
through ArrayList, HashSet and LinkedList through the java.util.Collection interface provided by
the Java language. In addition, java.util.Map provides functions to collect data on the basis of
the key-value structure that is called a set. The enumerative data structures of Java 6 are listed
below.
Data Structure Class
List ArrayList LinkedList (Vector)
Stack LinkedList (Stack)
Queue LinkedList
Hash Table HashMap
Set HashSet
The bada framework also provides
Osp::Base::Collection namespace
collections. A collection has a set
elements. They allow you to operate
bada provides various data structures
stacks and so on. bada provides
MultiHashMap and MapEntry data
IMultiMap, IMapEnumerator, IHashCodeProvider
types.
Figure
The ArrayList data structure
The ArrayList and LinkedList classes
an Index. The two data structures
Android Developer’s Guide for
HashMap (Hashtable)
HashSet
provides various data structures just like Android. The
namespace contains classes and interfaces that define various
set of operations which reflect the relationships among
operate on similar kinds of objects simultaneously.
structures through Osp::Base::Collection such as arrays,
the Stack, Queue, ArrayList, LinkedList, HashMap,
data types and provides the ICollection, IEnumerator,
IHashCodeProvider and IComparer interfaces to handle
Figure 4.2 bada’s Collection Data Types
structure
classes are data structures that enable managing a
structures are similar but the saving methods are different.
Android Developer’s Guide for bada
61
The
various
among the
arrays, lists,
HashMap,
IEnumerator, IList, IMap,
handle the data
a list of data with
different.
Android Developer’s Guide for bada
62
The ArrayList class saves data in continuous space to the physical memory. For an ArrayList
class object, data can be read fast but deleting or inserting data is slow. Therefore, it is
appropriate for data that is frequently read with a rare deletion or insertion. The LinkedList class
saves data using a link. Since inserting or deleting data is fast but reading data is slow, this data
structure is appropriate for cases that require frequent data modifications (insertion and
deletion).
Android bada
Initialize ArrayList<Integer> listNumber = new
ArrayList<Integer>(30);
ArrayList listNumber;
ArrayList listString;
int listCapacity = 30;
Add listNumber.add( new Integer(1));
listNumber.add( new Integer(2));
listNumber.add( new Integer(3));
listNumber.Construct(listCapacity);
listNumber.Add(*(new Integer(1)));
listNumber.Add(*(new Integer(2)));
listNumber.Add(*(new Integer(3)));
Delete list.remove( new Integer(1));
list.remove(2);
Integer* pValue1 = new Integer(1);
listNumber.Remove(*pValue1, true);
listNumber.RemoveAt( 0, true);
While the ArrayList and LinkedList classes access data with an index, the HashMap and
MultiHashMap classes access data with a key and a value. For a MultiHashMap, the same key
can be used more than once and the key in the “key-value” pair can be duplicated. However, for
a HashMap, the same key cannot be used.
4.7 Data Types comparison between bada and Android
In general, a Control refers to a component on the screen used to interact (input and output)
with the user. In Android, these components are called Widgets. Every Android widget is
implemented by inheriting the android.view.View class.
In bada, the namespace for Controls is Osp::Ui::Controls. Basically, bada’s Controls inherit the
Controls class. In general, touch-based smartphones should handle touch events by users. This
is called event handling. You can handle the events using UI Controls.
In general, Controls are classified
that receive information from users.
called a Label. The representative
the Controls that provide information
should just show information, the
handler to handle events.
4.8 Button Controls
In general, in Windows and in mobile
through the mouse or by touch. The
interface is a Button.
Android provides the android.widget.Button
button click events by implementing
the Osp::Ui::Control::Button class.
Osp::Ui::IActionEventListener.
Figure 4.3 Various applications of bada's Button control The IActionEventListener interface
events.
virtual void Osp::Ui::IActionEventListener::OnActionPerformed(
const Osp::Ui::Control &
Android Developer’s Guide for
classified into Controls that provide information to users
users. The representative Control to provide information
representative Control to receive data from users is called a
information to users do not need to handle events because
the Controls to receive data from users should use
mobile operating systems, the system interacts with
The most representative Control used for a touch
android.widget.Button class for handling buttons. Developers
implementing android.view.OnClickListener. In bada, developers
class. To handle a button event, you can use the
Various applications of bada's Button control
interface provides the OnActionPerformed virtual function
Osp::Ui::IActionEventListener::OnActionPerformed(
& source, int actionId)
Android Developer’s Guide for bada
63
users and Controls
information to users is
Button. While
because they
use an event
with users
touch-based
Developers handle
developers can use
function to handle
Android Developer’s Guide for bada
64
The first argument is the instance of the event source that can be used to identify the Control
that causes the event and the second argument is the Action ID of the action event of the
Control.
The following is a part of the ButtonSample.h header file.
class ButtonSample :
public Osp::Ui::Controls::Form,
public Osp::Ui::IActionEventListener
{
protected:
static const int ID_BUTTON = 101;
static const int ID_BITMAP_BUTTON = 102;
public:
virtual result OnInitializing(void);
virtual void OnActionPerformed(const Osp::Ui::Control& source, int actionId);
};
When you create a button, you have to set the Action ID of the button that will be used by the
OnActionPerformed( ) event handler.
In the ButtonSample.cpp that implemented the header, you can view how to construct a button
object. If the button above is touched, the event listener registered by the
AddActionEventListener( ) method is called. Since the current class (this) is specified as the
event listener in the source code above, the current class must have inherited the
IActionEventListener interface.
#include "ButtonSample.h"
result ButtonSample::OnInitializing()
{
// Create a Button
Button* pButton = new Button();
Android Developer’s Guide for bada
65
pButton->Construct(Rectangle(50, 50, 150, 150), L"Button");
pButton->SetActionId(ID_BUTTON);
pButton->AddActionEventListener(*this);
AddControl(*pButton);
return r;
}
// Implement an IActionEventListener
void ButtonSample::OnActionPerformed(const Control& source, int actionId)
{
switch (actionId)
{
case ID_BUTTON:
String str = (Button*)source.GetText();
break;
default:
break;
}
}
If the button above is clicked, the event listener OnActionPerformed( ) is automatically called
and the ID_BUTTON_ACTION value is set as the Action ID. To directly access the Button
object that called the event, you can use the source argument in the source code above.
4.9 List Controls
Android provides enumeration type widgets such as android.widget.ListView / GridView /
Gallery to represent the same type data. In addition, Android provides methods to display data
on a specific location of a layout using Adapter interface and the above widgets. In addition, if
the user selects a selection widget to handle the event, you can implement
android.widget.AdapterView.OnItemSelectedListener.
bada also provides similar controls through the Osp::Ui::Controls namespace. bada provides
various list view classes including ListView (List, CustomList, ExpandableList, SlidableList in
Android Developer’s Guide for bada
66
bada 1.x), IconListView (IconList in bada 1.x) and GroupedListView(GroupedList,
SlidableGroupedList in bada 1.x) to support various types of lists.
The List Control of bada 1.x provides the Osp::Ui::IItemEventListener interface to handle the
selection of an item.
The IItemEventListener interface provides the OnItemStateChanged( ) virtual function to handle
events of lists.
virtual void OnItemStateChanged (const Osp::Ui::Control &source, int index,
int itemId, Osp::Ui::ItemStatus status)
The first argument is the instance of the event source that can be used to identify the Control
that causes the event, the second argument is the index of the selected item, and the third
argument is the ID of the called item. The fourth argument is the status of the item.
The item status can be one of the following.
Status Descriptions
ITEM_CHECKED The state that the item has been checked (selected).
ITEM_UNCHECKED The state that the item has been unchecked
(unselected).
ITEM_SELECTED The state that the item has been selected.
Figure 4.4 Various applications of bada's List
Android Developer’s Guide for bada
67
To add an item to the list, you can use the AddItem( ) method. When you add an item, you have
to set the ID of the item to be used in the OnItemStateChanged( ) event handler. In general, if
you use a database, and you set the database key as the item ID, the OnItemStateChanged( )
event handler can receive the database key, fetch the data from the database and display it
easily.
// ID for the Item
static const int ID_ITEM0 = 301;
static const int ID_ITEM0 = 302;
// Create List
List* pList = new List();
pList->Construct(Rectangle(0, 0, 480, 800), LIST_STYLE_NORMAL,
LIST_ITEM_SINGLE_TEXT, 50, 0, 480, 0);
pList->AddItemEventListener(*this);
// Create item For List
String item(L"Item");
pList->AddItem(&item, null, null, null, ID_ITEM0);
pList->AddItem(&item, null, null, null, ID_ITEM1);
Android Developer’s Guide for bada
68
If the items above are touched, the event listener registered by the AddActionEventListener()
method is called. Since the current class (this) is specified as the event listener in the source
code above, the current class must have inherited the IItemEventListener interface.
void ExampleClass::OnItemStateChanged (const Osp::Ui::Control &source,
int index, int itemId, Osp::Ui::ItemStatus status){
switch (itemId) {
case ID_ITEM0:
// Todo:
break;
case ID_ITEM1:
// Todo:
break;
default:
break;
};
}
If an item of the list is selected, the OnItemStateChanged( ) event handler is automatically
called, and either the ID_ ITEM0 or the ID_ ITEM1 value is set to the Item ID. The order of the
currently selected item in the list is set to the argument index.
For the CustomList and ExpandableList items, the Osp::Ui::ICustomItemEventListener and
Osp::Ui::IExpandableItemEventListener interfaces are provided respectively.
bada 2.0 provides the ListView Control instead of a List. The
Osp::Ui::Controls::IListViewItemEventListener interface is provided to handle the ListView
events. You can construct a ListView as follows.
// create an instance of the ListView class with the Construct() method
__pList = new ListView();
__pList->Construct(Rectangle(0, 200, 480, GetClientAreaBounds().height - 200), true, true);
Android Developer’s Guide for bada
69
// Specify IListViewItemProvider and add IListViewItemEventListener.
__pList->SetItemProvider(*this);
__pList->AddListViewItemEventListener(*this);
AddControl(*__pList);
If you add IListViewProvider and IListviewItemEvnetListener to the ListView object, and a
ListView event occurs, OnListViewItemStateChanged() is called to handle the event of the
selected ListView item.
The IListViewItemEventListener interface provides the following interfaces to handle events.
Virtual Function Descriptions
OnListViewContextItemStateChanged This is called when the state of an element of the
ListContextItem is changed.
OnListViewItemLongPressed This is called when an item or element is pressed
and held.
OnListViewItemStateChanged This is called when the state of an element of the
ListView or GroupedListView is changed.
OnListViewItemSwept This is called when the Listitem is swept.
The virtual functions for the items of the IListViewItemEventListener interface are as follows.
void ListViewForm::OnListViewItemStateChanged(Osp::Ui::Controls::ListView &listView, int
index, int elementId, Osp::Ui::Controls::ListItemStatus status)
{
String itemText("");
AppLog("ListViewForm::%d",elementId);
switch(elementId) {
case ID_FORMAT_STRING:
itemText.Format(30, L"Item %d: Text Selected", index+1);
break;
case ID_FORMAT_BITMAP:
itemText.Format(30, L"Item %d: Bitmap Selected", index+1);
break;
Android Developer’s Guide for bada
70
case ID_FORMAT_CUSTOM:
itemText.Format(30, L"Item %d: Custom Selected",index+1);
break;
case ID_FORMAT_NULL:
itemText.Format(30, L"Item %d: Selected", index+1);
break;
}
__pLabelLog->SetText(itemText);
__pLabelLog->Draw();
__pLabelLog->Show();
}
To handle item selection events in the ListView, Osp::Ui::Controls::IListViewItemEventListener
interface is provided. To detect events occurring in the ListView, the
OnListViewContextItemStateChanged(), OnListViewItemStateChanged() and
OnListViewItemSwept() methods should be implemented.
ListItemStatus, the fourth argument of OnListViewItemStateChanged in the above source code,
delivers one of the following item states.
Status Description
LIST_ITEM_STATUS_SELECTED The selected item state
LIST_ITEM_STATUS_HIGHLIGHTED The highlighted item state
LIST_ITEM_STATUS_CHECKED The check item state
LIST_ITEM_STATUS_UNCHECKED The uncheck item state
LIST_ITEM_STATUS_MORE The more item state
You can add to or delete an item from ListView by implementing the CreateItem() and
DeleteItem() methods in the class that implements the IListItemProvider interface.
The following is the implementation of CreateItem.
Osp::Ui::Controls::ListItemBase*
ListViewSample::CreateItem(int index, int itemWidth)
{
Android Developer’s Guide for bada
71
ListAnnexStyle style = LIST_ANNEX_STYLE_NORMAL;
CustomItem* pItem = new CustomItem();
pItem->Construct(Osp::Graphics::Dimension(itemWidth,100), style);
// Add a string format item
pItem->AddElement(Rectangle(80, 25, 200, 50), ID_FORMAT_STRING, L"HOME", true);
// Add a custom format item
pItem->AddElement(Rectangle(290, 20, 60, 60), ID_FORMAT_CUSTOM,
*(static_cast<ICustomElement *>(__pCustomListElement)));
// Add Context menu to the Item
ListContextItem* pItemContext = new ListContextItem();
pItemContext->Construct();
pItemContext->AddElement(ID_CONTEXT_ITEM_1, "Test1");
pItemContext->AddElement(ID_CONTEXT_ITEM_2, "Test2");
pItem->SetContextItem(pItemContext);
return pItem;
}
The following shows an example of the implementation of the DeleteItem() function.
bool ListViewSample::DeleteItem(int index, Osp::Ui::Controls::ListItemBase* pItem, int
itemWidth)
{
delete pItem;
return true;
}
The first argument is the index of the item of the ListView to be deleted and the second
argument is the instance of the item to be deleted. In the method, the memory of the instance is
released by the delete function and the pointer is set to null.
Android Developer’s Guide for bada
72
4.10 Slider Control
Android provides the android.widget.SeekBar widget to receive a value within a range.
Developers can determine the minimum and maximum values for the range.
bada provides a Slider Control just like Android. You can use the Slider Control
(Osp::Ui::Controls::Slider) to receive a value within a range in an application.
Figure 4.5 bada’s Slider Control
bada1.x provides the OnAdjustmentValueChanged( ) virtual function to handle the slider events
through the Osp::Ui::IAdjustmentEventListener interface.
virtual void OnAdjustmentValueChanged(const Osp::Ui::Controls& source, int adjustment);
The first argument is the instance of the event source that can be used to identify the Control
that causes the event and the second argument is the user selected value.
For a Slider, you don’t need to set an Action ID unlike for the Button or List Control previously
described.
Slider* pSlider = new Slider();
pSlider->Construct(Rectangle(50, 200, 300, 100),
BACKGROUND_STYLE_DEFAULT, false, 0, 100);
Android Developer’s Guide for bada
73
pSlider->SetValue(40);
pSlider->AddAdjustmentEventListener(*this);
If the handle of the Slider above is moved, the Slider value is changed and the event listener
registered by the AddAdjustmentEventListener( ) method is called. Since the current class (this)
is specified as the event listener, the current class must have inherited the
IAdjustmentEventListener interface.
void ExampleClass::OnAdjustmentValueChanged(const Osp::Ui::Control& source, int
adjustment)
{
// Todo:
AppLog(“Adjustment : %d”, adjustment);
}
If the value of the Slider is changed, the OnAdjustmentValueChanged( ) event handler is
automatically called and the configured value is transferred through the adjustment.
From bada 2.0, the OnSliderBarMoved() virtual function of the
Osp::Ui::Controls::ISliderEventListener interface is called whenever the slider is moved.
4.11 Text Input Controls
Android provides the single input control android.widget.TextEdit and enables entering one or
more lines through multiple methods. In addition, Android provides the xml attributes with which
the input date format can be specified and methods allowing you to specify the input format for
characters, numbers, addresses, phone numbers or web addresses.
bada provides the following two controls as controls for users to enter text.
• Edit field
o EditField is the control that allows entering one line of text. The edit field does not
Android Developer’s Guide for bada
74
expand with the length of the text.
• Edit area
o The edit area is used for multi-line text input. It has more edit space than the edit
field and can accommodate more text. The edit area wraps the text when the
maximum line width of the edit area is reached.
Figure 4.6 EditField and EditArea
In addition, bada provides the Osp::Ui::Controls::ExpandableEditArea control that automatically
adjusts the text input area according to the amount of the entered text unlike EditArea.
To handle these types of text inputs and Controls, the Osp::Ui::ITextEventListener interface is
provided. The ITextEventListener interface provides the following virtual functions to handle
cancelling and modifying text input.
virtual void OnTextValueChangeCanceled (const Osp::Ui::Control &source)
virtual void OnTextValueChanged (const Osp::Ui::Control &source)
The instance of the event source that can be used to identify the Control that causes the event
is transferred as an argument.
// Create an EditField
EditField* pEditField = new EditField();
Android Developer’s Guide for bada
75
pEditField->Construct(Rectangle(0, 100, 480, 100));
pEditField->AddTextEventListener(*this);
//Add an EditField to the Form
AddControl(*pEditField);
In the above source code, if the text of the control is changed, the OnTextValueChanged( )
event handler of the event listener registered by the AddTextEventListener( ) method is called.
Since the current class (this) is specified, the current class must have inherited the
ITextEventListener interface.
// Implement an ITextEventListener
void EditFieldSample::OnTextValueChanged(const Osp::Ui::Control& source)
{
String text = (TextField*)source->GetText();
}
void EditFieldSample::OnTextValueChangeCanceled(const Osp::Ui::Control& source)
{
// Todo:
}
4.12 ColorPicker Control
bada provides the Osp::Ui::Controls::ColorPicker Control to enable users to select a color. To
do this in Android, you have to implement this as a CustomView using a SeekBar.
Android Developer’s Guide for bada
76
Figure 4.7 Osp::Ui::Controls::ColorPicker
Android Developer’s Guide for bada
77
If a color is selected through the ColorPicker, you can get the selected color information through
the OnColorChanged( ) virtual function of the Osp::Ui::IColorChangeEventListener interface.
virtual void OnColorChanged (const Osp::Ui::Control &source,
const Osp::Graphics::Color &color)
The second argument is the selected color information.
// Create a ColorPicker.
ColorPicker* pColorPicker = new ColorPicker();
pColorPicker->Construct(Point(20, 0));
// Add a ColorChangeEvent listener.
pColorPicker->AddColorChangeEventListener(*this);
In the above source code, if the the color is set, the OnColorChanged( ) event handler of the
event listener registered by the AddColorChangeEventListener( ) method is called.
void ExampleClass::OnColorChanged(const Osp::Ui::Control& source,
const Osp::Graphics::Color &color)
{
// To do
}
4.13 DatePicker and TimePicker Controls
Android provides the DatePicker class to select the date and time.
bada provides the Osp::Ui::Controls::DatePicker control to select the date and the
Osp::Ui::Controls::TimePicker control to select the time.
Android Developer’s Guide for bada
78
Figure 4.8 Android’s DatePicker and bada’s Osp::Ui::Controls::DatePicker
If you enter a date through DatePicker, you can get the information of the entered date through
the OnDateChanged( ) virtual function of the Osp::Ui::IDateChangeEventListener interface.
virtual void OnDateChangeCanceled (const Osp::Ui::Control &source)
virtual void OnDateChanged (const Osp::Ui::Control &source, int year,
int month, int day)
The OnDateChangeCanceled( ) event handler is called when a date input is cancelled and the
OnDateChanged( ) event handler is called when the date of the DatePicker is changed.
The first argument of the OnDateChanged( ) event handler is the instance of the event source
that can be used to identify the Control that causes the event and the arguments from the
second one are the selected year, month and day information.
// Create a DatePicker
DatePicker* pDatePicker = new DatePicker();
pDatePicker->Construct(L"Get Date");
// Add a DateChangeEvent listener
pDatePicker->AddDateChangeEventListener(*this);
In the above source code, if the date is changed, the OnDateChanged( ) event handler of the
event listener registered by the AddDateChangeEventListener( ) method is called.
void ExampleClass::OnDateChanged(const Osp::Ui::Control& source,
Android Developer’s Guide for bada
79
int year, int month, int day)
{
DateTime date;
String formattedString;
DateTimeFormatter* pDateFormatter = null;
Locale locale(LANGUAGE_ENG, COUNTRY_GB);
pDateFormatter = DateTimeFormatter::CreateDateFormatterN(
locale, DATE_TIME_STYLE_DEFAULT);
date = (DatePicker*)source->GetDate();
pDateFormatter->Format(date, formattedString);
AppLog("%ls", formattedString->GetPointer());
}
void ExampleClass::OnDateChangeCanceled(const Osp::Ui::Control& source)
{
AppLog("Canceled.\n");
}
To enable selecting the time, bada provides the Osp::Ui::Controls::TimePicker Control like the
Control for the date. Using the Osp::Ui::ITimeChangeEventListener interface, you can handle
time changes.
virtual void OnTimeChangeCanceled (const Osp::Ui::Control &source)
virtual void OnTimeChanged (const Osp::Ui::Control &source,
int hour, int minute)
The basic usage of the ITimeChangeEventListener event handler is similar to that of the
IDateChangeEventListenerinterface of the DatePicker described above.
Android Developer’s Guide for bada
80
4.14 Animation Control
In Android, you can use frame by frame animation and the tweened-animation using
AnimationDrawable. In bada, you can use bada’s Osp::Ui::Controls::Animation Control that
provides an animation function with multiple images.
Figure 4.9 bada’s Animation Control
The Osp::Ui::IAnimationEventListener interface provides the OnAnimationStopped( ) virtual
function to handle the event of the animation.
virtual void OnAnimationStopped (const Osp::Ui::Control &source)
The instance of the event source that can be used to identify the Control that causes the event
is transferred as an argument.
Image image;
image.Construct();
Bitmap* pBitmap1 = image.DecodeN("1.png",
BITMAP_PIXEL_FORMAT_ARGB8888);
Bitmap* pBitmap2 = image.DecodeN("2.png",
BITMAP_PIXEL_FORMAT_ARGB8888);
Bitmap* pBitmap3 = image.DecodeN("3.png",
BITMAP_PIXEL_FORMAT_ARGB8888);
Bitmap* pBitmap4 = image.DecodeN("4.png",
BITMAP_PIXEL_FORMAT_ARGB8888);
long duration = 40;
// A aniframe object
AnimationFrame* pAniFrame1 = new AnimationFrame(*pBitmap1, duration);
AnimationFrame* pAniFrame2 = new AnimationFrame(*pBitmap2, duration);
Android Developer’s Guide for bada
81
AnimationFrame* pAniFrame3 = new AnimationFrame(*pBitmap3, duration);
AnimationFrame* pAniFrame4 = new AnimationFrame(*pBitmap4, duration);
// Construct the animation array
ArrayList* pAnimationFrameList = new ArrayList();
pAnimationFrameList->Construct();
pAnimationFrameList->Add(*pAniFrame1);
pAnimationFrameList->Add(*pAniFrame2);
pAnimationFrameList->Add(*pAniFrame3);
pAnimationFrameList->Add(*pAniFrame4);
Animation* pAnimation = new Animation();
pAnimation->Construct(Rectangle(0, 340, 480, 186),
*pAnimationFrameList);
pAnimation->SetRepeatCount(10000);
pAnimation->AddAnimationEventListener(*this);
To set an animation, create the animation frames as an array and register it to the Animation
Control. If the animation is terminated, the OnAnimationStopped( ) event handler of the event
listener registered to the AddAnimationEventListener( ) method is called.
void ExampleClass::OnAnimationStopped(const Osp::Ui::Control& source)
{
// To do
}
5. Input and Output(I/O) of bada for Android developers
Android provides data storage
storage (device memory) and external
myapp application is installed, the
storage /data/data/[package_name].
application, the Shared Preferences,
For file input and output operations
directly use the File IO class
android.content.SharedPreferences
within the package namespace of
The android.database.sqlite package
The external storage is the public
The media file formats (e.g. jpg,
In bada the private data area and
you can use the Osp::Io namespace
5.1 Osp::Io Namespace
The Osp::Io namespace performs
databases and inter application communication mechanisms like channels
Android Developer’s Guide for
Input and Output(I/O) of bada for Android developers
options such as Shared Preferences, cached
external storage devices. As shown by the figure
the application secures and uses its own storage
/data/data/[package_name]. In the private space on the basis of the
Preferences, database and files are saved.
Figure 5.1 Android's IO
operations to these internal and external storage devices,
class provided by the java.io package. Android
android.content.SharedPreferences class so that developers can share common
of the application on the basis of the File class.
package supports the SQLite3 database.
public area that can be accessed by any application
png, avi, mpg) are automatically scanned by MediaStore.
and public data area are distinctive just like in Android.
namespace for basic file input and output operations.
Namespace
performs the input and output functions for files , directories, registries ,
and inter application communication mechanisms like channels .
Data area
Android Developer’s Guide for bada
82
Input and Output(I/O) of bada for Android developers
cached data, internal
below, when the
storage in the internal
package of this
devices, you can
Android provides the
common configuration
application on the device.
MediaStore.
Android. In addition,
, directories, registries ,
Android Developer’s Guide for bada
83
The File class provides the functions to enter and output data for a file structure. In the bada
platform, the access privilege of each directory differs. You can get the file access privilege
information through the File::GetFileAttributes() method.
Figure 5.2 bada’s Basic I/O Classes
The Directory class provides the functions to create a directory, delete an empty directory, and
get the file list of the current directory.
The Registry class provides the functions to save application settings.
bada also supports the SQLite database that is widely provided by general mobile platforms.
Since you can also use SQLite in Android, you can reuse the previously created SQL queries in
bada as is.
5.2 Directories
In Android, developers can handle files and directories using the java.io.File class. bada
provides the Osp::Io::Directory class for directory handling.
Note that in the bada platform, the write and read privileges are different for each directory.
Directory Description Privilege
/Home The home directory of the running
application
Read/Write
/Home/Share The directory with which you can
share data with another application.
Read/Write
/Share/[appid] This directory is used to read the Read
Android Developer’s Guide for bada
84
temporary data of another application.
/Res The directory where resources such
as the icon and sound files are saved.
Read
/Share/AppControl/[appcont
rol-name]
This directory is used to read the data
provided by the application’s Controls.
Read
/Media/{Image, Sounds,
Video, Themes, Other}
This directory is to save media files
such as image, sound and video files.
Read (Write is possible
with the API of the
Media or Contents
namespace.)
/Storagecard/Media/{Image
s, Sounds, Videos,
Themes, Other}
The directory for the media files that
are saved to external memory such as
image, sound and video files.
/Share2 The directory to share data with
trusted applications. (This has been
added since bada 1.2.)
Read/Write
The Directory class provides functions to get the file list of the directory as well as functions to
create and delete directories.
void GetFileListInDir(String strDirPath,
Osp::Base::Collection::ArrayList* listFile)
{
result r = E_SUCCESS;
String name;
Directory* pDir = new Directory;
r = pDir->Construct(strDirPath);
if(IsFailed(r)) {
delete pDir;
return;
}
String path;
Android Developer’s Guide for bada
85
DirEnumerator* pDirEnum = pDir->ReadN();
while(pDirEnum->MoveNext() == E_SUCCESS) {
DirEntry entry = pDirEnum->GetCurrentDirEntry();
path.Format(30, L"%ls", entry.GetName().GetPointer());
listFile->Add(*(new String(path)));
};
delete pDir;
}
5.3 Files
bada provides the Osp::Io::File class for the file input and output operations.
Usage of the File class for File I/O operations is similar to that of normal File I/O operations
except for a few restrictions.
You can use the File class in a similar way as using the File Stream in the C language in
addition to standard library APIs.
File file;
char buffer[5];
int readCnt;
file.Construct(L"/Home/sample.txt", L”w+”);
file.Write("0123456789", 10);
file.Seek(FILESEEKPOSITION_CURRENT, -5);
readCnt = file.Read(buffer, 5);
if(readCnt != 5) AppLog(“Error”);
The Construct (FilePathName, mode, createParentDirsToo) method for the File class is as
follows. The mode argument determines the file open mode from among r, r+, w, w+, a and a+.
The last argument createParentDirsToo is the option to determine whether to create the parent
directory if it does not exist.
Android Developer’s Guide for bada
86
5.4 Databases
Just as Android provides databases using SQLite3, bada provides databases using SQLite. In
bada, developers can use databases using the Osp::Io::Database class. To use a database,
you need to know how to use SQL statements. You can use SQL statements using the
DbStatement class.
The methods that are frequently used in a database are as follows.
Method Description
result Osp::Io::Database::ExecuteSql (const
Osp::Base::String & sql, bool autoCommit)
Executes an
SQL statement.
DbEnumerator* Osp::Io::Database::QueryN (const
Osp::Base::String & query)
Executes an
SQL query.
DbStatement* Osp::Io::Database::CreateStatementN (const
Osp::Base::String & statement)
Creates a
statement.
DbEnumerator* Osp::Io::Database::ExecuteStatementN
(const DbStatement & statement)
Executes a
statement.
You can create a database using the Construct method.
database.Construct("<database_file_name>", true);
If the last argument is true and the specified directory does not exist, the directory is
automatically created. To use a database, using the /Home directory for which the read and
write operations are supported is recommended.
When you create an SQL statement using the CreateStatementN( ) method, you can enter “?”
instead of a value and then specify the value for the “?” argument later using the BindString( )
method.
String sql1, sql2
DbStatement* pStmt;
DbEnumerator* pEnum;
Android Developer’s Guide for bada
87
Database database;
database.Construct(L"/Home/dbFile", true);
// create database table
sql1.Append(L"CREATE TABLE IF NOT EXISTS table(col1 INTEGER PRIMARY
KEY, col2 DOUBLE, col3 TEXT)");
database.ExecuteSql(sql1, true);
// insert rows
database.BeginTransaction();
statement.Append(L"INSERT INTO table (column0, column1, column2) VALUES
(?, ?, ?)");
pStmt = database.CreateStatementN(statement);
pStmt->BindInt(0, 1); // integer
pStmt->BindDouble(1, 0.1); // double
pStmt->BindString(2, L"test"); // String
pEnum = database.ExecuteStatementN(*pStmt);
database.CommitTransaction();
// delete rows
database.BeginTransaction();
sql2.Append(L"DELETE FROM table WHERE col1 = 1");
database.ExecuteSql(sql2, true);
database.CommitTransaction();
Android Developer’s Guide for bada
88
6. Graphics of bada for Android developers
Graphics refers to the processing of the representation and manipulation of figures (e.g. points,
lines, circles, rectangles, polygons, free-form curves) or images on a platform. The Android and
bada platforms provide packages and namespaces for the most primitive graphics functions.
6.1 bada’s Graphics Support Environment
The bada platform provides primitive drawing functions and various image formats for graphics
processing.
Figure 6.1 bada’s Graphics Classes
Android's android.graphics package supports 2D graphics and the android.opengl package
supports OpenGL ES of kronos for 3D graphics. From Android OS 3.0 Honeycomb,
Renderscript is supported for high-level mathematical calculations for 2D and 3D graphics
processing.
Like Android, bada also provides functions for graphics. bada supports 2D graphics internally
and supports 3D graphics through OpenGL ES(Osp::Graphics::Opengl).
Android Developer’s Guide for bada
89
Figure 6.2 Android's graphics system (source: developer.android.com)
bada represents a specific location on the screen using the Point class, dimensions with the
Dimension class and space with the Rectangle class.
Figure 6.3 Location and Dimensions in bada In general, the methods of the above Point, Dimension and Rectangle classes are similar. The
major methods of the Point class are as follows.
Method Description
Osp::Graphics:Point::Point(void) Creates a point at the location
of (0, 0).
Osp::Graphics:Point::Point(int x, int y) Creates a point at the location
specified by the (x, y)
coordinates.
Osp::Graphics:Point::SetPosition(int x, int y) Moves to the location specified
by the (x, y) coordinates.
Osp::Graphics:Point::Translate(int deltaX, int
delteaY)
Moves to the position of
(deltaX, deltaY).
The basic graphics classes of bada are as follows.
bada Class Android Class Description
Point Point Point
Android Developer’s Guide for bada
90
Dimension Dimension 2-dimensional space
Rectangle Rectangle Rectangle area
Color Color Color
Font Font Character Font
Bitmap Bitmap Provides functions to draw a bitmap image
file.
Canvas Canvas Provides functions to draw graphic objects on
the screen.
EnrichedText Provides functions to draw various text
formats.
TextElement Provides functions to draw text on the
Canvas.
BufferInfo Provides the pixel information.
The color class represents colors. In bada, colors are represented with the ARGB (32 Bit) color
system. The “A” in “ARGB” stands for Alpha (Transparency 0x00: Transparent ~ 0xFF: Opaque)
and the other letters stand for Red, Green and Blue color values bada provides the following 10
constants for colors.
Color Constant Description
Color::COLOR_BLACK Black
Color::COLOR_BLUE Blue
Color::COLOR_CYAN Cyan
Color::COLOR_GREEN Green
Color::COLOR_GREY Grey
Color::COLOR_MAGENTA Magenta
Color::COLOR_RED Red
Color::COLOR_VIOLET Violet
Color::COLOR_WHITE White
Color::COLOR_YELLOW Yellow
The Font class is the class that represents characters and supports the various font properties
including the Width, Height, Bold and Italic settings.
Android Developer’s Guide for bada
91
6.2 Images
Android provides the android.widget.ImageView widget to display images on layouts and
provides the android.graphics.Drawable class to support compressed image formats.
Like Android, bada also provides classes and Controls to draw images on the screen.
The Osp::Graphics::Bitmap class is used to draw an image in bada. bada supports a resolution
(size) of up to 5000x5000 pixels for images.
In bada, developers can get and use the image buffer data in a BufferInfo class object. You can
use the class to acquire the size of an image or to access each individual pixel of the image.
The BufferInfo class provides the following members.
Type Name Description
int width The width of the image in pixels.
int height The height of the image in pixels.
int pitch The length of the scan-line of the buffer in
bytes.
int bitPerPixel The number of bits of a pixel of the buffer.
PixelFormat PixelFormat The color format of the buffer.
void* pPixels The pointer to the actual pixel data.
You can load and save images using the Osp::Media::Image class.
The image formats supported by bada are different for loading and saving. When loading
images, the JPEG, GIF, PNG, BMP, TIFF and WBMP formats are supported but the JPEG,
PNG and BMP formats are supported for saving images. To use the Image class, the privileges
must be configured in the manifest.xml file as with using the database described above.
6.3 2D Graphics
For 2D graphics, you can use the Osp::Graphics namespace and you can draw lines and
figures using the Canvas class. The Canvas class provides the following drawing methods.
Android Developer’s Guide for bada
92
Method Descriptions
DrawLine Draws a line.
DrawTriangle Draws a triangle.
DrawRectangle Draws a rectangle.
DrawRoundRectangle Draws a rectangle with rounded edges.
DrawPolyline Draws a polyline.
DrawPolygon Draws a polygon.
DrawArc Draws an arc.
DrawEllipse Draws an ellipse.
DrawText Draw text (Text, EnrichedText).
DrawBitmap Draws a bitmap image.
Before drawing a figure or text, configuration is necessary, which is provided by Canvas class.
Canvas class enables your application to create a background (canvas) for graphics, and to
draw graphic elementsThe Canvas class provides the following methods for the configuration
before drawing.
Method Descriptions
SetBackgroundColor Sets the background color.
SetForegroundColor Sets the foreground color.
SetFont Sets the font.
SetLineWidth Sets the line width.
SetLineStyle Sets the line style.
SetPosition Sets the position.
Using the methods above, you can draw lines and rectangles. The following example shows
how to draw a rectangle.
Canvas* pCanvas = new Canvas();
pCanvas->Construct();
pCanvas->SetBackgroundColor(Color::COLOR_YELLOW);
pCanvas->Clear();
pCanvas->SetForegroundColor(Color::COLOR_RED);
Android Developer’s Guide for bada
93
pCanvas->DrawRectangle(Rectangle(50, 50, 100, 100));
pCanvas->Show();
delete pCanvas;
In the example source code above, a Canvas class instance is constructed and initialized, the
background color is set to yellow, and the Clear( ) method is called to fill the Canvas with the
background. Then the foreground color is set to red and the DrawRectangle( ) method is called
to draw a rectangle with a size of 100 x 100 at position (50, 50) in the red color.
In bada, one of the ways to draw formatted text (Rich Text) is using the EnrichedText class.
Using the EnrichedText class, you can draw text in various ways using various fonts and colors.
Android Developer’s Guide for bada
94
7. Multimedia of bada for Android developers
Multimedia refers to media content that uses a combination of different content forms.
Media refers to information that human beings can recognize through their sense organs.
Media also refers to the storage and transmission channels or tools used to store and deliver
information, knowledge, feelings and opinions between human beings. It also means sharing
information and knowledge by delivering it.
Multimedia refers to the combination of media content.
In Android, the android.media package provides multimedia functions. This package provides
multimedia functions for audio, video, 2D/3D graphics, animation, and so on.
Audio and video environments are provided by MediaPlayer and MediaRecorder on the basis of
OpenCore (from version 2.3, the StageFright multimedia engine is used).
By default, the .mov, .mp4, .m4v and .3gp formats are supported for video, but phone
manufactures can add, change and remove the supported formats. Using the
MediaPlayer.framework, full screen video can be played.
Figure 7.1 Android's media output system (source: Google IO of 2009)
Android Developer’s Guide for bada
95
Figure 7.2 Android's media classes bada also provides multimedia functions such as image, camera, video recording and audio
play/recording functions.
bada supports sound and video through the Osp::Media namespace. To support 3D sound,
OpenAL is supported from bada 2.0 onward.
Class Description
Image Provides image encoding/decoding functions.
Player Plays local (device) or network (streaming) media files.
Camera Provides functions to take pictures or record video using a
camera.
AudioRecorder Records audio using the microphone.
VideoRecorder Records video using the camera.
The relationships between the multimedia classes in the Osp::Media namespace are drawn
below.
Android Developer’s Guide for bada
96
Figure 7.3 bada’s Multimedia Classes
Android Developer’s Guide for bada
97
7.1 Audio and Video
The audio file formats supported by Android are as follows. Although the following formats are
supported by default, manufacturers can add, change or remove formats.
Format Description
Ogg vorbis The audio format developed by Xlph.org.
MIDI MIDI type 0, 1
PCM/WAVE The audio format of pure uncompressed
digital signals.
AAC (Advanced Audio Codec) The iTunes audio file format (.m4a)
MP3 (MPEG Audio Layer-3) The MP3 compressed audio file format
(.mp3)
The bada platform also provides audio functions. bada not only supports audio formats such as
MP3 but also video formats of various codecs through the Osp::Media::Player class. bada
supports playing media files on local storage devices (internal or external memory) or over the
network (streaming).
The file formats supported by Android and bada's Osp::Media namespace are as follows.
Type Formats supported by bada Formats supported by Android
Audio PCM(WAV), AMR-NB, AAC, AAC+, EAAC+,
MIDI, MP3, WMA
AAC, AMR-NB, AMR-WB, FLAC,
MP3, MIDI, Ogg, Wave
Video H264, H.263, MPEG, VC-1 H264 AVC, H.263, MPEG-4 SP, VP8
The Osp::Media::Player constructor is as follows.
Construct(const IPlayerEventListener &listener, const Osp::Graphics::BufferInfo
&pBufferInfo = null)
The first argument is the event listener and the second argument is the buffer information about
the video that will be played.
The event listener of the Osp::Media::Player class is called Osp::Media::IPlayerEventListener.
Android Developer’s Guide for bada
98
The IPlayerEventListener interface provides functions for playing media and the following event
handlers.
Virtual Function Descriptions
void OnPlayerOpened( ) Called when a file is opened asynchronously.
void OnPlayerEndOfClip( ) Called when playing ends.
void OnPlayerBuffering( ) Called when streaming data is being
buffered.
void OnPlayerErrorOccurred( ) Called when an error occurs.
void OnPlayerInterrupted( ) Called when an interrupt occurs.
void OnPlayerReleased( ) Called when the interrupting Player has been
released.
void OnPlayerSeekCompleted( ) Called when the seeking operation is
complete.
To play an MP3 file, specify a file name and call the Play( ) method of the Player class as shown
by the figure below.
Player* pPlayer = new Player();
pPlayer->Construct(*this, null);
pPlayer->OpenFile(String(L"/Res/bada.mp3"));
pPlayer->SetVolume(50);
pPlayer->Play();
Android’s MediaPlayer framework is used to play video and audio files and not only supports the
MOV, MP4, M4V and 3GP formats but also additional video formats. It also provides functions
to control playing, setting playback points, playing videos and stopping files and automatically
handles resizing and rotating the window on the device screen to play various video formats.
Android uses the android.media.MediaPlayer.OnCompletionListener event listener when the
playing operation of the MediaPlayer is finished.
In bada, you can play a video using the Osp::Media::Player class described above. When
playing a video, the screen should be displayed unlike when playing audio. To display the
screen, the OverlayRegion is used.
Android Developer’s Guide for bada
99
Osp::Graphics::Rectangle rect= Rectangle(0, 0, 480, 560);
Osp::Graphics::BufferInfo bufferInfo;
// Get OverlayRegion for video playback
OverlayRegion * pPlayerRegion = pPlayerForm->GetOverlayRegionN(rect,
Osp::Ui::Controls::OVERLAY_REGION_TYPE_NORMAL );
pPlayerRegion->GetBackgroundBufferInfo(bufferInfo);
Player* pPlayer = new Player();
// Set the buffer for playback
pPanel->GetBackgroundBufferInfo(bufferInfo);
// Construct
pPlayer->Construct(*this, &bufferInfo);
pPlayer->OpenFile(String("/Res/badaBI.mp4"));
pPlayer->Play();
pPlayer->Pause( );
pPlayer->Stop( );
7.2 Camera
Android provides the android.Graphics.Camera class to take pictures using a camera and save
pictures and the Camera.Parameters class to configure the camera settings. In addition,
developers can process the images taken by the camera through the callback methods for the
camera.takePicture(shutterCallback, rawCallback, jpegCallback) method, using a Looper. If the
path to the external memory (SDCARD) is specified before taking a picture using the camera,
the pictures are saved in the specified path. Once a picture is saved, the media file list is
updated by MediaScanner. Whenever the media file list is added, deleted or updated, the media
file list is automatically updated by MediaScanner.
bada also provides camera functions. In bada, the methods to access the photo album and
camera are separated. In bada, the photos taken by the camera are saved in the /Media folder
Android Developer’s Guide for bada
100
as described in the Input/Output (I/O) chapter. You can fetch the image file list of the directory
and show the images.
The Camera class provides methods to handle the camera device. In bada, you can test the
camera on the simulator using the PC’s web camera. Of course, you cannot test the SetEffect( ),
SetExposure( ), SetFlash( ), SetIsoLevel( ), ZoomIn( ), ZoomOut( ) and SetAutoFocus( )
methods that control the camera device because they require the actual camera device.
In bada, you need to complete the following steps to operate the camera.
Step Description
Initialize Checks if the camera device is available.
Make the camera ready.
Preview Displays the image from the camera on the LCD.
Capture Saves the image from the camera.
For the camera, the step to preview the image from the camera is necessary before recording a
video unlike for the audio or video functions. This step is called the Preview step which should
show the image and handle user actions.
In this Preview step, if the user wants to save the image, the image can be saved as an image
or video in the following Capture step.
Android Developer’s Guide for bada
101
Figure 7.4 bada’s Camera Operation
In the Initialization step for the camera, the camera settings are configured. The camera has
various properties including the brightness, contrast, exposure, ISO level, effect (Black&White,
Sephia, etc.) and image size. The Camera class provides various methods relating to the
camera properties. You can set the brightness to 0 ~ 9 using the GetBrightness( ) and
SetBrightness(int brightness) methods, and set an effect using the SetEffect(CameraEffect
effect) method.
The following are the effects provided in bada.
Constant Effect
CAMERA_EFFECT_NONE No Effect
CAMERA_EFFECT_COLOR Color Effect
CAMERA_EFFECT_BW Black&White Effect
CAMERA_EFFECT_SEPIA Sepia Effect
CAMERA_EFFECT_SOLARIZE Solarize Effect
CAMERA_EFFECT_NEGATIVE Negative Effect
You can get and set the camera’s exposure using the GetExposure( ) and SetExposure( )
methods. The default value is 5. You can get and set the camera’s ISO value using the
Android Developer’s Guide for bada
102
GetIsoLevel( ) and SetIsoLevel(CameraIsoLevel) methods. The supported ISO values in bada
are as follows.
Constant ISO Value Constant ISO Value
CAMERA_ISO_DEFAULT Default ISO CAMERA_ISO_200 ISO 200
CAMERA_ISO_MIN Minimum
ISO CAMERA_ISO_400 ISO 400
CAMERA_ISO_AUTO Auto ISO CAMERA_ISO_800 ISO 800
CAMERA_ISO_50 ISO 50 CAMERA_ISO_1600 ISO 1600
CAMERA_ISO_100 ISO 100 CAMERA_ISO_MAX Maximum
ISO
You can get and set the camera’s zoom level using the Zoom In( ) and ZoomOut( ) methods.
You can get the highest zoom level using the GetZoomLevel( ) method. You can get and set the
camera’s picture quality using the GetQuality( ) and SetQuality(CameraQuality) methods. The
following picture qualities are supported in bada.
Constant Picture Quality
CAMERA_QUALITY_NORMAL Normal Quality
CAMERA_QUALITY_FINE Fine Quality
CAMERA_QUALITY_SUPER_FINE Super Fine Quality
CAMERA_QUALITY_MAX Highest Quality
For taking pictures and other operations using the camera, the
Osp::Media::ICameraEventListener interface is provided. The ICameraEventListener provides
the following event handlers.
Method Descriptions
OnCameraAutoFocused This is called when the auto focus operation is
complete.
OnCameraPreviewed This is called when the preview event is called.
OnCameraCaptured This is called after an image is captured.
OnCameraErrorOccurred This is called when an error occurs.
Android Developer’s Guide for bada
103
The source code for the initialization is as follows. Implement ICameraEventListener, construct
the Camera object, create OverlayRegion and construct a camera object here and configure it.
Then the initialization stage to the camera is completed.
Osp::Graphics::Rectangle rect= Rectangle(0, 0, 480, 560);
Osp::Graphics::BufferInfo bufferInfo;
// Acquire OverlayRegion
OverlayRegion * pPlayerRegion = pPlayerForm->GetOverlayRegionN(rect,
Osp::Ui::Controls::OVERLAY_REGION_TYPE_NORMAL );
pPlayerRegion->GetBackgroundBufferInfo(bufferInfo);
// Construct and configure a camera object
Camera* pPrimaryCamera = new Camera();
pPrimaryCamera->Construct(*this, CAMERA_PRIMARY);
Now you need to receive and display the image for the camera. Set the format of the image to
be saved here.
pPrimaryCamera->SetPreviewResolution(Dimension(480, 560));
pPrimaryCamera->SetCaptureFormat(PIXEL_FORMAT_JPEG);
pPrimaryCamera->PowerOn();
pPrimaryCamera->StartPreview(&bufferInfo, false);
The formats of the images to be saved in Android are defined as constants in the
Bitmapt.Config class. In bada, the formats are also defined as the following constants.
Format Android Description
PIXEL_FORMAT_RGB565 RGB565 The RGB565 Pixel Format
PIXEL_FORMAT_ARGB8888 ARGB8888 The ARGB8888 Pixel Format
PIXEL_FORMAT_R8G8B8A8 The R8G8B8A8 Pixel Format
PIXEL_FORMAT_YCbCr420_PLAN
AR
ImageFormat.YUY12 The YUV420 Pixel Format
PIXEL_FORMAT_JPEG ImageFormat.JPEG JPEG Encoding
Android Developer’s Guide for bada
104
If a user wants to save the image, the Capture operation is performed. You can handle these
operations using the OnCameraCaptured( ) event handler of the ICameraEventListener listener
as shown above.
void OnCameraCaptured ( Osp::Base::ByteBuffer& capturedData, result r )
{
// The source code to be executed after an image is captured.
File file;
file.Construct(L"/Home/sample.jpg", L"w", true);
file.Write(capturedData);
}
To save the captured image in the JPEG format, you can save the data in the ByteBuffer that is
received as an argument as a file. When the camera is no longer being used, you can turn the
camera off in the reverse order of the initializing the camera.
pPrimaryCamera->StopPreview();
pPrimaryCamera->PowerOff();
Although recording a video is similar to saving a still image, the event listener and handling
method are slightly different. You can record a video using the Osp::Media::VideoRecorder
class. Use the Osp::Media::IVideoRecorderEventListener as the event listener and perform the
necessary operations.
Camera* pCamera = new Camera();
pCamera->Construct(*this);
pCamera->PowerOn();
VideoRecorder* pVideoRecorder = new Osp::Media::VideoRecorder();
pVideoRecorder->Construct(*this, *pCamera);
pCamera->StartPreview(&previewBufferInfo, false);
To start recording a video, specify the file name and call the Record( ) method.
pVideoRecorder->CreateVideoFile(L"/Home/sample.mp4", true);
pVideoRecorder->Record();
pVideoRecorder->Stop();
Android Developer’s Guide for bada
105
To use the camera, the camera configuration in the manifest.xml file is required.
Figure 7.5 Configuration of manifest.xml
8. Communication of bada for Android developers
8.1 Networking (The Osp::Net Namespace)
A network is a set of devices connected to each other. Most mobile platforms support data
communications with other devices. For sending data over the network, the BSD UNIX socket
introduced in 1983 is used. A socket refers to the type of communications between a host (End-
System) and another host. While generally, UNIX operating systems including Linux use
sockets for communications, the MS Windows operating systems uses WinSock which is similar
to the BSD socket.
Android supports socket communication using Java's java.net package. In addition, java.nio is
also available on Android, which supports Networked IO for a more secure, fast communication.
The android.net package is also provided so that developers use java.net more easily in
Android. Among them, the ConnectivityManager is a system manager class that supports
Android Developer’s Guide for bada
106
centralized tasks such as network connection status monitoring and changing the status. The
ConnectivityManager manages Wi-Fi, 3G and Bluetooth resources which are the networking
methods of Android.
bada also supports network programming as in Android. In bada, the network service is
provided through the Osp::Net namespace. Bluetooth, Http, Sockets and Wi-Fi are supported.
The Socket class provides a BSD style socket. In bada, sockets are basically used as non-
blocking mode. If you want to set the socket to blocking mode, you can do that by calling the
Socket::Ioctl( ) method with the NET_SOCKET_FIONBIO option.
Generally, the time when the communication is complete cannot be easily identified in non-
blocking mode. In this case, you can use the Osp::Net::Sockets::ISocketEventListener. The
event handlers of ISocketEventListener are as follows.
Virtual Function Description
OnSocketConnected This is called when the socket connection attempt is
successful.
OnSocketAccept This is called when the socket connection is
accepted.
OnSocketReadyToReceive
This is called when there is data to receive.
Data can be received using the Receive or
ReceiveFrom methods.
OnSocketReadyToSend
This is called when there is data to send.
Data can be sent using the Send or SendTo
method.
OnSocketClosed This is called when the socket is closed.
Let’s use the Socket class for network communication.
Socket* pSocket = new Socket();
pSocket->Construct(NET_SOCKET_AF_IPV4,
NET_SOCKET_TYPE_STREAM,
NET_SOCKET_PROTOCOL_TCP);
Android Developer’s Guide for bada
107
pSocket->AddSocketListener(*this);
pSocket->AsyncSelectByListener(NET_SOCKET_EVENT_CONNECT |
NET_SOCKET_EVENT_WRITE|NET_SOCKET_EVENT_READ|
NET_SOCKET_EVENT_CLOSE);
Ip4Address peerAddr("XXX.XXX.XXX.XXX"); // server socket address
unsigned short peerPort = 8080; // port
NetEndPoint peerEndPoint(peerAddr, peerPort);
pSocket->Connect(peerEndPoint);
The initialization part for the Socket class is similar to that of a normal socket. To initialize the
Socket class, the IP version is specified as the first argument and the socket type is specified as
either STREAM or DATAGRAM as the second argument.
Type Descriptions
NET_SOCKET_TYPE_STREAM Stream Socket
NET_SOCKET_TYPE_DATAGRAM Datagram Socket
Then, set the protocol to TCP or UDP as the third argument.
Type Descriptions
NET_SOCKET_PROTOCOL_TCP TCP Socket
NET_SOCKET_PROTOCOL_UDP UDP Socket
NET_SOCKET_PROTOCOL_SSL SSL Socket
You can send data using the Send( ) method of the Socket class of the OnSocketReadyToSend
event handler of ISocketEventListener.
void OnSocketReadyToSend(Socket& socket)
{
const char* pSendData = "Send";
ByteBuffer txBuffer;
txBuffer.Construct(strlen(pSendData) + 1);
txBuffer.SetArray((byte*)pSendData, 0, strlen(pSendData));
Android Developer’s Guide for bada
108
txBuffer.Flip();
socket->Send(txBuffer);
}
To receive data, you can use the OnSocketReadyToReceiveevent handler of the
ISocketEventListener that is automatically called when data is sent. When you can receive data
using the Receive( ) method of the Socket class.
void OnSocketReadyToReceive(Socket& socket)
{
char data[MAX_BUFFER_SIZE];
socket->Ioctl(NET_SOCKET_FIONREAD, arg);
rxBuffer.Construct(arg);
socket->Receive(rxBuffer);
}
When you have finished using a socket, close and delete the socket. You can do this using the
OnSocketClosed event handler of the ISocketEventListener.
void OnSocketClosed(Socket& socket, NetSocketClosedReason reason)
{
socket ->Close();
delete socket;
}
bada provides Bluetooth functions through the Osp::Net::Bluetooth namespace. In addition,
bada provides the Osp::Net::Wifi namespace for Wi-Fi communication.
Android Developer’s Guide for bada
109
8.2 Web Services
The World Wide Web (WWW or Web) was originally conceived and developed to meet the
demands for automatic information sharing between scientists of the European Organization for
Nuclear Research (CERN) working in different universities and institutes all over the world. The
web refers to a network of computers linked throughout the world with hypertext links like a web.
The World Wide Web which is also called WWW or 3W operates on the basis of the HTML
language and the HTTP protocol and enables users to share multimedia data such as graphics,
sound and video.
To display Internet documents written in HTML, a web browser is used. A web browser needs
an Internet browser engine that will parse and show HTML documents. There are representative
Internet browser engines. One is the WebKit used by Android and the other is Gecko used by
Mozilla. bada’s Dolphin browser uses the WebKit like Android.
Andriod provides the android.widget.WebView class to display HTML documents. Using the
WebView Control, developers can easily implement an Internet browser. The UIWebView
Control not only supports JavaScript, CSS and HTML but also the JPEG/GIF/PNG/TIFF image
formats, the MP3 audio format and the MPEG4 video format as well as the PDF, Word, Excel
and PowerPoint document formats. bada also provides the landscape orientation to play videos
but also automatically handles scrolling, zooming-in/out, links, movement and form input.
bada provides the Web::Controls::Web Control to enable developers to display web pages
easily like with Android's WebView. To handle events in the Web Control, you can use the
Osp::Web::Controls::ILoadingListener that provides the following event handlers.
Android Developer’s Guide for bada
110
Method Description
OnEstimatedProgress Reports the current page loading progress as a
percentage (%).
OnHttpAuthenticationCanceled Called when HTTP authentication is canceled.
OnHttpAuthenticationRequested Called when HTTP authentication is requested.
OnLoadingCanceled Called when loading is canceled.
OnLoadingCompleted Called when loading is complete.
OnLoadingErrorOccurred Called when an error occurs.
OnLoadingRequested Called when loading is requested.
OnLoadingStarted Called when loading is started.
OnPageTitleReceived Called when the title of a new page is received.
OnWebDataReceived Called when data is received.
To use the Web Control, the WEB_SERVICE related to Osp::Web should be configured in the
manifest.xml file.
Figure 8.1 WEB_SERVICE Settings
Using the Web Control is relatively simple. Construct a Web Control instance, register an object
that inherits the ILoadingListener to the Web Control object and load the web page through the
LoadUrl( ) method.
Web* pWebControl = new Web();
pWebControl->Construct(Rectangle(0, 120, 480, 680));
pWebControl->SetLoadingListener(this);
pWebControl->LoadUrl(L"http://www.bada.com");
8.3 Telephony Services
In Android, the system manager
functions to manage the phone status,
To acquire the status of the phone,
to AndroidManifest.
In bada, to access the telephony
provides the functions to make or
SIM module. To use this function,
Manifest.xml file in the bada Developer
Figure 8.2
Figure 8.3 Telephony/data communication related classes
Android Developer’s Guide for
>SetLoadingListener(this);
>LoadUrl(L"http://www.bada.com");
Telephony Services
class, TelephonyManager, provides the Telephony
status, to search for received phone numbers and
phone, you have to add android.permission.READ_PHONE_STATE
telephony function, you can use the Osp::Telephony namespace
or receive calls, access the telephone network and
function, you have to select TELEPHONY when you create
Developer Site.
bada application's Telephony privilege
Telephony/data communication related classes
Android Developer’s Guide for bada
111
Telephony API and
and manage calls.
android.permission.READ_PHONE_STATE
namespace that
and access the
create the
Android Developer’s Guide for bada
112
As the business area of telecommunication companies moves from voice calls to data services,
bada provides data communication classes such as the NetworkManager, NetworkStatus and
NetworkInfo classes.
Using the NetworkManager class, you can figure out the current network information or status.
Unlike voice call services that are usually available, the network connection information is
important for data services. Using the NetworkStatus class, you can figure out the network
connection status as well as the call/data service availability and roaming status.
The CallManager class provides functions for voice and video calls as well as functions to make
and receive calls. The network communication classes that use the telephone network are the
NetworkManager, NetworkInfo and NetworkStatus classes. The NetworkManager class is for
the information about the connected network and available network services, and the
NetworkInfo class is for network information such as MCC (Mobile Country Code), MNC (Mobile
Network Code), PLMN (Public Land Mobile Network), LAC (Location Area Code) and Cell ID.
The NetworkStatus class is for network status information such as the roaming state and
whether a call or data service is available. The class to access the SIM module is the SimInfo
class.
Using the CallManager class, developers can figure out the current call status and the current
call type. You can figure out the current call status using the GetCurrentStatus( ) method. The
current call status can be either the voice/video call status (CALL_STATUS_ACTIVE) or the idle
status (CALL_STATUS_IDLE). If the current call status is the voice/video call status, you can
get the call type using the GetCurrentCallType( ) method that returns either a voice call
(TYPE_VOICE_CALL) or a video call (TYPE_VIDEO_CALL).
8.4 Messaging Services (SMS/MMS/Email)
The Message service is the second most frequently used function on a phone after the call
function.
In Android, permissions are required to receive and send SMS messages. To receive an SMS
message, the android.permission.RECEIVE_SMS permission is required and to send an SMS
message, the android.permission.SEND_SMS and android.permission.WRITE_SMS
Android Developer’s Guide for bada
113
permissions are required. If you acquire the permission and register the RECEIVE_SMS action
to BroadcastReceiver, you can receive SMS messages in connection with an Activity and
Service. In addition, you can manage receiving and sending messages using SmsManager. In
addition, using ContentProviderm you can access a message with a URI value such as
“content://sms/inbox”.
The message services supported by the bada platform are categorized into three types. The
three message service types are as follows: An SMS (Short Message Service) which refers to
the normal short message service for mobile phones, an MMS (Multimedia Message Service)
which refers to the message service that can send multimedia content such as photos, and
emails that refer to emails on the Internet.
To support SMS, bada provides the SmsManager, SmsMessage and RecipentList classes and
provides the ISmsListener interface to handle SMS events. In addition, bada provides the
Osp::Messaging::ISmsMessageEventListener interface as the event handler to receive SMS
messages.
The SmsManager class uses the SMS message service. You can send a message using the
Send( ) method with the arguments of the message contents, the phone number of the recipient,
and whether to save the sent message in the outbox. To check if an SMS message has been
sent successfully, you can use the Osp::Messaging::ISmsListener interface. You can perform
necessary jobs after sending a message by overriding the OnSmsMessageSent event handler.
The SmsMessage class is to save the SMS message to be sent. To save the recipient
information, the RecipentList class is provided.
Since a message can be sent to more than one recipient, the recipients are managed as a list.
The Add( ) and Remove( ) methods are provided to add to and remove a recipient from the list.
SmsManager* pSmsManager = new SmsManager();
pSmsManager->Construct(*this);
RecipientList recipient;
recipient.Add (RECIPIENT_TYPE_TO, L"01012345678");
Android Developer’s Guide for bada
114
recipient.Add (RECIPIENT_TYPE_TO, L"01078901234");
SmsMessage smsMessage;
smsMessage.SetText(L"Hello World!");
pSmsManager->Send(smsMessage, recipient, true);
To handle a received SMS message, you can do as follows. First, declare a class by inheriting
ISmsMessageEventListener and implementing OnSmsMessageReceived()method. Then, call
SmsManager.AddSmsMessageEventListener() with the instance of the declared class as an
argument.
class SmsMessageEventListener: public ISmsMessageEventListener
{
public: void OnSmsMessageReceived(const SmsMessage &message);
};
// Reception
void ReceiveSmsMessage::SmsTest(void) {
SmsListener smsListener;
SmsMessageEventListener smsMessageEventListener;
// Register the listener to SmsManager
r = smsManager.Construct(smsListener);
r = smsManager.AddSmsMessageEventListener(smsMessageEventListener);
}
// Handles the SMS reception event.
void SmsMessageEventListener::OnSmsMessageReceived(const SmsMessage &message)
{ // Do something
}
An MMS (Multimedia Messaging Service) enables users to not only send text but also audio,
images and videos in the message. In bada, you can send an MMS message using the
MmsManager, MmsMessage and RecipentList classes. While an SMS message does not have
a title, an MMS message needs a title. To check if an MMS message has been sent
Android Developer’s Guide for bada
115
successfully, you can use the Osp::Messaging::IMmsListener interface. You can perform
necessary jobs after sending a message by overriding the OnMmsMessageSent event handler.
MmsManager mmsManager;
mmsManager.Construct(*this);
MmsMessage mmsMessage;
mmsMessage.SetSubject(L”MMS Subject");
mmsMessage.SetText(L"Hello World!");
mmsMessage.AddAttachment(MMS_IMAGE, L”/Home/mms.png”);
RecipientList recipients;
recipients.Add (RECIPIENT_TYPE_TO, L”+82312798535");
recipients.Add (RECIPIENT_TYPE_CC, L”+82312792288”);
mmsManager.Send(mmsMessage, recipients, true);
The Email function is provided by the EmailManager class for which the basic usage is the
same as that for an MMS. To send an email, the EmailMessage class is provided.
To check if an email has been sent successfully, you can use the
Osp::Messaging::IEmailListener interface. You can perform necessary jobs after sending an
email by overriding the OnEmailMessageSent event handler.
EmailManager emailManager;
emailManager.Construct(*this);
EmailMessage emailMessage;
emailMessage.SetSubject(L”Email Subject");
emailMessage.SetText(L"Hello World!");
emailMessage.AddAttachment(MMS_IMAGE, L”/Home/email.png”);
RecipientList recipients;
recipients.Add (RECIPIENT_TYPE_TO, L”[email protected]");
recipients.Add (RECIPIENT_TYPE_CC, L” [email protected]”);
Android Developer’s Guide for bada
116
emailManager.Send(emailMessage, recipients, true);
9. Location Based Service of bada for Android
developers
Location-based services (LBS) allow
their mobile device using the global
In Android, to use Google Maps using
library and not the Android framework,
this case are the tiles of the Google
location information and show the
Overlay class displays the location
shown below, in Android, you can
address information using the android.location
Figure 9.1
To apply the coordinate information
Google API, the coordinate information
Geopoint, and the Google Map is
buttons at specific locations on the
OverlayItem.
Android Developer’s Guide for
Location Based Service of bada for Android
allow device users to determine the geographical
global positioning system (GPS).
using the location information, you have to use
framework, the Google API, and receive the Map API
Google Maps properly displayed on the MapView. To
the location on the map at the corresponding coordinates,
location on the map using the icon of the OverlayItem
can manage the GPS signal as coordinate information
android.location package to acquire the location information.
1 Android’s Location package classes
information of the Geocoder / Address class to a Google
information is converted to the map coordinates management
is displayed as a MapView. In addition, to arrange
the MapView, use the class that implements the
Android Developer’s Guide for bada
117
geographical position of
an external
API key. Only in
To acquire the
coordinates, the
OverlayItem class. As
information and the
information.
Google Map using the
management class
arrange icons and
Overlay and
Figure 9.
Samsung bada location features
sub-namespaces, Osp::Locations::Services
9.1 Location Namespace
In bada, through the Osp::Location
changes through the ILocationListener
acquires the location information
Figure 9
Android Developer’s Guide for
.2 Android’s Google Map API Classes
are handled by the Osp::Locations namespace
Osp::Locations::Services and Osp::Locations::Controls.
Location Namespace
Osp::Location namespace, the LocationProvider class detects
ILocationListener event, changes the location of the Location
information as a result.
9.3 bada’s Osp::Location Namespace
Android Developer’s Guide for bada
118
namespace and its two
detects location
Location class and
Android Developer’s Guide for bada
119
The Osp::Location
Namespace
Android class Descriptions
LocationProvider android.location.Loca
tionProvider
Receives a Location object and gets the
location information including the latitude,
longitude, altitude, speed and course.
Location android.location.Loca
tion
Provides the time-stamped coordinates,
accuracy, speed and course. The positioning
method used for the location and the satellite
information.
Coordinates android.location.Geo
coder
Provides the coordinate information including
the latitude, longitude and altitude.
QualifiedCoordinates android.location.Crite
ria, Geocoder
Provides qualified coordinate information
including the latitude, longitude and altitude.
Landmark com.google.android
.maps.Overlay
Provides the icons that can be displayed on
the map.
LandmarkStore Saves the specified location on the device or
the bada server.
AddressInfo android.location.Addr
ess
Address information
GeographicArea Provides the geographical area on the surface
based on the WGS 84 Ellipsoid standard.
ILocationListener android.location.Loca
tionListener
Called when the LocationProvider state is
changed.
IAreaListener Called when the phone enters the specified
area.
The LocationProvider item gets the location information in the following three methods.
Location Method Descriptions
LOC_METHOD_GPS GPS
LOC_METHOD_WPS Wi-Fi + Cell Phone Base Station
Android Developer’s Guide for bada
120
LOC_METHOD_HYBRID GPS + WPS
9.2 Location Services
You can get the geographic information from LocationProvider, display the map on the phone
and display a specific location on the map. You can use the following services.
Location Services Description
Geocoding service Converts an address to coordinates and vice versa.
Route service Provides a path between two points.
Directory service Provides a location search service.
A. Location Service Provider
bada provides location information through the location service provider deCarta. To use the
deCarta location service provider, you must obtain a client name and password for the bada
platform from the deCarta developer zone (http://developer.decarta.com)
You can connect to the service provider deCarta in an application using the following source
code.
ProviderManager::ConnectToServiceProviderN (L"", LOC_SVC_PROVIDER_TYPE_MAP,
L"ClientName=<client_name>;ClientPassword=<client_password>;HostUrl=http://mapdev.osps
erver.net/openls/openls");
The first argument is the service provider name, and the second argument is the service type of
the service provider. The third argument is the URL for the service provider. The service
provider’s service type is pre-determined as the following constants in the
Osp::Locations::Services::LocationServiceProviderType namespace.
Service Provider Type Description
LOC_SVC_PROVIDER_TYPE_MAP The service provider type for map services.
LOC_SVC_PROVIDER_TYPE_ROUTE The service provider type for map services.
LOC_SVC_PROVIDER_TYPE_GEOCODING The service provider type for the geocoding
Android Developer’s Guide for bada
121
and reverse geocoding services.
LOC_SVC_PROVIDER_TYPE_DIRECTORY The service provider type for map services.
B. Map controls
The Osp::Locations::Controls namespace displays the map using the map controls (render
maps in layers, display user locations, handle overlays, display information windows, and allow
easy user input). The namespace provides the following features.
Location Services Description
Map Rendering Enables the construction of a multi-layer and drawing maps
on the screen.
Information Windows Provides additional information about the location on the
map.
Mylocation Displays the current location on the map.
Overlay Displays the various shapes of the icons to represent
locations on the map.
User input handling Enables users to zoom-in and pan maps and view paths.
To display the current location of the user on the map, construct a
Osp::Locations::Controls::Map object and set the size of the map. Set the zoom level and center
the map on the screen. Then enable MyLocation. If My Location cannot be enabled, ask the
device user to enable location services in the device system settings under Settings > Location
by selecting the Enable location services check button. Then, finally, the map is drawn on the
Canvas.
pMap = new Map();
r = pMap->Construct( Osp::Graphics::Rectangle(0, 0, width, height),
*pProvider);
r = pMap->SetZoomLevel(17.0, false);
r = pMap->SetCenter(center, false);
pMap->SetMyLocationEnabled(true);
r = pMap->Draw();
Android Developer’s Guide for bada
122
r = pMap->Show();
C. The location provider and remote location provider
Using Osp::Locations::LocationProvider, you can get the basic location information of the
latitude, longitude, altitude, speed, and course. In addition, you can identify whether a terminal
entered a specific area through the area monitoring service. To track the current location, you
have to use the listener as follows. Create a class to implement ILocationListener.
class LocationListener : public ILocationListener
Construct the LocationListener and LocationProvider objects, and set the interval for
RequestLocationUpdate() to update the current location periodically.
LocationListener *pListener = null;
pListener = new LocationListener();
LocationProvider pLocProvider;
pLocProvider.Construct(LOC_METHOD_HYBRID);
int interval = 5;
pLocProvider.RequestLocationUpdates(*pListener, interval, false);
D. Landmarks
You can display a specific location
addition, you can save a location
you can save and retrieve your landmarks
Osp::Locations::RemoteLandmarkStore
Android Developer’s Guide for
location on the map using Osp::Locations::Landmark
location using the Osp::Locations::LandmarkStore class.
landmarks from the bada server using the
Osp::Locations::RemoteLandmarkStore class.
Figure 9.4 bada's Landmarks
Android Developer’s Guide for bada
123
instances. In
class. In addition,
Android Developer’s Guide for bada
124
10. UIX of bada for Android developers
In Android, the sensors supported by Android are defined as constants of SensorManager.
Android SensorManger Sensor Constant Description
TYPE_ACCELEROMETER A constant describing a accelerometer sensor
type
TYPE_ALL A constant describing all sensor types
TYPE_GYROSCOPE A constant describing a gyroscope sensor type
TYPE_LIGHT A constant describing an light sensor type.
TYPE_MAGNETIC_FIELD A constant describing a magnetic field sensor
type.
TYPE_ORIENTATION A constant describing the device’s orientation.
TYPE_PRESSURE A constant describing a pressure sensor type
TYPE_PROXIMITY A constant describing an proximity sensor
type.
TYPE_TEMPERATURE A constant describing an ambient temperature
sensor type
The sensors in an Android device are registered to the SensorManager by the system service
and whenever the sensor value changes, you can get the value measured by the sensor
through the handler that implements the SensorListener.
10.1 bada's Sensors
Samsung bada supports the following sensor types: Acceleration, Magnetic, Proximity and Tilt.
Since these sensors are handled by extending user events, they are supported through the
Osp::Uix namespace. Uix stands for UI extension and contains unique features outside the
typical UI control scope.
Sensor Features
Proximity
The proximity sensor detects the presence of nearby
instances. It only reports on/off information. It corresponds to
the Proximity sensor of Android.
Android Developer’s Guide for bada
125
Tilt
The tilt sensor combines the 3-axis acceleration sensors and
3-axis magnetic sensors to determine the following angular
positions: Azimuth, Pitch, Roll
The combination of the accelerometer and the Magnetic-field
sensor of Android.
Magnetic
The magnetic sensor is a 3-axis electronic compass
(sometimes referred to as a magnetometer). It can also be
used to determine the orientation.
It corresponds to the Magnetic-field sensor of Android.
Acceleration
The acceleration sensor measures changes in velocity. It can
also be used in to determine the orientation.
It corresponds to the accelerometer sensor of Android.
10.2 Osp::Uix Namespace
Let's look at the major classes related to sensors.
bada Class Android class Features
FaceDetector
android.media.FaceDetector Locates faces in a still image or
video.
FaceRecognizer
Provides tools to identify a face in
a still image or video.
FaceRecognitionInfo
Provides information about a face
along with its location in a still
image or video.
Haptic
android.os.Vibrator Controls and plays vibration
effects on the device.
TouchEffect
Adds sound and vibration effects
to a UI or user-defined button.
Motion
android.hardware.SensorMana
ger
Receives notifications when the
device moves in some predefined
SensorManager
SensorData
WeatherSensor
N/A
CurrentWeather
WeatherForecast
10.3 SensorManager
If you register the listener handler
get the sensor value through events
Figure
To get the value of a sensor, you
event listener of the sensor you want
OnDataReceived() method by implementing
uses the sensor.
class MySensorListener : public ISensorEventListener
\
void MySensorListener::OnDataReceived(SensorType
result r)
Android Developer’s Guide for
manner.
Adds and removes
listener and provides
on sensors.
Stores the sensed
N/A Requests weather
and internally adds
a listener.
Stores the current
Stores the weather
the next day.
SensorManager
handler of a sensor to the Osp::Uix::SensorManager object,
events whenever the value is changed.
Figure 10.1 bada’s Sensor Listener
you have to construct the SensorManager object and
want to the object. To do this, you have to redefine
implementing Osp::Uix::ISensorEventListener in the
ISensorEventListener {
MySensorListener::OnDataReceived(SensorType sensorType, SensorData&
Android Developer’s Guide for bada
126
removes a sensor
provides information
sensed data.
weather information
adds and removes
current weather data.
weather forecast for
object, you can
and register the
redefine the
the class that
SensorData& sensorData,
Android Developer’s Guide for bada
127
{
long timeStamp = 0; float x = 0.0, y = 0.0, z = 0.0;
sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_TIMESTAMP,
timeStamp);
sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_X, x);
sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Y, y);
sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Z, z);
AppLogException("####################SensorType[%s],
TimeStamp:[%d], Accel.x,y,z:[%f,%f,%f]",
SensorTypeToNameTable[sensorType],
timeStamp,
x, y, z);
}
}
If you add the event listener for a particular sensor and the sensor to the SensorManager,
whenever the sensor value is changed, the changed value of the sensor is sent to the
OnDataReceived( ) event handler.
SensorManager* pSensorManager = new SensorManager;
pSensorManager->Construct();
r = pSensorManager->AddSensorListener(*pListener, SENSOR_TYPE_ACCELERATION,
interval, false);
The used sensors should be released using the RemoveSensorListener(listener) method at the
end of the application life cycle.
10.4 Device Motions
Android detects the movement, rotation and direction of the device using the Accelerometer,
Gyroscope and Orientation sensors. Developers can detect motions by registering the
SensorEventListener to the SensorManager and measure the changes of the x, y and z values
of the corresponding sensor. These values are provided through the MotionEvent class.
In bada, your application can receive
Osp::Uix::Motion class, where the
double-taps, shaking and snapping
Double tap
Since the Snap result value changes
necessary.
Figure 10.
To implement an application that
in the class and implement the methods
class MotionExample : public Osp::Uix::IMotionEventListener
{
. . .
void MotionExample::OnDoubleTapDetected(void)
// Do something...
}
void MotionExample::OnShakeDetected(MotionState
Android Developer’s Guide for
receive notifications and information on motion events
the device moves in a predefined pattern. bada can
snapping motions.
Shake Snap
Figure 10.2 bada’s Motions
changes depending on the orientation, the following
.3 bada’s Snap events of +X, +Y and +Z
that detects motion, you have to implement IMotionEventListener
methods for the three modes.
Osp::Uix::IMotionEventListener
MotionExample::OnDoubleTapDetected(void) {
MotionExample::OnShakeDetected(MotionState motionState) {
Android Developer’s Guide for bada
128
events using the
can detect
Snap
following separation is
IMotionEventListener
Android Developer’s Guide for bada
129
// Do something...
}
void MotionExample::OnSnapDetected(MotionSnapType snapType) {
//
}
. . .
To make the sensor detect an action, you have to specify the action type to the Motion object.
private: Osp::Uix::Motion* pMotion;
\
result MotionExample::Initialize(void)
{
pMotion = new Motion();
pMotion->Construct(*this);
pMotion->SetEnabled(MOTION_TYPE_DOUBLETAP | MOTION_TYPE_SHAKE);
return E_SUCCESS;
}
11. Packaging
developers
To install and run an application
the application with the developer's
channel such as the Android market
key to the application on the basis
prevents unauthorized persons from
signing an application and uploading
Figure
Then register the signed application
(http://market.android.com/publish
description.
In bada, developers should register
site (http://developer.bada.com),
IDE and registers the application
Android Developer’s Guide for
selling application in bada for Android
on an Android or bada Smartphone, the developers
developer's private key and upload the application to a distribution
market or Samsung Apps. This signing procedure applies
basis of the host machine (computer) of the developer,
from registering a developed application to the market
uploading an application to the market because the key
Figure 11.1 Android's packaging
application binary file to the publishing site
http://market.android.com/publish) of the Android market with the necessary image
register the developed application to the Samsung bada
issue the manifest.xml file, build the application
application to the Samsung Apps Seller site.
Android Developer’s Guide for bada
130
selling application in bada for Android
developers should sign
distribution
applies a unique
developer, and
market by
key is different.
image and
bada developer
application in the Eclipse
Android Developer’s Guide for bada
131
11.1 Registering Developers
Registering the application to Samsung Apps requires building with the certified manifest.xml file
followed by the completion of the packaging. The certified manifest.xml file can be received after
registering with the bada website (http://developer.bada.com) as a developer. The application
registration process for an already registered bada developer is as follows.
11.2 Issuing Application IDs
First, select the Application Manager from the MyApplication menu.
Figure 11.2 bada’s MyApplication
Select the Generate a New Application Profile button to move to the Basic Information screen
where you can enter the description about the application.
Figure 11.3 Generate a New Application Profile button in the ApplicationManager
In the Basic Information screen, you should fill in the Set your application name field and check
for duplication. Then enter a description about the application in the “Describe your application”
field. Fields with the * mark must be filled in.
Android Developer’s Guide for bada
132
Figure 11.4 Basic Information of the ApplicationManager
Then you have to enter the Application version and API version in the Advanced Information
screen. First, fill in the Application version field.
Figure 11.5 The version field in the Advanced Information
Then select the API version. Be aware that if bada 2.0 is selected, the application type needs to
be selected from 4 types of applications.
Figure 11.6 Selecting the bada 1.x application type in the Advanced Information screen
Android Developer’s Guide for bada
133
For bada 2.0 API, the application should be specified as one of the four application types.
Figure 11.7 Selecting the bada 2.0 application type in the Advanced Information screen
Clicking the Generate button after entering the application information generates the
manifest.xml file.
Figure 11.8 Completion
11.3 Configuring the Privileged API for the Application
bada’s manifest.xml file contains the privileges for the device resources for applications as well
as the application ID. Therefore, after the completion of the Application ID generation, the
privileged API should be selected. For example, if you want to use the Notification service, you
have to select the service as shown by the figure below. In the same context, the Camera
privilege should be selected in the Media field in order to use the camera.
Android Developer’s Guide for bada
134
Figure 11.9 Selecting a Privileged API
After the selection, click the Next button to finish the configuration.
11.4 Creating the manifest.xml file
After selecting bada based mobile phones compatible with the OS type selected in the
Advanced Information screen, clicking the Finish button generates the manifest.xml file.
Figure 11.10 Download manifest.xml
Then, if you download the manifest.xml file here, the application registration is completed. Then,
let's look at how to replace the manifest.xml file in the Eclipse project and build the application.
You can reissue the manifest.xml file by clicking the application name in the bada developer site
or selecting the MyApplication menu and modifying the app information of the site. If the API
version to be used is changed, press the Modify button in the version information page to
change the API version.
11.5 Extracting an App from Eclipse
Overwrite the default manifest.xml file in the root directory of the Eclipse project with the
downloaded manifest.xml or back up the downloaded manifest.xml file.
Android Developer’s Guide for bada
135
Figure 11.11 Download manifest.xml
Then change the Build Configuration to Target-Release to build the application for real bada
Smartphone devices. When the build is complete, run Make Package to create the package file.
Figure 11.12 Generating the bada app package with Make Package
11.6 Registering with Samsung Apps
You can use the developer ID that you registered with on developer.bada.com, on the
seller.samsungapps.com site. In the initial login, you can sign up as a Private or Corporate
Seller.
Android Developer’s Guide for bada
136
Figure 11.13 Seller types in Samsung Apps
To register as a seller, fill out the form and receive a confirmation by email. Clicking the URL in
the confirmation email will complete the registration process. Now you can login as a seller and
proceed with the registration process, depending on the application types.
Figure 11.14 Selecting the Application Type in Samsung Apps
The app registration process consist of the Basic information, Display information and Final
Review screens. Fill in the forms in sequence.
Figure 11.15 The Application Registration Process in Samsung Apps
As the first step, enter the basic information of the application in the Basic Information screen so
that the application can be found by the Samsung Apps search system. Let’s have a look at
some of the important information. Start with selecting bada in the Select OS field and then the
screen resolution.
Android Developer’s Guide for bada
137
Figure 11.16 OS Selection during the Application Registration
Then select the category of the application.
Figure 11.17 Category Selection during the Application Registration
In the binary file registration screen, once a zip file created by Make package is selected, the
bada application is validated by the server and the result is displayed.
Figure 11.18 Registering the binary file during the application registration
Once this step is completed, the download status can be monitored by MyApplication in the
Application tab. The application approval takes 7 working days and a game application takes 15
working days.
11.7 Using Mobile
In the case of Android, you can get
register your application to the Android
However, unlike Android, bada applications
possible to install applications under
registering a certification to the mobiles
On a Wave phone, select Settings
phone to a removable memory device.
Figure 11.19 Changing the device to a Removable Memory Device
Now the Test Root certification needs
rootCaCert.cer file located in the
Copy the file to the Other folder of
For Wave phones, run the My Files
rootCACert.cer file which was copied
Select this file to install the certification
Android Developer’s Guide for
Mobile Devices
get a Google developer account at $25/year and
Android market.
applications can be developed and released for free.
under development on mobile devices, and it only
mobiles devices in use.
Settings > Connectivity > USB utilities> Mass storage
device.
Changing the device to a Removable Memory Device
needs to be copied and registered. The Root certification
Tools\sbuild folder under the directory where bada
of the mobile device.
Files program and select the Other folder, then you
copied in the previous step.
certification and then connect the mobile device.
Android Developer’s Guide for bada
138
and immediately
free. It is also
only requires
to change the
Changing the device to a Removable Memory Device
certification is the
bada is installed.
you will find the