Professional Documents
Culture Documents
Tizen For Dummies
Tizen For Dummies
Contents at a Glance
Introduction....................................................... 1
Part I: Introducing Tizen..................................... 5
Acknowledgments.......................................... 199
Table of Contents
Introduction........................................................ 1
About This Book......................................................................... 1
Conventions Used in This Book ............................................... 1
Who Should Read This Book..................................................... 2
How This Book Is Organized..................................................... 2
Part I: Introducing Tizen.................................................. 3
Part II: Getting Practical................................................... 3
Part III: Tizen in Detail...................................................... 3
Part IV: The Part of Tens.................................................. 3
Icons Used in This Book............................................................. 4
Where to Go from Here.............................................................. 4
vi
Table of Contents
vii
viii
Table of Contents
ix
Table of Contents
Acknowledgments........................................... 199
xi
xii
Introduction
Introduction
The Tip icon points out important information that can save
you time or make a task easier.
This icon marks information you wont want to forget.
Be careful when you see this icon!
Part I
Introducing Tizen
In this part . . .
Chapter 1
Getting an Inside
Look at Tizen
In This Chapter
Discovering what makes Tizen unique
Becoming part of the Tizen community
Discovering Tizen
Tizen is an open source, standards-based, cross-architecture
device software platform designed to find a place in
everything from smartphones to smart TVs and beyond.
The Linux Foundation announced the Tizen project in
September 2011 and the Tizen Association was formed in 2012
to drive industry engagement and support for the project.
Currently, the main contributors to Tizen are Samsung and
Intel, but with increasing industry support, you can expect
more organizations to become active contributors. Currently,
the Tizen Association board has 12 members from different
industry sectors, including many mobile operators.
You can find out more about Tizen and the Tizen Association
at www.tizen.org and www.tizenassociation.org.
Focusing on HTML5
Tizens primary focus for application development is HTML5,
which is rapidly emerging as the preferred development environment for mobile applications. Tizen support for HTML5
is extensive and powerful. It includes support for most of the
major W3C APIs included under the banner of HTML5, as well
as many supplementary web APIs.
The first prerelease version of Tizen emerged blinking into
the spotlight of the developer community in January 2012.
The final 1.0 version, code named Larkspur and including
Linux and Windows versions of the SDK and the Tizen Web
UI framework, was released in May, just before the first Tizen
Developers Conference in San Francisco. At this event, the
attendees were given a reference device, known as the software development platform (SDP), or lunchbox, as it is nicknamed due to its less than svelte appearance.
The version of Tizen we used to create this book is 2.1, which
was released in May 2013, and introduced many new web
APIs. The Tizen 2.0 SDK was the first to include C++ APIs
which you can use to create native apps. However, web apps
are still the main way of developing for Tizen and thats the
focus of this book.
expected to be an expert in everything from application development to the low-level technologies that enable your phone
to talk to the cellphone towers. Figure 1-1 shows the different
perspective that users, application developers and platform
developers have on the way a typical open source platform is
organised. Put yourself in the shoes of each of these people
as we show you how Tizen fits in to the mobile open source
landscape.
10
11
Tizen is open
As an open source software platform, Tizen provides many
opportunities for both individuals and Original Equipment
Manufacturers (OEMs) the people that make the phones.
Anyone can grab the source code and customize it to meet
their own needs. Any OEM can ship Tizen devices with a customized user interface, app store, or set of services.
Open source projects also encourage collaboration. Software
engineering is changing, and its a challenge for an individual
or even an organization to build something without using
open source code. Collaborating with the open source community is a more efficient and cost-effective way of development, and it generally avoids re-inventing the wheel.
Defining open
At any gathering of open source
developers, the one subject
guaranteed to cause an argument
aside from which pizza restaurant to
order from is What is the definition
of open source?
In this book, we describe Tizen as
open source because the source
12
Tizen is innovative
Innovation can come from many sources. It may be an idea
from an individual or an organisations R&D projects, but
most innovation comes from collaboration.
The Tizen Project brings these different resources and knowledge together. Everyone can contribute ideas and innovations
to the platform, and everyone can benefit.
Innovation doesnt stop at collaboration; it also brings differentiation to a product and leads to more choice for end users.
Comparing Tizen to
Other Platforms
Tizens openness contrasts with closed, proprietary platforms, such as iOS, Blackberry 10 and Windows Phone, for
which the source code is not available. The choice for users
of these platforms is also limited, with only Windows Phone
licensed to other manufacturers and the rest available only on
the vendors devices.
13
Getting Involved
You can participate and contribute to the Tizen Project at different levels. As described on the Tizen website (www.tizen.
org), you can be a platform contributor, an application developer, a user, or a Tizen product vendor.
At the platform level, the membership for the TSG (for example, groups responsible for areas such as Release Engineering,
Quality Assurance, and Program Management) is invitation
14
Submitting patches
If you think you can improve the existing code of the Tizen
platform, you can submit your changes to the Gerrit system
for code review. The maintainer, release engineers, and the
QA team will review your patches and decide whether they
will be accepted based on the quality of your code. Once the
changes are approved, you can submit them to the Gerrit
system and Gerrit will merge the changes into the Tizen code
base. You can find a guide to submitting changes at:
https://source.tizen.org/documentation/
developer-guide/submitting-patches
The Tizen wiki is available for collaborating on documentation
related to the Tizen project:
https://wiki.tizen.org/wiki/Main_Page
If you have any information or tutorials you want to share
with the community, youre free to add them to the wiki.
However, before contributing, you should check the User
Guide and style guides.
15
Forums
Another source of help and information are the forums available on the Tizen developer site:
https://developer.tizen.org/forums
The forums are available to any developer with an account to
ask questions, contribute to discussions, and share information.
Bug tracker
Tizen uses JIRA to track bugs and gather requests for new
features:
https://bugs.tizen.org/jira
Anyone with a tizen.org account can add a new bug, comment
on an existing bug, or even submit a patch to fix a bug.
16
Chapter 2
18
Going native
The 2.1 release of the Tizen SDK
includes a set of C++ APIs which
you can use to create native apps.
Depending on your requirements,
you can choose whether to create a
web app or take the native approach.
Developing a native app is a good
choice if your app is performance
intensive or you need access to
19
20
Installer
When an application is installed, the Tizen package manager
is called to install the web application. The package manager invokes the web runtimes app installer program, which
checks that the app is properly signed and then starts the
installation. Once installed, the app is registered with the web
runtime database using the information supplied in the apps
configuration file, including the app ID, name of the app, and
icon. The apps icon then appears in the menu screen.
When the user uninstalls an app, the app is unregistered from
the web runtime database, and all app resources are removed
from the client.
Runtime core
The runtime core is responsible for managing the lifecycle of
an application, including startup, suspend and resume, and
terminate.
When an app launches, the Tizen launchpad executes the
web app process. This creates a new process for the web app
and initialises some of the callbacks that will be invoked for
certain system events. When an app is initially launched, the
runtime will retrieve the web apps start file, usually called
index.html, initialise the web view and load this .html file.
If the app provides a service for example, getting an image
from a web service then this feature will be registered as
a service, using the Image MIME type. When another app
requests the image service, the app will receive the request
and handle it.
The Tizen web runtime rendering engine is based on WebKit2.
This is the same WebKit used in the Tizen browser. As a
result, web apps can take advantage of the same HTML5 APIs
and the same 2D and 3D optimisations and CSS3 optimisations
that the built-in browser uses.
21
Plugin core
The plugin core is what enables the web app to talk to the
device/platform via JavaScript APIs. It communicates with
the JSCore module in the platform layer (refer to Figure 2-1)
and implements on-demand loading of plugins at runtime. The
advantage of on-demand loading of plugins is that the web
app starts faster because plugins are loaded only when the
JavaScript needs them.
22
23
that new W3C standards are introduced that provide the same
functionality as some of the Tizen device APIs discussed in
this book. In this case, you should update your application to
use these APIs and help to make your apps more portable and
future proof.
You can find a complete specification of the device APIs in
the SDK help, but the following sections provide a quick overview and point you to the more detailed information and code
samples in later chapters.
The SDK also includes code samples covering most of the
device APIs; see Chapter 3 for more information on using the
samples included with the SDK.
Tizen
The Tizen JavaScript object is used to access device APIs
such as Contact, Calendar and NFC.
For example, to access the default address book, you use the
following code:
var addressBook = tizen.contact.
getDefaultAddressBook();
The contact object is a property of the tizen object and contains a ContactManager object, which provides access to
the Contacts API, including the getDefaultAddressBook()
function. The same pattern is used with the other device APIs.
Throughout this book and in the Tizen SDK, the web Interface
Definition Language (IDL) is used to describe APIs in a language independent way. This allows the APIs to be described
using terms familiar to those of you with a background in
strongly typed object oriented languages, such as C++, even
though the APIs are accessed through JavaScript.
Apart from being the base object used to access the other
device APIs, the tizen object also provides access to a set
of generic functions, including error handling and filters.
Chapter 9 demonstrates how to use filters.
24
Alarm
The Alarm API allows you to set an alarm to run an application
at a specified time and launch it if its not already running.
Application
The Application API allows you to retrieve a list of running
applications and launch other apps by using an application
control. So, you might launch the camera app to take a picture
or record video or use the media player to play music files.
You can also provide services to other apps. Chapter 9 covers
launching an application using an application control.
Bookmark
The Bookmark API provides access to the devices bookmarks. You can use it to retrieve bookmarks, as well as add
and remove both bookmarks and bookmark folders.
Bluetooth
The Bluetooth API provides access to the Bluetooth protocol,
which can be used for transmitting files over short distances
between devices.
Calendar
The Calendar API allows you to manage events and tasks
so that it can handle your schedule or to-do list. Chapter 13
explains the Calendar API in detail.
CallHistory
The CallHistory API provides access to the call history functionality, such as finding and removing call history entries.
25
Contacts
You use the Contacts API to manage contacts and handle multiple address books. Chapter 12 explains the Contacts API in
detail.
Content
The Content API lets you search for content on the device,
either stored locally or on a memory card. Chapter 9 shows
you how to use these features.
DataControl
The DataControl API, introduced in Tizen 2.1, is used to
access data exported by other applications, for example
native applications. You can use the functionality provided
by the DataControl API to operate on both SQL and key-value
databases.
DataSynchronization
The DataSynchronization API, supported from Tizen 2.1,
allows you to synchronize device data with a server using the
OMA Data Synchronization 1.2 protocol.
Download
The Download API, introduced in Tizen 2.0, is used to download files from the Internet and monitor the download status.
Filesystem
The Filesystem API provides access to the devices file system.
The SDK includes more information, including tutorials.
26
MessagePort
The MessagePort API allows you to exchange data with
another web application, or with a native application. Data is
sent using the RemoteMessagePort, and data is received from
the LocalMessagePort.
Messaging
The Messaging service allows you to send SMS, MMS, and
Email messages and search messages on the device. Chapter 11
explains this API in more detail and provides source code for
searching SMS messages on your device.
NetworkBearerSelection
The NetworkBearerSelection API, new to Tizen 2.1, allows you
to specify a particular network connection to be used from
your web applications to connect a given domain or host.
NFC
Near Field Communication (NFC) is used for short range wireless communication. NFC enabled devices can be used for
mobile payments and in a range of other applications. We
explain Near Field Communication (NFC) in detail in Chapter 10.
You discover the different applications of NFC technology and
how to use NFC in your Tizen web apps.
Notification
The Notification API, introduced in Tizen 2.0, provides a way
of alerting the user to events happening in your app. You can
find details of how to create and manage notifications in the
SDK help.
27
Package
The Package API, new to Tizen 2.1, allows you to install and
uninstall packages, retrieve information about the packages
installed on the device, and monitor any changes to installed
packages.
Power
Another new API introduced in Tizen 2.0, this provides access
to a devices power state and allows you to control display
dimming and brightness, for example. More information,
including a tutorial are included in the SDK.
Push
The Push API, new in Tizen 2.1, allows web applications to
receive push notifications from the push server.
SecureElement
The SecureElement API, introduced in Tizen 2.1, provides
access to secured elements on the device, such as a UICC/SIM,
embedded security element or secure SD card.
SystemInfo
Provides access to device specific information, such as local
storage, battery levels, cellular network, and so on. More
information and a tutorial are included in the SDK.
SystemSetting
The SystemSetting API, introduced in Tizen 2.0, lets you get
and set various device properties. At the time of writing you
can get and set the following device properties: the device
and lock screen wallpaper, the ringtone for incoming calls and
the email message notification sound.
28
Time
Provides date and time functions, including working with the
current date and time and locale specific date and time handling. Chapter 13 uses the Time APIs to set the date and time
of calendar tasks.
Part II
Getting Practical
In this part . . .
Chapter 3
Getting Started
In This Chapter
Installing the Tizen SDK
Building your first web app
Getting Help
etting to grips with a new platform can feel like travelling to a country for the first time. You may be the
kind of traveller who likes to turn up at the airport hours in
advance, with a well-planned itinerary, phrase book, and a list
of the local hotspots. Or, like some authors we could mention,
you may prefer to run to catch your flight, carrying only a
pair of sunglasses and a smile. Both travellers will get to their
destination, both will probably have a good time, but for all
their spontaneity, the less prepared traveller may be left with
a nagging feeling that he may have missed out on something.
In this chapter, you find everything you need to build your
first Tizen app. If youre feeling adventurous or just cant wait
to get coding, this chapter will be all you need to get started.
But if youre new to web development or the Eclipse IDE or
you just want to make sure that you get the most out of the
development environment before diving in head first, then
think of this chapter as the first part of a trilogy.
Chapter 4 looks at each component of a Tizen app in detail,
while Chapter 5 uncovers the secrets of testing and debugging. Tizen development may not be everyones idea of an
adventure, but youll be well prepared for the trip.
32
Getting perspective
A perspective describes the layout
of views to help you achieve a
particular task. In the case of the
default Tizen Web Perspective, that
task is web development, so youll
see views including the Connection
Explorer, and HTML Web Page Editor.
Chapter 5 introduces the Connection
Explorer, while the HTML Web Page
33
a separate SDK image file and choose to install the SDK from
this package.
This latter approach allows you to complete the SDK installation when youre not connected to the Internet.
After you install the SDK, the first time you launch the IDE
youre asked to select a workspace. On the Welcome screen
that appears, choose the Workbench option. The Tizen Web
Perspective appears, as shown in Figure 3-1.
34
Its well worth taking a look at all the templates and sample
code provided in the IDE, to give you a head start creating
your app.
To launch the New Project wizard and choose a template,
follow these steps:
1. In the IDE, choose FileNewTizen Web Project.
Tizen Web UI Builder: A set of templates containing all the files to create a web application
using the Tizen Builder.
4. Click Finish.
35
These templates include the basic structure for an application and all the relevant JavaScript libraries required for the
selected UI framework. All you need to do is add your application specific code.
36
2. From the Select an Export Destination list, doubleclick the Tizen folder icon and then select the Tizen
User Template, as shown in Figure 3-3.
3. Click Next.
37
6. Click Next.
8. Click Next.
1. Choose FileImport.
3. Click Next.
5. Click Finish.
The project is imported into the workspace.
38
Figure 3-4: The Import dialog box of the New Project Wizard.
1. Choose FileNewProject.
3. Click Next.
5. Click Finish.
Your project is now created and loaded into the workspace.
After you create the project, you need to edit two files:
.project and config.xml. You can find full instructions on
how to edit these files on the Tizen developer website:
https://developer.tizen.org/downloads/sampleweb-applications/load-web-app-tizen-sdk
39
40
Table 3-1
HTML View Modes
41
HTML Preview
You can instantly preview a HTML file using the HTML
Preview tool (see Figure 3-7). Google Chrome is used to display the Preview, so the appearance will be more accurate
than the preview in the Web Page Editor, which uses your systems default browser.
To view your HTML file in the HTML Preview tool, select the
Preview button from the IDEs toolbar.
CSS Preview
You can instantly preview the look and feel of any CSS file
using the CSS Preview tool, shown in Figure 3-8. Google
Chrome is used to display the content in the Preview, and any
changes you make will be reflected immediately.
To view your CSS file in the CSS Preview tool, select the
Preview button from the IDEs toolbar.
42
CSS
The CSS tool removes comments, white space, extra semicolons, empty declarations, zero values, and so on from your
CSS code.
To minify your CSS file, right-click the file in the Project
Explorer, and the options in Figure 3-9 appear at the bottom of
the list. Choose the Minify CSS option, and the file is minified
with a new version of the file (.min.css) created.
43
JavaScript
The JavaScript tool removes comments and extra white
space, replaces identifiers, and performs micro-optimisations
in your JavaScript code.
To minify your JavaScript file, right-click the file in the Project
Explorer, and the options in Figure 3-10 appear at the bottom
of the list. Choose the Minify JS option, and the file is minified
with a new version of the file (.min.js) created.
44
Help documentation
You can find the most up-to-date information about Tizen in
the SDK Help documentation. You can open the Help from
within the IDE, by choosing HelpHelp Contents. You can
also access Help on the Tizen website:
https://developer.tizen.org/documentation
Here are some of the most useful Help sections to consult to
find out more about the platform and creating apps:
Getting Started with Tizen/Overview/Architecture
describes the platform architecture and introduces the
components that make the platform.
Getting Started with Tizen/Development Environment/
Tizen SDK describes the tools available in the SDK and
tips on how to use them.
Tizen Web App Programming/API References/Device
API Reference provides detailed information about the
Tizen device APIs and how to use them within your web
application. This specification uses Interface Definition
Language (IDL), which is used to describe APIs in a language independent way.
45
Tizen Web App Programming/Programming Guide
includes the Device Guides, which explain the functionality of each device API and provides code examples for
the main features.
Tizen Web App Programming/Tutorials includes tutorials
that take you step by step through some more detailed
examples for the main APIs.
Tizen Web App Programming/API References/UI
Framework Reference is a guide to all the Tizen Web UI
Framework widgets and offers examples of how to use
them in your web application.
Sample applications
In addition to the tutorials and the sample applications provided in the SDK, several sample web applications are available for download from the Tizen developer site:
https://developer.tizen.org/downloads/sampleweb-applications
These applications use a variety of standard HTML5,
JavaScript, and CSS3 techniques and can be run either on the
desktop or a mobile device. Each application has a tutorial
describing the main features of the application and how they
were implemented.
You can use the instructions described in the Other web
applications section, earlier in this chapter, to import these
projects into the IDE.
See Chapter 1 for more details about the Tizen wiki, mailing
list, IRC channel, and forums.
46
Chapter 4
48
49
Localized content
The example shown in Figure 4-1 is missing one key ingredient
of a well-designed web app, and thats localized content.
One of the ways to ensure that your web app displays content
appropriate to the current locale is to use folder-based localisation. With this approach, you create a folder for each locale
for which youre creating localized content. For example, for
the French locale, put localized HTML files, images, and other
resources into the /locales/fr folder at the root level of
the application package. If the current locale is set to French,
then the platform will first look inside this folder for French
localized resources.
Figure 4-2 shows the package for an app using folder-based
localization.
50
51
<content src=index.html/>
<icon src=icon.png/>
<name>SysteminfoSample</name>
<tizen:privilege
name=http://tizen.org/privilege/application.read/>
<tizen:privilege
name=http://tizen.org/privilege/systeminfo/>
</widget>
The first line of the config.xml file is the declaration identifying the XML version and encoding used:
<?xml
version=1.0
encoding=UTF-8?>
The next part of the config.xml file defines the widget element and its attributes:
<widget xmlns=http://www.w3.org/ns/widgets
xmlns:tizen=http://tizen.org/ns/widgets id=http://
yourdomain/SysteminfoSample version=0.1.7
viewmodes=maximized>
</widget>
The namespace declaration will be the same for all Tizen web
apps. It just specifies that the app is a W3C format widget that
uses the Tizen-specific extensions.
The id attribute is mandatory and uniquely identifies your
widget in this case, the Systeminfo sample. If you have your
own domain name, then use it in place of yourdomain in
Listing 4-1. The id doesnt have to be a valid URL and is just
used for identification.
You can also set other optional attributes, including version,
height, width, viewmodes, and defaultlocale.
The widget element can also contain a number of optional
child elements, representing additional information about
your application. We explain what these elements are used for
in the next section.
52
Overview
In the Overview tab, you can enter general information about
your application.
53
The items shown in Table 4-1 are the attributes that you can
set through the Overview tab in the Configuration Editor.
Table 4-1
Type
Description
Identifier
Version
Name
Content
Icon
Widget
In the Widget tab, you can enter specific information about
your application.
The items shown in Table 4-2 and Table 4-3 are the attributes
that you can set through the Widget tab in the Configuration
Editor.
54
Table 4-2
Type
Description
Author
Web Site
License
License URL
Description
Description
Width
Height
View Modes
Features
In the Features tab, you can declare all the mandatory hardware and software components that are required by your
application. This information will be used by the Tizen application store to filter applications, ensuring that only those
applications which are compatible with a users device are
shown.
To add a feature to your applications config.xml file, select
the Features tab and click the Add button. A new row is added
to the Features table, and you can add the feature string.
55
Privileges
A privilege is a URI-identifiable runtime component for
example, an API such as http://tizen.org/privilege/
systeminfo. In order to access an API at runtime, your
application must register it in the config.xml file. To add a
new privilege to your applications config.xml file, select
the Privileges tab and click the Add button, as shown in
Figure 4-4.
If you select the Internal radio button, youll be able to select
from a list of Tizens built-in privileges. Optionally, using the
other radio buttons and text boxes, you can enter a URL or
the name of a file that contains a privilege definition.
After you select the new privileges, click the Finish button.
After you finish making changes to the configuration file,
choose FileSave or close the config.xml window and click
Yes when youre prompted to save your changes.
Access
The Tizen platform supports WARP, the W3C Access Request
Policy. So by default, applications are restricted from accessing network resources. If your application needs to access any
network resources, you must add them in the config.xml file.
56
Localization
The Tizen platform supports localization of selected elements
in the config.xml file, including the application name and
description.
Any elements that you can localize will be displayed in the
Localization tab. To localize a config.xml element:
Figure 4-5: Locales. Add any new locales you want to support.
57
4. To add the required localized strings for each language, start by clicking the triangle icon to reveal a
list of the locales selected in Step 2.
Preferences
A preference is a persistently stored name-value pair that is
associated with the application. You usually use a preference
58
Tizen
In the Tizen tab, you can enter any Tizen-specific information
about your application. This information includes the applications id, the minimum version of the APIs that the application
supports, the location of the start file if hosted on an external
server, settings such as screen orientation, support for context menus, background support, encryption and installation
location, and any app control information.
Table 4-4 shows the attributes that you can set in the Tizen
tab if your application provides an application control for
other applications to use.
Table 4-4
Tizen Information
Type
Description
src
operation
scheme
mime
Source
The Source tab shows the XML content of the config.xml
file. You can use this tab to view the values youve set up
using the other configuration tabs. You can also manually edit
the file.
59
Start file
The start file is the file that is loaded by the web runtime on
application startup. The New Project wizard provided in the
IDE creates a default application start-up file for you called
index.html.
Your start file doesnt have to be named index.html. You
can give it any name you like, but you must define the name
of the start file in the content elements src attribute in the
config.xml file. For example:
<content src=my-app.html/>
JavaScript
If your application requires any interactive elements, you can
program them using JavaScript code. You can include this
code directly in your index.html file within a <script>
element, or you can load it from an external JavaScript file.
The New Project wizard provided in the IDE creates a default
external script file called main.js for you to add to your
JavaScript code.
In order to load your external JavaScript code, you must
include your script in the header section of the index.html
file using the following code:
<script src=js/main.js></script>
60
Style sheet
Generally, your index.html file should contain only the
basic content and structure of your application, with any style
and presentation information contained within style sheets.
The New Project wizard provided in the IDE creates a default
style sheet called style.css, which you can use to apply
styles and presentation information to the elements used in
your application.
To load a style sheet, include the following link in the header
section of the index.html file:
<link
rel=stylesheet
href=css/style.css
/>
You can preview the look and feel of any style elements using
the CSS Preview tool, as described in Chapter 3.
Application icon
The icon.png file is the applications default icon file and
should contain a logo or some other graphical representation
of the application.
The use of this icon file depends on the Tizen device youre
developing for, but it generally appears in the application
menu screen.
Author signature
An author can digitally sign any application to ensure its
integrity. This signature file, which cryptographically covers
all nonsignature files within the application package, is the
author signature.
61
Distributor signature
A distributor can also sign an application to ensure its integrity. This signature file, which cryptographically covers all
nonsignature files and the author signature, if it exists, is the
distributor signature.
This file isnt mandatory in the package. The package can contain more than one distributor signature, so the naming convention is signature1.xml, signature2.xml, and so on.
Check out the SDK Help for more details about creating a distributor signature.
You can find additional information about author and distributor signatures in the XML Digital Signatures for Widgets
specification at www.w3.org/TR/widgets-digsig.
Third-party source
code or libraries
Sometimes you may want or need to use external libraries to
implement UI controls or functionality that isnt a standard
part of the Tizen platform. Using third-party libraries is a
really simple way to reuse existing technology and implement
advanced features in your application.
After you add the libraries to the project and load them in the
start file, you can use them in your application code.
62
63
<script src=js/wijmo/jquery.wijmo.wijprogressbar.min.js
type=text/javascript></script>
<script src=js/wijmo/jquery.wijmo.wijexpander.min.js
type=text/javascript></script>
<script src=js/main.js></script>
Make sure that you load your JavaScript files in the order
dictated by any dependencies. For example, in this code, the
main.js file is loaded last because its dependent on features
provided in the wijmo libraries.
Example 1: A 5-minute
application
A simple Tizen web application is a package that contains
only a start file and a configuration file. In this example, we
show you how to quickly create a simple web application to
run on your mobile device.
The most simple web application you can create is a hostedweb application. Basically, its an application that launches a
mobile web-page into your web-runtime.
64
65
<tizen:application id=NylyS9tSdz.My-App
package=NylyS9tSdz required_version=1.0/>
</widget>
When you save your changes, the IDE will verify that the
config.xml file is valid. If any errors occur, the IDE displays
a warning dialog box.
66
Example 2: Something a
bit more complicated
In this example, we introduce the use of JavaScript, CSS, and
Tizen APIs in a web application. Rather than showing you a
step-by-step guide to creating this more complicated app, we
look at the default Systeminfo sample application provided in
the SDK.
First, you need to build and run the Systeminfo app from the
Tizen SDK. You can find detailed instructions in the Chapter 3.
67
68
Looking at index.html
At the beginning of the index.html file is the head section of
the document. This section contains elements for defining the
character set and an application description. This section is
also where any JavaScript files and style sheets are loaded.
In this index.html, we load a single style sheet and JavaScript
files for jQuery, the Web UI Framework, and our app:
<head>
<meta charset=utf-8/>
<meta name=description content=Systeminfo API Tutorial/>
<title>Systeminfo</title>
<script src=tizen-web-ui-fw/latest/js/jquery.js></script>
<script src=./js/config.js></script>
69
<script src=tizen-web-ui-fw/latest/js/tizen-webui-fw-libs.
js></script>
<script
src=tizen-web-ui-fw/latest/js/tizen-web-ui-fw.
js data-framework-viewportscale=false></script>
<script type=text/javascript src=./js/main.js></script>
<link rel=stylesheet type=text/css href=./css/style.
css/>
</head>
70
You can also bind any other actions to events during initialisation in the same way. In this sample application, all the click
events for the items in the list elements are implemented in
this way:
$(#display-info).bind(vclick,
getSystemProperty(DISPLAY,
return false;
});
function()
{
onDisplaySuccess);
71
You can modify style and layout attributes and preview them
immediately using the CSS Preview feature provided by the
IDE, as shown in Chapter 3.
Multiple style sheets can be used in your application to style
your elements, but due to the way that cascading style sheets
are merged, you must be careful about the order they are
linked to in the index.html document head.
72
Chapter 5
74
The quickest way for you to test and debug your applications
without having to package and install them on the Emulator
or a device is to use the Simulator.
The Simulator is based on the Ripple UI framework and runs
in the Google Chrome browser, so you must have Chrome
installed on your development machine. The Simulator uses
the Chrome/WebKit backend to render your applications
layout, and you can debug your app using all the standard
Chrome development features, including the Web Inspector.
In the Simulator, the Tizen device APIs are implemented using
JavaScript, so you may see differences between running your
app in the Simulator and running on the Emulator or a real
device.
In the Simulator shipped with the Tizen 2.1 release, the implementation of some of the APIs may be incomplete, check the
Tizen 2.1 Release Notes for more information.
75
76
77
78
79
80
81
82
83
You must set your device date and time to the current date,
or youll be unable to deploy any web applications to it.
84
85
After you open the Web Inspector, youre ready to debug your
JavaScript as described in the Debugging JavaScript section,
later in this chapter.
86
Debugging JavaScript
Note: This information is relevant for whichever debugging
environment youre using.
To debug your JavaScript, choose the Sources option from
the menu to view the JavaScript files in the Remote Inspector
window, as shown in Figure 5-14. You can select the required
JavaScript file to debug by clicking the arrow next to the
filename.
87
You can also debug your JavaScript by adding debug statements into your code using the console.log() function.
Any log messages will be displayed in the IDEs console panel
at the bottom of the Web Perspective.
88
Table 5-1
SDB Commands
Command
Description
sdb connect
<host>[:<port>]
sdb disconnect
<host>[:<port>]
sdb shell
sdb help
sdb version
sdb start-server
sdb kill-server
sdb get-state
sdb get-serialno
Print <serial-number>
sdb status-window
In the Emulator, you can also open an SDB shell from the
Emulator configuration menu (refer to Figure 5-4).
89
90
Table 5-2
SDB Options
Option
Description
-d
-e
-s <serial number>
Chapter 6
s any mobile developer knows, the write-once, run-anywhere promise of HTML5 is still a long way from being
realized. Web developers face a lot of challenges, including
designing CSS style sheets to cope with different screen sizes,
fine-tuning JavaScript code to handle subtle differences in
device APIs, and even deciding which app store to sell their
wares in. But those same developers also know a good opportunity when they see one and wont let a few problems get in
their way.
In this chapter, we examine different aspects of the web app
landscape, including platforms, JavaScript frameworks, web
API standards, and app stores. We focus on some of the most
common web porting problems and provide some solutions.
If youve built a web page or developed a web app for another
platform, this chapter acts as your guide to porting your web
app to Tizen. If you want to make your Tizen web apps more
portable, were here to help with that, too.
92
93
94
Taking the time to explore existing technologies and choosing the right tool for your job will definitely help shorten your
development time.
Standards
Another good thing about the web technology is that its
open and standards driven. The World Wide Web Consortium
(W3C) is the main body that drives these standards for
example, the device APIs on mobile. But other organisations,
such as the GSM Association (GSMA), publish requirements
and APIs for web apps.
The GSMA OneAPI is designed to allow developers to create
platform independent apps containing features such as operator billing that work for all network operators. This builds
on the work of previous organisations such as the Wholesale
Application Community (WAC), which is now integrated into
GSMA.
95
Distribution
The final part of web app landscape is the distribution channel, including the app stores in which you sell your web apps.
The distribution channel is the most important part of the
ecosystem because its how youll start making money from
your app. However, supporting multiple stores on multiple
platforms can also become complicated.
Some stores, such as the Chrome Web Store and the Mozilla
Marketplace, accept stand-alone web apps, but use different
packaging formats. The Chrome store requires web apps to
be packaged as .crx files, while Mozilla Marketplace requires
.xpi packages. Other stores, including the Apple iOS App
Store and Google Play, accept only native applications, so
youll have to wrap your web code in a native app in order to
gain entry to these stores.
Note: The Tizen store is in the preparation stage at the time of
writing.
96
(installable bundle)
myscript.js*
.crx
.xpi
options.xul*
main.html
Format
install.rdf*
icon.png
/img folder*
manifest.webapp
manifest.json
Content
Mozilla
Marketplace
Chrome Store
.zip
/img folder
splashscreen.png
.ipk
sources.json
/css folder
/js folder
index.html
icon.png
appinfo.json
webOS
/img folder*
/css folder
/js folder
default.html
package.appxmanifest
Windows Phone
Stores
Table 6-1
.wgt
/img folder*
/css folder*
/js folder*
index.html
icon.png*
config.xml
Tizen
97
98
99
Our updated CSS code for a fluid layout of the Aura app looks
like this:
.stage {
width: 100%;
position: relative;
overflow: hidden;
-webkit-transform: translateZ(0);
}
100
When using HTML5 in strict mode, the parent element of percentage element must also have its size in percent. Otherwise,
an error occurs.
You can use other methods, such as the viewport and media
queries, to optimise your mobile apps layout. You can set the
layout viewport to the device width with this HTML code:
<meta
name=viewport
content=width=device-width>
This code ensures that your app is optimized to take advantage of the full device width of a mobile device.
The media query in CSS3 allows you to detect the screen size
of device and adjust the style accordingly:
101
102
103
1. Create a new Tizen web app using one of the templates in the SDK
104
105
106
Part III
Tizen in Detail
In this part . . .
Chapter 7
Building Your UI
In This Chapter
Introducing jQuery Mobile
Using basic controls
Taking advantage of UI building tools
Creating advanced UIs
110
Page structure
To use jQuery Mobile, you just need to create an HTML5 page.
The page must start with an HTML5 doctype to take advantage of jQuery Mobile library. In the head tag, you can specify
a meta data tag viewport for the initial scale and screen size
of your mobile web app. Under the body tag, you can create a
single or multiple jQuery Mobile page by using data-role=
page inside the div. This creates a view that uses up to
the full screen of your mobile device if the status bar area is
hidden.
Inside the page div, you can also add the header, content,
and footer sections, as shown in Figure 7-1.
111
Events
jQuery Mobile also provides various types of custom events
to create useful hooks between the UI and your JavaScript
code. These events cohabit nicely with the native events of
the platform. For example, touch-related events include tap,
taphold, swipe, swipeleft, swiperight, and pinch.
To assign the event to your UI, you just use the following
method:
$(document).on(swipeleft, function(event, data){
//your implementation of swipeleft event
});
112
Table 7-1
Name
From
Description
Checkbox
JQM
Radio Button
JQM
Radio button
Button
JQM
Basic buttons
JQM
Segment Control
JQM
Slider
JQM
Progressbar
jQueryUI
Lists
JQM
List of items
List Divider
JQM
Virtual List
New
Extendable List
New
Swipe List
New
Popup
JQM
Pop-up window
113
Name
From
Description
Context Popup
JQM
JQM
Notification
New
Gallery
New
Image collection
Tabbar
New
DateTime Picker
New
Handler
New
Multimedia View
New
VirtualGrid
New
FastScroll
New
Split View
New
Gallery 3D
New
Note: These are the UI elements available at the time of writing. For more details
consult the UI Framework Reference in the SDK help.
114
115
116
Implementing events in
the UI builder
The UI Builder can also generate code to handle the events
supported by Tizens predefined UI widgets. For example, a
list item supports the SwipeLeft event, and you can generate
the skeleton JavaScript code to handle this event from within
UI Builder.
Highlight the list item in the UI Builder and click the Event
Handler tab in the Property Panel. You see a drop-down
menu, which lists all the events the List Item widget supports. Choose SwipeLeft to assign this event to the List
Item and click the triangle that appears below the menu, as
shown in Figure 7-6.
117
118
f-page is for the pages between the cover and back that
you need to flip.
f-cover is the cover page.
f-cover-back is the back of the cover.
For the page layout, the box class presents the content of the
page for example, the images and articles. These boxes each
need an additional height and width class to give the
element percentage-based dimensions.
119
class=f-page>
<div class=f-title>
<!-- ... -->
</div>
<div class=box w-50 h-100>
<div class=img-cont img-1></div>
<h3>Headline <span>Published May 7, 2012</span></h3>
<p>Some text</p>
</div>
<div class=box w-50 h-100>
<!-- ... -->
</div>
</div>
<div
class=f-page>
<!-- ... -->
</div>
<!-- ... -->
<div class=f-page f-cover-back>
<!-- ... -->
</div>
</div>
Figures 7-7 and 7-8 show the final code running on the Tizen
development device. The cover page contains the image and
flip text.
120
Chapter 8
Taking Advantage of
Location-Based Services
In This Chapter
Displaying a map
Converting between addresses and co-ordinates
Dropping a pin on a map
122
deCarta JavaScript APIs:
http://developer.decarta.com/Apis/
JavaScript
Displaying a Map
While you can use any of the JavaScript mapping APIs for displaying a map in your Tizen web app, we use the Google Maps
API for this example. Heres how you display a map based on
your current location:
123
navigator.geolocation.getCurrentPosition(
function(position) {
console.log(Latitude: +
position.coords.latitude +
Longitude: +
position.coords.longitude);
},
function(error) {
console.err(Failed to get current
position);
}
);
The final step is to assign the div element that contains the map. For example, if you want to display the
map in the page content, add the following to your
HTML file:
<div data-role=content id=map>
124
Figure 8-1: Displaying a map in the Tizen Emulator using the Google map
APIs.
125
Finding an Address
Displaying a map given a longitude and latitude is relatively
simple, but sometimes all you have is a human-readable address.
Converting this address into a longitude and latitude is known
as geocoding, while the process of translating coordinates to a
human-readable form is referred to as reverse geocoding.
In this section, we show you how to make use of the Google
geocoding service, but there are many other third party geo
coding APIs available.
126
An array of GeocoderAddressComponents
A string containing the human-readable address of this
location
A GeocoderGeometry object
An array of strings denoting the type of the returned
geocoded element.
The GeocoderResult result objects are returned as an
array because one geocoder request may return multiple
GeocoderResult objects. In our example, we just read the
first object from the array.
The GeocoderStatus object tells you the status of your geocoder request. The predefined values are ERROR, INVALID_
REQUEST, OK, OVER_QUERY_LIMIT, REQUEST_ DENIED,
UNKNOWN_ERROR, or ZERO_REQUEST.
Google also provides the Geocoding web service. You can use
an HTTP request to access the geocoder directly. This service
is designed for geocoding static addresses for placement of
app content on a map. Its not designed to respond in real
time to user input.
For more information about Google Maps Geocoder API, go to
https://developers.google.com/maps/documentation/
javascript/3.exp/reference#Geocoder
127
128
Chapter 9
130
Table 9-1
Multimedia Features
Feature
Recommended API
Capturing audio
Capturing images
Capturing video
Discovering Content
The Tizen Content API provides functionality for searching
for content stored either locally on your device or an external
memory card.
You dont want this sensitive information falling into the
wrong hands, and the Tizen platform restricts app access to
131
the content by using permissions. There are different permission levels, which your app will set depending on whether you
want to just find an item or modify an items attributes. These
permissions are set in the config.xml file. (See the Getting
Permission section, later in this chapter, for more details).
If the appropriate permissions are set, a ContentManager
object is created and stored in the content property of your
apps tizen object. You then use this ContentManager to
locate content. If the correct permissions are set, you can also
update any items editable attributes. You can find details of
the available methods and the editable attributes in the SDK
Help documentation.
Content
A content item is an object that contains the attributes of a
single piece of content, rather than the content itself. You use
the Content interface to access an items attributes.
In the Tizen platform, the Content interface is extended by
the AudioContent, ImageContent, and VideoContent
interfaces with attributes specific to the content type. Table
9-2 lists these attributes.
Table 9-2
Content Type
Attributes
Content
AudioContent
ImageContent
VideoContent
132
Getting permission
Because content is private data, the Tizen platform restricts
access to this data using different permission levels.
Permissions are set in the config.xml file. (See Chapter 4 for
more on permissions.)
Here are the permissions related to content:
Adding http://tizen.org/privilege/content.
read to your permissions gives you access to the
methods in the API for searching for content, and
watching for added, updated or removed content.
Adding http://tizen.org/privilege/content.
write to your permissions gives you access to the
methods in the API for updating the attributes of items.
133
You can combine these filters using a composite filter with the
INTERSECTION filter type, which is equivalent to a logical AND:
var searchFilter = new tizen.CompositeFilter(INTERSECTION,
[audioFilter, genreFilter]);
Then you can use the find() method to search for the first
ten items that match your search requirements:
tizen.content.find(audioFoundCb, errCb, null, searchFilter,
sortMode, 10);
134
To use this feature, you need to edit the application permissions in the config.xml file to include the http://tizen.
org/privilege/application.launch permission.
135
Launching an application
The application object provides a launchAppControl()
method, which your app calls to launch the service defined in
the Application Control object.
When the system receives the launch request, it processes
the parameters of the Application Control object to select
the application that provides the appropriate service. If the
system finds a suitable application, it launches it, passing the
information contained in the Application Control object.
The launchAppControl() method is asynchronous, so
you can define optional success and error callbacks to get
status information. The success callback is triggered when the
application is launched successfully; to get the status of the
requested operation and any data passed back to your app,
you need to define a reply callback. This is how you get the
location of the image chosen by the user in the gallery app,
for example.
136
You dont need to set a URI, category or any data for this
camera Application Control request.
After you create the Application Control object, your
app requests that this application is launched using the
launchAppControl() method:
tizen.application.launchAppControl(appControl, null, successCb,
errCb, appControlReplyCb);
137
138
For audio: AAC, AMR-NB, AMR-WB, MP3, WMA, and
VORBIS.
For video: H.263, H.264, MPEG-1, MPEG-4, WMV3, VC1,
and THEORA.
139
You can also create your own custom controls for an audio
player. In this case, you use the following code to add an
audio element to your app:
<audio id=audioPlayer src=audio/test.mp3></audio>
If youre not using the default controls, you need to add the
buttons and other controls for your custom playback UI.
When the user clicks the Play button, the audio file is loaded
into the audio element and starts playing.
140
141
Multimedia Streaming
In a Tizen web application, its possible to access multimedia streams from local devices, such as the video camera
and microphone. This functionality is based on the W3C
getUserMedia specification.
The getUserMedia specification is a work in progress and
not fully standardized. Many browser projects have implemented their own versions of the specification. The Tizen
platform uses WebKit and provides access to local multimedia
streams through the webkitGetUserMedia API.
The implementation of getUserMedia is very much bleedingedge technology. Any APIs or functionality discussed in this
section are liable to change in future versions of the specifica tion and may work differently in later versions of Tizen.
webkitGetUserMedia
The webkitGetUserMedia API is the WebKit implementation
of the getUserMedia specification. Its used to create a local
media stream from either the devices camera, microphone,
or both.
The webkitGetUserMedia API is an access method, prompting the user for permission to use the audio/video input. If the
user gives permission, the APIs success callback is triggered
with a local media stream object. If the user refuses permission, the optional error callback is triggered.
The local media stream object generated by the webkit
GetUserMedia API can be displayed in a video element,
which is what we focus on in this section.
142
143
144
Chapter 10
146
Introducing NFC
Near Field Communication (NFC) isnt a new technology.
You can trace its roots back to 2004 when Nokia, Philips,
and Sony founded the NFC Forum. The technology is based
on the Radio-Frequency Identification (RFID) standards. The
difference is that RFID is a passive information tag and cant
process the information sent from other devices, while NFC
enabled devices can do more, such as card simulation and
peer-to-peer communication. Thats why NFC needs the
processing power of a smart device.
NFC provides a wireless communication method with some
unique characteristics:
Close proximity
Low speed
No setup required
No battery required for a passive tag
At the moment, it seems that NFC is everywhere. Google is
encouraging adoption of Google Wallet, which allows
consumers to make small transactions via NFC-enabled
devices, such as the Nexus S and Samsung Galaxy SIII. The S
III was also the device used by Visa and Samsung to provide
mobile payment services during the London 2012 Olympics.
But NFC has uses far beyond mobile payments. For example,
the Android Beam feature, introduced in the Ice Cream
Sandwich (4.0) release, allows users to exchange small
amount of information, such as web URLs, between phones
just by touching them together. Several manufacturers have
introduced NFC-enabled speaker systems, which allow you to
start streaming audio from a device with a single touch.
147
These examples are just the tip of the iceberg, NFC has many
other uses. According to the NFC Forum specifications, NFC
devices can be operated in three different modes, shown in
Figure 10-1:
Read/write mode: NFC devices are able to read or write
small amounts of information to NFC-compatible tags.
Possible uses include getting information from an NFC
tag on a smart poster or creating your own personal NFC
sticker.
Peer-to-peer mode: Two NFC devices exchange data.
This data could include Bluetooth or Wi-Fi link setup
parameters, virtual business cards, or digital photos.
Card Emulation mode: The NFC devices appear to an
external reader much the same as a traditional contactless
card. This enables contactless payment and ticketing.
148
149
Setting up NFC
To use NFC, you have to create the NFCAdapter object. It is
fairly simple to create the adapter by just calling
var
nfcAdapter = tizen.nfc.getDefaultAdapter();
150
Reading a tag
When a tag is detected by the device, it calls the tag detected
callback function. At this point, you can carry out an operation
on the detected tag. For example, to read the tag, you use the
readNDEF method.
151
function(){
//error callback of readNDEF()
}
);
}
}
};
152
Writing a tag
The implementation of writing a tag is very similar to the code
required to read a tag. After the NFCTagDetectCallback is
triggered, you can use the writeNDEF() method of the tag
object to write information to the tag:
var onTagDetect = {
onattach: function(tag){
if(tag.isSupportedNDEF){
tag.writeNDEF(
ndefMessage,
function(){
//handle success case
},
function(){
//handle failure case
}
);
}
}
};
After you create the NDEF message, you can pass it to the
writeNDEF method.
153
154
155
function(data){
156
onError);
157
In some devices, if there is hardware (for example, a gyroscope) to exclude the effect of gravity from the acceleration
data, you can use the acceleration property directly:
function motionHandler(data){
var acceleration = data.acceleration;
}
Table 10-1
Accelerating Up Accelerating
Forward
acceleration
{0, 0, 0}
{0, 0, 5}
{0, 2, 0}
acceleration
including Gravity
{0, 0, 9.81}
{0, 0, 15}
{0, 2, 9.81}
Accelerating
Left
Accelerating Up
& to the Right
acceleration
{3, 0, 0}
{5, 0, 9}
acceleration
including Gravity
{3, 0, 9.81}
{5, 0, 11}
158
Chapter 11
Messaging
In This Chapter
Creating and sending messages
Searching for messages
Building a User Interface for message searching
160
Message service
In order to use messaging functionality in your application,
you first have to retrieve the message service for the required
service type. A message service is the interface that gives you
access to the message creation, sending, and reading capabilities of the platform. Email, SMS, and MMS messaging service
types share a common interface.
For example, to access email functionality, you retrieve the
email service with the following code:
tizen.messaging.getMessageServices(messaging.email,
msgServiceCb, errCb);
This service request API is asynchronous, so any available email messaging services are returned in an array of
MessageService objects by the success callback.
Once the required message service is retrieved, you can send
messages and load message content and attachments. For
email, you can synchronise content with an external server.
Message structure
A message consists of a Message object, which contains the
attributes of the message, a MessageBody object, and optionally any MessageAttachment objects.
161
Message
The Message interface describes the properties of a message,
such as the message recipients, subject, sender, type, and so
on. (The message attributes and the service types they apply
to are described in the SDK Help documentation.)
The Message interface constructor is used to create a
Message object. For example, heres how to create an SMS
object:
msg = new tizen.Message(messaging.sms,
{ plainBody: Hi Sarah, how are you?,
to: [1234]
});
Once created, this message can either be sent using the SMS
message service or stored as a draft in the filesystem using
the MessageStorage interface.
MessageBody
The MessageBody object describes the body of a message
with the following attributes: an id, the loaded status, a plain
text part, an html part, and inline attachments for email
messages.
When reading a message, if the loaded status attribute of the
message body is set to false, it indicates that the body hasnt
been downloaded from the server. If this is the case, the body
must be downloaded using the MessageService objects
loadMessageBody() method.
MessageAttachment
The MessageAttachment object describes the content and
properties of a message attachment with the following
attributes: an attachment id, a message id, the MIME type, and
the file path of the downloaded content.
If a message contains one or more attachments, the messages
hasAttachment attribute will be set to true. Because
attachments arent always automatically downloaded from
the server, you may need to download them using the load
MessageAttachment() method.
162
Message storage
Each message service object in the system has its own message storage object. This provides an interface to query,
update, and delete messages and subscribe to any changes in
the message storage object. It also provides functionality to
find specific messages, conversations, or message folders.
Getting Permission
Because messages are private data, the Tizen platform
restricts access to this data using different permission levels.
Permissions are set in the config.xml file and are explained
in detail in Chapter 4. Here are the ones related to messaging
content:
Adding http://tizen.org/privilege/messaging.
read to your permissions lets you find and watch
messages, conversations and folders from the message
storage.
Adding http://tizen.org/privilege/messaging.
write to your permissions lets you add, remove and
update messages in the message storage, synchronize
content and folders with external mail servers, and send
messages.
163
164
165
Initialisation
This example uses the Tizen UI Framework, which is based on
jQuery Mobile, and applications are developed using a page
structure. Any initialisation code that needs to be run when
the page is loaded should be executed when the pageinit
event is fired.
In this example, the initialisation code includes functionality to retrieve the SMS message service, and event bindings
for the page and the search box. This is implemented in the
main.js file, as shown in Listing 11-2.
166
167
Listing 11-4 shows the code to create and display the message
list.
The first action is to clear any previous list data using the
remove() method, and then you can append the new list
data. To differentiate between the incoming and outgoing
messages, you can check the from message attribute, which
will be empty for outgoing messages.
To create each list item, you need to append a list item element with the relevant bubble class type to the msgList list
element. In this example, the body text and timestamp of the
message is added to the list item. After the list has been populated, you tell the framework to update the list using the List
Views refresh() method.
168
169
170
prevString
function
findString(str)
{
var typeFilter =
new
tizen.AttributeFilter(type,
EXACTLY, messaging.sms);
var strFilter = new tizen.AttributeFilter(body,
CONTAINS, str);
var searchFilter = new tizen.CompositeFilter(INTERSECTION,
[typeFilter, strFilter]);
// If search string isnt empty use composite filter,
// otherwise use type filter
if(str != ) {
msgStore.findMessages(searchFilter, msgFoundCb, errCb);
} else {
msgStore.findMessages(typeFilter, msgFoundCb, errCb);
}
}
function updateList() {
var input = $(#searchBox).val();
if(input != prevString)
findString(input);
prevString = input;
}
}
Chapter 12
172
Address books
It doesnt matter how many address books you have or where
they are stored (for example, on your device or SIM card)
you use the same ContactManager interface to retrieve
them.
For example, to retrieve the unified address book, you use the
following in your code:
var addressBook = tizen.contact.getUnifiedAddressBook();
173
Contacts
A contact is a set of information that contains all the data you
hold about a specific person or organisation, including name,
phone numbers, and email addresses.
To retrieve a specific contact from the address book, you can
use the Address Books get() method. This method returns a
contact object, which contains all the information related to
the contact.
The following contact properties are supported: id, person
Id, addressBookId, lastUpdated, isFavorite, name,
addresses, photoURI, phoneNumbers, emails, birthday,
anniversaries, organizations, notes, urls, ring
toneURI, and groupIds.
The Tizen Contacts API supports the standard vCard version
3.0 and includes functions for importing contacts from and
exporting to vCard format. Take a look at the Exporting a
contact section, later in this chapter, for a code sample.
174
Getting Permission
Because contacts and address books contain private and
sensitive data, the Tizen platform restricts access to this data
using different permission levels. Permissions are set in the
config.xml file and are explained in detail in Chapter 4. Here
are the ones related to contacts:
Adding http://tizen.org/privilege/contact.read
to your permissions gives you access to the methods in the
API for retrieving address books, getting/finding/watching
persons or contacts, and retrieving contact groups.
Adding http://tizen.org/privilege/contact.
write to your permissions gives you access to the
methods in the API for adding, modifying and deleting
persons, contacts or groups, and linking or unlinking a
contact to a person.
Adding a contact
In this example, we show you how to add a single contact to
an address book.
Before you can perform any operations on an address book,
you must first retrieve it from the system. Heres how to get
all the available address books:
tizen.contact.getAddressBooks(addContactCB, errorCB);
175
Notice that we pass newly constructed objects representing contact name, email address, and phone number to
the tizen.Contact constructor. You can also specify the
ContactOrganization, ContactAnniversary, and other
properties. See the Tizen SDK Help for a full list of properties
available.
Alternatively, you can also create a Contact object by specifying the properties as a formatted vCard string:
var
contact
new
tizen.Contact(BEGIN:VCARD\n
+ VERSION:3.0\n
+ N:Bishop;Walter\n
+ FN:Walter Bishop\n
+ EMAIL:walter@email.com\n
+ TEL;HOME:5552773\n
+ END:VCARD);
After you create your contact, you can then add it to the
address book:
addressBook.add(contact);
176
Retrieving a contact
In this example, we show you how to get a specific contact
from the address book. You can get a contact in two ways:
using the contact reference or searching with filters.
If you know the ContactRef of the contact youre looking for,
you can directly retrieve the contact from the address book
using the get() method.
The ContactRef is a unique reference to the contact, as it
contains both the id of the address book the contact is contained within and the id of the contact.
You can create this reference using the ContactRef constructor with the AddressBookId and ContactId of the
contact youre trying to retrieve. The address books id
and the contacts id are both attributes of the Contact
object, which are set after the contact has been added to
the AddressBook.
var contactRef; // Value initialised with known data
var addressBook = tizen.contact.getAddressBook(contactRef.
addressBookId);
var contact
=
addressBook.get(contactRef.contactId);
console.log(Name: + contact.name.displayName
+ Email: + contact.emails[0].email
+ Tel: + contact.phoneNumbers[0].number);
177
You can perform more complex queries by combining multiple filters together. (See the SDK Help documentation for
more information.)
This attribute filter gets used within the find() method:
addressBook.find(successCB, errorCB, attrFilter);
Deleting contacts
The AddressBook object contains methods that allow you
to update or delete multiple contacts in a batch operation.
These operations are asynchronous, so success or failure of
the operation is indicated by the invocation of the appropriate callback method.
In this example, we show you how to delete all the contacts in
a specific address book.
178
errorCB);
In this example, because you dont pass in a filter parameter to the find() method, the full list of contact items is
returned in the success callback.
The success callback is invoked with the array of Contact
objects. To delete all the contacts in the address book, you
use the removeBatch() method. This method takes an array
of ContactIds as an input, so you need to create an array
of ContactIds from the array of Contacts returned in the
find() methods success callback.
function successCB(contacts) {
if (contacts.length > 0) {
var contactIds = [];
for(var i=0; i<contacts.length; i++) {
contactIds[i]=contacts[i].id;
}
addressBook.removeBatch(contactIds,
deleteSuccessCB, errorCB);
}
}
When the removeBatch() operation is completed successfully, the optional success callback is invoked. If any errors
occur during the operation the optional error callback is
invoked.
Exporting a contact
In this example, we show you how to export a contact in the
vCard format. The Contact API supports vCard version 3.0.
The Contact object provides a convertToString()
method to convert all the parameters contained within the
contact object into a string that complies with the vCard
format.
179
You can get a contact from the address book using either
of the examples shown in the Retrieving a contact section,
earlier in this chapter. Then you just call the convert
ToString() method:
var contactRef; // Value initialised with known data
var
var
addressBook = tizen.contact.getAddressBook(contactRef.
addressBookId);
contact
=
addressBook.get(contactRef.contactId);
180
Chapter 13
Getting Organized
with Calendars
In This Chapter
Using the Calendar API
Creating and retrieving tasks
Adding reminders to a task
182
CalendarManager
This calendar object implements the CalendarManager
interface, which provides methods to access the calendars
stored in the system. The same interface is used to access
both event calendars and task calendars.
So, for example, to retrieve the default event calendar, you
use the following code:
var calendar = tizen.calendar.getDefaultCalendar(EVENT);
Calendar
The Calendar interface provides the methods to get, find,
add, update, delete, and watch items within the calendar.
Access to some of these methods is restricted depending on
which permission youve set for your application.
You can perform single add, update, and delete operations
on the calendar synchronously, or you can perform multiple
add, update, and delete operations using asynchronous batch
methods. See the A New Batch sidebar in this chapter for
more details about batch functions.
CalendarItem
CalendarItem is an interface from which both the
CalendarEvent and CalendarTask interfaces are derived.
The CalendarItem interface defines the functions and attributes that are common to both events and tasks.
183
Supported properties
The following properties are
supported for all calendar item
types: i d , c a l e n d a r I d ,
lastModificationDate,
description, summary,
isAllDay, startDate,
duration, location,
geolocation, organizer,
visibility, status,
priority, alarms,
categories, and attendees.
Getting Permission
In order to use any of the Calendar API features, the relevant
privilege must be set in the applications config.xml file.
(See Chapter 4 for more information about the config.xml
file.)
Adding http://tizen.org/privilege/calendar.
read to your permissions gives you access to the methods in the API for retrieving calendars, getting/finding/
watching items, converting items to strings, cloning
items, and expanding recurrences.
Adding http://tizen.org/privilege/calendar.
write to your permissions gives you access to the methods in the API for adding, modifying and deleting events
or tasks.
184
Creating a Task
In this example, we add a single task to the default task calendar.
Before you can perform any operations on the task calendar,
you first need to retrieve it from the system:
var calendar = tizen.calendar.getDefaultCalendar(TASK);
After you create your task, you can then add it to the calendar:
calendar.add(task);
185
A new batch
In Chapter 12, we explain
that operations that involve
making changes to the address
book can be combined into
batch operations to improve
performance. You can also use
the addBatch, updateBatch,
and removeBatch functions to
combine multiple changes to the
calendar, such as adding, updating,
Retrieving Tasks
You can get a task from the calendar in two ways:
By using the task id
By searching for specific task parameters in the calendar
The task id is the identifier that was assigned to the task when
it was added to the calendar.
If you know the task id, you can retrieve the task from the calendar using the get() method:
var taskId;
taskId = ... // gets a valid Task ID from somewhere
var calendar = tizen.calendar.getDefaultCalendar(TASK);
// Retrieve task
var task = calendar.get(taskId);
If you dont know the task id or you want to search for multiple tasks, you can use a filter with the find() method.
The tizen object provides several filter options that you can
use when searching for a task.
186
187
Setting an Alarm
In this example, we show you how to retrieve a task item from
the calendar, add a reminder alarm to it, and then update the
calendar.
To get a specific task item from the calendar, you can use the
get() method:
var task = calendar.get(taskId);
After you create your alarm, you can then add it to the task
and update the calendar:
task.alarms = [alarm];
calendar.update(task, false);
If you want to check whether the task has been updated, you
can retrieve the task from the calendar and check the last
ModificationDate attribute or the alarms attribute.
188
Part IV
In this part . . .
Chapter 14
192
Douglas Crockfords
JavaScript Lectures
Douglas Crockford is involved in the ongoing development of
JavaScript, was responsible for the JSON (JavaScript Object
Notation) data format and for many popular JavaScript tools.
Hes considered the JavaScript expert; when he speaks, its
worth hearing what he has to say. In 2010/11 he presented
a series of lectures on the history of JavaScript, its features
and programming style. You can find these lectures here:
http://yuiblog.com/crockford/
JavaScript Patterns
Object oriented languages such as JavaScript, lend themselves
to the design and use of design patterns reusable solutions that
can be applied to common coding problems. While JavaScript is
not strongly typed like C++ and Objective-C, it does provide many
object-oriented features such as constructors and inheritance.
This book, written by Stoyan Stefanov and published by
OReilly (ISBN: 978-0-596-80675-0) provides code templates
and explains the best approach to creating reusable code in
JavaScript. Its another essential volume on our bookshelves.
193
JavaScript Libraries
There are thousands of JavaScript libraries out there which you
can use to add features to your app and to save you time. Chapter
4 explains how to use external JavaScript libraries in your code.
jQuery (http://jquery.com/) is the most popular and
powerful JavaScript framework and is actually included with
Tizen. It allows you to write code thats portable. Weve found
it particularly useful for AJAX (www.adaptivepath.com/
ideas/ajax-new-approach-web-applications) features
and grabbing data from external websites. It also makes it
easy to traverse DOM (Document Object Model) trees.
We mention Modernizr (http://modernizr.com/) in
Chapter 6. Its handy for detecting the features of a browser
and writing portable code which works well across browsers.
Also worth checking out is Wijmo (http://wijmo.com/)
a set of UI widgets bad on jQuery.
These are just a few libraries we found especially useful; youre
sure to find many more to assist your development efforts.
194
www.html5rocks.com has good tutorials on a whole
range of web development topics.
www.htmlgoodies.com/primers/html/ is a good
place to start when checking out the available resources.
http://html5doctor.com/ is a good place to get
your questions answered.
Youll find that all these sites link to lots more information
sources, but thats why its fun to explore.
Smashing Magazine
A special mention to Smashing Magazine (and not just
because we like the name). Their website at www.smashing
magazine.com/ contains hundreds of articles on web design
and development.
Its particularly useful for those with a web design background.
Smashing Magazine also publish books, including Smashing
jQuery by Jake Rutter (Wiley, ISBN: 978-0-470-97723-1) which is
well worth checking out.
And . . . You
Of course the most important resource is you. The best way
to learn a new skill is by doing it. We hope this book encourages you to write a web page, start tweaking some JavaScript
examples, create a Tizen web app based on the examples and
start developing the next great killer app.
Chapter 15
196
197
Tizen Is Consistent
These device APIs use patterns that will be familiar to you
if youre used to libraries such as jQuery. If youre already
a web developer, it wont take you long to become a Tizen
expert.
198
Acknowledgments
The authors would like to thank:
Dr Yong-Suk Moon, Justin Hong, Ray HS Yun, Hokyung Kim,
and Philip Northam for their help in making this project
possible.
We would also like to thank our colleagues in HQ, SCRC, SPRC,
and SISO, especially Hyeyoung Jung, DaeHo Han, TaeHee Lee,
JunHo Lee, and Yuqiang Du.
Special thanks go to BK Wang, EunYoung Choi and all other
reviewers.
Finally, we would like to thank our colleagues for their support, encouragement, and a never-ending supply of biscuits.
More personally:
From Cheng: To Mom, Dad, Mary, Luke, and Tong with love.
From Jon: Love to Julia and Iliya, for keeping me crazy.