Está en la página 1de 220

Tizen

FOR

DUMmIES

By Jon Lansdell, Cheng Luo


and Michelle Somerville

A John Wiley and Sons, Ltd, Publication

01_9781118539538-ffirs.indd i

1/18/13 1:28 PM

Tizen For Dummies


Published by
John Wiley & Sons, Ltd
The Atrium
Southern Gate
Chichester
West Sussex
PO19 8SQ
England
For details on how to create a custom For Dummies book for your business or organisation, contact
CorporateDevelopment@wiley.com. For information about licensing the For Dummies brand for
products or services, contact BrandedRights&Licenses@Wiley.com.
Visit our Home Page on www.customdummies.com
Copyright 2013 by John Wiley & Sons Ltd, Chichester, West Sussex, England
All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval system or
transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning
or otherwise, except under the terms of the Copyright, Designs and Patents Act 1988 or under the
terms of a licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London,
W1T 4LP, UK, without the permission in writing of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Ltd, The Atrium,
Southern Gate, Chichester, West Sussex, PO19 8SQ, England, or emailed to permreq@wiley.com, or
faxed to (44) 1243 770620.
Trademarks: Wiley, the Wiley logo, For Dummies, the Dummies Man logo, A Reference for the Rest of
Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com and related trade dress
are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United
States and other countries, and may not be used without written permission. All other trademarks are
the property of their respective owners. Tizen is a registered trademark of The Linux Foundation.
John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER, THE AUTHOR, AND
ANYONE ELSE INVOLVED IN PREPARING THIS WORK MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS
WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION
WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED
OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH
THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL,
ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS
REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.
NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS
A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN
THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION
OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS
SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED
OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print
may not be available in electronic books.
ISBN: 978-1-118-53953-8
Printed and bound in Great Britain by Page Bros, Norwich
10 9 8 7 6 5 4 3 2 1

01_9781118539538-ffirs.indd ii

1/18/13 1:28 PM

Table of Contents
Introduction....................................................... 1
About This Book ........................................................................ 1
Conventions Used in This Book ............................................... 1
Foolish Assumptions ................................................................. 2
How This Book Is Organized .................................................... 2
Part I: Introducing Tizen ................................................. 2
Part II: Getting Practical .................................................. 3
Part III: Tizen in Detail ..................................................... 3
Part IV: The Part of Tens................................................. 3
Icons Used in This Book ............................................................ 3
Where to Go from Here ............................................................. 4

Part I: Introducing Tizen ..................................... 5


Chapter 1: Getting an Inside Look at Tizen . . . . . . . . . . . .7
Discovering Tizen ...................................................................... 7
Focusing on HTML5 ......................................................... 8
Tizens place in the mobile world.................................. 8
Figuring Out What Makes Tizen Different ............................. 10
Tizen is based on standards......................................... 10
Tizen is open .................................................................. 11
Tizen is innovative......................................................... 11
Tizen has industry support .......................................... 12
Comparing Tizen to Other Platforms .................................... 12
Getting Familiar with the Tizen Association ........................ 13
Getting Involved ....................................................................... 13
Submitting patches ........................................................ 14
Mailing list and IRC ........................................................ 14
Forums ............................................................................ 15
Bug tracker ..................................................................... 15

Chapter 2: Exploring the Tizen Architecture . . . . . . . . .17


Introducing Web Apps............................................................. 18
The web runtime ............................................................ 18
Installer ........................................................................... 19
Runtime core .................................................................. 20
Plugin core ...................................................................... 20
Using Tizen Web APIs .............................................................. 21

02_9781118539538-ftoc.indd iii

1/18/13 1:28 PM

iv

Tizen For Dummies


Exploring the Tizen Device APIs ............................................ 22
Tizen ................................................................................ 22
Alarm ............................................................................... 23
Application ..................................................................... 23
Bluetooth ........................................................................ 23
Calendar .......................................................................... 24
Call ................................................................................... 24
Contacts .......................................................................... 24
Download ........................................................................ 24
Filesystem ....................................................................... 24
Geocoder......................................................................... 24
Media Content ................................................................ 24
LBS (Location-Based Service) ...................................... 25
Messaging ....................................................................... 25
NFC .................................................................................. 25
Notification ..................................................................... 25
Power .............................................................................. 25
SystemInfo ...................................................................... 26
Time ................................................................................. 26

Part II: Getting Practical.................................. 27


Chapter 3: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . .29
Installing the IDE ...................................................................... 30
Creating Your First Tizen Web App ....................................... 31
Using a sample app........................................................ 33
Using your own template .............................................. 33
Importing an existing project ....................................... 35
Tizen web application ......................................... 35
Other web applications ...................................... 36
Writing the Code ...................................................................... 37
HTML Web Page Editor ................................................. 37
HTML Preview pane ...................................................... 38
CSS Preview pane........................................................... 39
Minifying CSS and JavaScript ................................................. 39
CSS ................................................................................... 39
JavaScript ....................................................................... 40
Building Your Project .............................................................. 40
Running Your Project .............................................................. 40
Help Is on the Way ................................................................... 41
Help documentation ...................................................... 41
Sample applications ...................................................... 42

02_9781118539538-ftoc.indd iv

1/18/13 1:28 PM

Table of Contents

Chapter 4: Piecing Together the


Application Jigsaw . . . . . . . . . . . . . . . . . . . . . . . . . . . .43
Examining the Pieces ............................................................... 44
The application package ............................................... 44
Localized content .......................................................... 44
The configuration file .................................................... 46
Breaking down the config file ............................ 46
config.xml the easy way: the
Configuration Editor........................................ 48
Start file ........................................................................... 55
JavaScript ....................................................................... 55
Style sheet ...................................................................... 56
Application icon ............................................................. 56
Author signature ............................................................ 56
Distributor signature ..................................................... 57
Third-party source code or libraries .......................... 57
Adding source code or libraries to a project... 58
Adding source code or libraries in
index.html ......................................................... 58
Putting the Pieces Together ................................................... 59
Example 1: A 5-minute application .............................. 59
Creating the application project ....................... 59
Editing the icon file ............................................. 60
Editing the configuration document ................. 60
Editing the start file ............................................. 61
Running the application ..................................... 61
Example 2: Something a bit more complicated ......... 62
Using the Tizen APIs ........................................... 64
Looking at index.html ......................................... 64
Figuring out what is in main.js ........................... 66
Defining style attributes in style.css ................. 68

Chapter 5: Testing and Debugging . . . . . . . . . . . . . . . . . .71


Testing Your App ..................................................................... 72
Running in the Simulator .............................................. 72
Testing with the Emulator ............................................ 73
Using the Emulator Manager
to create an image ........................................... 74
Launching an Emulator instance ....................... 75
Using the Connection Explorer.......................... 76
Running your application in the Emulator ....... 78
Using the Event Injector ..................................... 79

02_9781118539538-ftoc.indd v

1/18/13 1:28 PM

vi

Tizen For Dummies


Testing your app on a device ....................................... 81
Connecting the device ........................................ 81
Running your app on the device ....................... 81
Tracking Down the Bugs ......................................................... 82
Debugging in the Simulator .......................................... 83
Debugging in the Emulator ........................................... 83
Debugging on the device .............................................. 84
Debugging JavaScript .................................................... 85
Debugging with the Smart Development Bridge ........ 87
Using SDB commands ......................................... 87
Discovering the connected devices .................. 88

Chapter 6: Porting Your Web App to Tizen . . . . . . . . . . .89


Everything You Wanted to Know about
Web Apps (But Were Afraid to Ask) .................................. 90
Web apps on different platforms ................................. 90
Tools and frameworks .................................................. 91
Standards ........................................................................ 92
Distribution .................................................................... 92
Porting Problems Solved......................................................... 93
Handling different package formats ............................ 93
Making your layout flexible .......................................... 95
Fixing inconsistent behavior ........................................ 98
Porting device specific libraries ................................ 100
Making your app more portable ................................ 102

Part III: Tizen in Detail .................................. 103


Chapter 7: Building Your UI . . . . . . . . . . . . . . . . . . . . . . .105
Delving into the Nuts, Bolts, and jQuery Mobile................ 106
Embedded custom data attributes ............................ 106
Page structure .............................................................. 106
Events ............................................................................ 107
Exploring the Tizen UI Widgets ............................................ 107
Example: Building a Contacts UI .......................................... 109
Using the control bar as a tab bar ............................. 111
Adding a search bar .................................................... 112
Implementing the Swipe List ...................................... 113
Adding the finishing touches ..................................... 114
The UI Builder: Just Drag and Drop ..................................... 115
Choosing your widgets ............................................... 116
Implementing events in the UI builder ...................... 118
Adding Some Flourish to Your UI ........................................ 120

02_9781118539538-ftoc.indd vi

1/18/13 1:28 PM

Table of Contents

vii

Chapter 8: Taking Advantage of


Location-Based Services . . . . . . . . . . . . . . . . . . . . . .123
Location, Location, Location ................................................ 124
Finding Your Way................................................................... 124
Displaying a Map .................................................................... 125
Finding an Address ................................................................ 126
Tizen Geocoder API ..................................................... 127
Google Geocoder API .................................................. 128
X Marks the Spot .................................................................... 130

Chapter 9: Working with Multimedia . . . . . . . . . . . . . .133


Introducing the Multimedia APIs ......................................... 134
Discovering Content .............................................................. 134
Media source ................................................................ 135
Media item .................................................................... 135
Getting permission ...................................................... 136
Example: Creating a playlist ....................................... 137
Capturing Images and Video................................................. 138
Using the Application Service feature ....................... 139
ApplicationService object ................................ 139
Launching a service .......................................... 140
Example: Taking a photo ............................................ 140
Playing Audio and Video ....................................................... 142
Example: Playing local audio files ............................. 143
Example: Playing local video files.............................. 144
Multimedia Streaming ........................................................... 145
webkitGetUserMedia ................................................... 146
Example: Streaming video from
your devices camera .............................................. 147

Chapter 10: Using Hardware in Tizen . . . . . . . . . . . . . .149


Introducing NFC ..................................................................... 150
Using NFC in your Tizen Apps .............................................. 152
Setting up NFC .............................................................. 153
Setting up the listeners ............................................... 153
Reading a tag ...................................................... 154
Writing a tag ....................................................... 156
Using NFC in peer-to-peer mode ................................ 157
Detecting Device Orientation ............................................... 158
Detecting Device Motion ....................................................... 160
Using the Vibration API ......................................................... 161

02_9781118539538-ftoc.indd vii

1/18/13 1:28 PM

viii

Tizen For Dummies

Chapter 11: Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . .163


Introducing the Messaging API ............................................ 164
Message service ........................................................... 164
Message structure ....................................................... 164
Message .............................................................. 165
MessageBody ..................................................... 165
MessageAttachment .......................................... 165
Message storage ................................................ 166
Getting Permission................................................................. 166
Getting Practical: Searching for Messages.......................... 166
Creating the page ......................................................... 167
Filling the message list ................................................ 168
Initialisation ....................................................... 169
Searching for messages .................................... 169
Drawing the list .................................................. 170
Searching the message list ......................................... 171
Processing user input ....................................... 172
Searching for messages .................................... 173

Chapter 12: Working with Contacts . . . . . . . . . . . . . . . .175


Meeting the Key Personnel ................................................... 175
Address books ............................................................. 176
Contacts ........................................................................ 176
Getting Permission................................................................. 177
Managing Your Contacts ....................................................... 178
Adding a contact .......................................................... 178
Retrieving a contact .................................................... 179
Deleting contacts ......................................................... 181
Exporting a contact ..................................................... 182

Chapter 13: Getting Organized with Calendars . . . . . .183


Introducing the Calendar API ............................................... 183
CalendarManager ......................................................... 184
Calendar ........................................................................ 184
CalendarItem ................................................................ 184
Getting Permission................................................................. 185
Creating a Task ....................................................................... 186
Retrieving Tasks ..................................................................... 187
Setting an Alarm ..................................................................... 189

02_9781118539538-ftoc.indd viii

1/18/13 1:28 PM

ix

Table of Contents

Part IV: The Part of Tens ................................ 191


Chapter 14: Ten Really Useful Resources . . . . . . . . . . .193
JavaScript: The Definitive Guide .......................................... 193
Douglas Crockfords JavaScript Lectures ........................... 194
JavaScript: The Good Parts .................................................. 194
JavaScript Patterns ................................................................ 194
Browser Developer Tools ..................................................... 195
JavaScript Libraries ............................................................... 195
Keeping up with HTML5 ........................................................ 196
Smashing Magazine................................................................ 196
The Linux Foundation on YouTube ..................................... 197
And . . . You ............................................................................. 197

Chapter 15: Ten Reasons You Should


Develop for Tizen . . . . . . . . . . . . . . . . . . . . . . . . . . . . .199
Tizen Is Easy to Learn ........................................................... 199
Tizen Doesnt Reinvent the Wheel ....................................... 200
Tizen Supports the Latest Standards .................................. 200
Tizen Supports These Standards Very Well ....................... 200
Tizen Fills in the Gaps ........................................................... 200
Tizen Is Consistent................................................................. 201
You Can Easily Get Help ........................................................ 201
You Can Give Back ................................................................. 201
Tizen Isnt Just for Mobile..................................................... 201
Tizen Isnt Just for Web Developers .................................... 201

02_9781118539538-ftoc.indd ix

1/18/13 1:28 PM

Tizen For Dummies

02_9781118539538-ftoc.indd x

1/18/13 1:28 PM

Introduction

elcome to Tizen For Dummies. This book will be your


best friend to help you understand the technologies
and story behind the Tizen platform.
If you already know about web technologies, such as HTML
and JavaScript, you can use the information in these pages to
give you a head start in developing Tizen apps.

About This Book


The information in this book is based on the Tizen 2.0 alpha
release. Tizen is a fast-moving, evolving project, and youll
almost certainly be running a later version. Changes happen,
bugs are fixed, behaviours change, but the key concepts
dont. These key concepts are the heart of this book.
The Tizen SDK Help will always provide the most up-to-date
reference information. Check out https://developer.
tizen.org and the resources listed throughout this book to
ensure that you stay up to date.

Conventions Used in This Book


When this book was printed, some code or web addresses may
have needed to break across two lines of text. If that happened,
rest assured that we havent put in any extra characters (such
as hyphens) to indicate the break. So, when using this code or
one of these web addresses, just type exactly what you see in
this book, pretending as though the line break doesnt exist.
When youre choosing a series of menu commands, we use
to indicate the different commands youre choosing. So when
you see choose FileNewTizen Web Project, you should
simply click the File menu, click New from the menu that
appears, and then click Tizen Web Project.

03_9781118539538-intro.indd 1

1/18/13 1:28 PM

Tizen For Dummies


In addition, we often refer you to the Tizen website or the SDK
Help file. You can open the Help file from within the Tizen
IDE by choosing HelpHelp Contents. You can also find help
online at the Tizen website at https://developer.tizen.
org/documentation.

Who Should Read This Book


When writing this book, we made a few assumptions about
you, the reader. Youre either
A software engineer with experience developing for the
desktop, but no experience developing mobile apps.
Youre keen to start developing mobile apps and want to
know what Tizen offers.
A technical manager, evaluating the opportunities Tizen
offers for your next project on mobile.
A developer with a good grasp of web technologies,
such as HTML, JavaScript, and CSS, who is curious about
Tizen. (Dont worry if youre not a web guru; we dont
expect you to be.)
A parent with small children, looking for something to
read during the precious hours while the kids sleep
If any of the preceding applies to you, or you just stumbled
upon this book and found your curiosity piqued, the information presented here will give you a good idea of what the
Tizen platform is and how you can start developing for it.

How This Book Is Organized


To help you find the information you need, this book is
divided into four parts.

Part I: Introducing Tizen


If you want to know what makes Tizen different and discover Tizens place in the mobile landscape, you can find the
answers in this part. We examine how Tizen compares to other
platforms and explain the importance of the Tizen community.

03_9781118539538-intro.indd 2

1/18/13 1:28 PM

Introduction
We also give you a tour of the components of the Tizen plaform, explain how web applications fit in and provide you
with a quick summary of the Tizen Device APIs.

Part II: Getting Practical


Part II encourages you to fire up the Tizen IDE and start developing apps. Think of the first three chapters of this part as
a Tizen orientation trilogy, where you discover everything
you need to know to build your first Tizen app. In addition, if
youve built a web app for another platform and want to move
it to Tizen, we explain many of the issues youll encounter
when porting.

Part III: Tizen in Detail


Part III explains the Tizen Device APIs in more detail. We dont
include all the APIs or try to replace the information you can
find in the Tizen SDK Help. Instead, we focus on what you
need to know to build a fully featured Tizen web app.

Part IV: The Part of Tens


No For Dummies book would be complete without a part of
tens. In this part, you discover ten really useful resources
andten reasons why you should develop for Tizen.

Icons Used in This Book


Throughout the margins of this book are small pictures.
These icons have special meaning:
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!

03_9781118539538-intro.indd 3

1/18/13 1:28 PM

Tizen For Dummies


This icon highlights information that is nice to know but not
crucial to the discussion. Feel free to skip this information if
youre not interested in it.

Where to Go from Here


The content in this book is designed to be easy to navigate.
Dip in and dip out of each chapter as the mood takes you. We
dont expect you to read the book cover to cover, but if you
do make it to the end before your friends do, please dont
spoil the ending.
Think of this book as your first stop on your Tizen development journey. We explain the concepts, identify gotchas, provide hints, tips, and handy sample code, and draw on our own
experience to help kick-start your Tizen development efforts.
If youre an experienced web developer, you may want to
focus on the chapters that explain Tizen device APIs and
show you how to apply your existing knowledge of HTML and
JavaScript to create Tizen web apps.
If youre new to web development, it may feel at times as if
youre navigating uncharted waters. Think of this book as
your map. You discover how Tizen web applications are created using a mixture of technologies, including W3C APIs,
third-party Javascript libraries, and Tizen-specific APIs, all
mixed together to create powerful apps.

03_9781118539538-intro.indd 4

1/18/13 1:28 PM

Part I

Introducing Tizen

04_9781118539538-pp01.indd 5

1/18/13 1:29 PM

In this part . . .

his part is your Tizen orientation session, where


we issue you with your virtual map, compass and
backpack as you start to explore this new platform. You
learn about Tizens place in the mobile landscape and
what makes this mobile platform different from the rest.
You explore the structure of a typical open source platform, see where Tizen fits in and find out how you can get
involved in the Tizen community.
In Chapter 2 you learn how Tizen is organized and
discover how Tizen web applications look and behave
like native ones. We also explore Tizens support for web
standards and introduce the Tizen device APIs which
allow you to create powerful and feature-rich apps.

04_9781118539538-pp01.indd 6

1/18/13 1:29 PM

Chapter 1

Getting an Inside
Look at Tizen
In This Chapter
Discovering what makes Tizen unique
Becoming part of the Tizen community

ou may have heard of Tizen, but not know what it is.


No worries! In this chapter, you discover Tizens place
in the mobile world and some of the many reasons why this
open source software platform is one of a kind. You also find
out how Tizen compares to other mobile platforms and how
to become involved in 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.
Tizen has solid open source foundations, and it makes use
of established open source components, such as WebKit,
GStreamer, Xorg, and Connman. If you want to know how
Tizen compares to other open source mobile platforms, see

05_9781118539538-ch01.indd 7

1/18/13 1:30 PM

Part I: Introducing Tizen


the section Tizens place in the mobile world, later in this
chapter.
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.
At the time of writing, the Tizen 2.0 alpha release includes
APIs only for web app development. So, currently the only
way to create Tizen apps is to use HTML, JavaScript, and
related technologies. Luckily, thats the focus of this book.
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.0 alpha,
which was released in September 2012.

Tizens place in the mobile world


Our years of mobile development has taught us one simple
fact creating a mobile platform is hard. The average smart
device includes a dazzling range of technologies that put
desktop computers to shame. We expect our smart devices
to entertain us, help us find our way home, run our schedules
and just occasionally make phone calls. No one person can
be expected to be an expert in everything from application
development to the low-level technologies that enable your

05_9781118539538-ch01.indd 8

1/18/13 1:30 PM

Chapter 1: Getting an Inside Look at Tizen


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.

Figure 1-1: Different perspectives on the layers of a mobile open


source platform.

The way platforms are organized is often described in terms


of an onion. You gradually peel away the layers until you
reach the core.
At the top layer, we have applications and services. Its whats
contained here that helps end users make their decision
about which device to buy. They choose their devices according to what apps and services are available for them to use.
Next we come to the platform level. This layer is where youll
find the APIs and SDKs that allow developers to create applications. Its where youll find Tizen and the APIs discussed in
this book. Tizen has many similarities to other platforms, but
you discover the differences, too.

05_9781118539538-ch01.indd 9

1/18/13 1:30 PM

10

Part I: Introducing Tizen


Delving deeper we come to the middleware. Many middleware
components will come from conventional desktop open source
projects. Different platforms will pick and choose which open
source components to include. The great thing about open
source software is the range of components available.
The lowest layer is the kernel. For open source mobile platforms,
this layer will generally be a Linux kernel. The kernel interacts
with middleware components to talk to the hardware. Its the
middleware layer that the platform developers, who contribute
to the components of the platform, will be most interested in.

Figuring Out What Makes


Tizen Different
When Tizen was announced, some of the most common
questions asked by developers, analysts and users included
whether a new platform was needed at all and what makes
Tizen stand out from the crowd.
In this book, we attempt to answer some of these questions,
but for now, here are four ways in which Tizen is different
from the rest.

Tizen is based on standards


HTML5 is a set of standards that enjoys support from across
the industry, and its a standard that Tizen supports very
well. HTML5 supports multiple browsers, operating systems,
and devices. In its latest incarnation, HTML5 provides greater
access to device hardware, advanced audio and video capabilities, and more flexibility for design and layout. Using HTML5,
developers can create cross-platform applications, writing the
code once and running it on multiple platforms. The extent to
which a platform supports the HTML5 specification is vital for
developers who want to make the most of the latest features.
Tizen supports most of the official HTML5 standards, along
with some miscellaneous and legacy standards. Designed to
get the most out of HTML, JavaScript, and CSS, Tizens web
engine is tuned to within an inch of its life to squeeze best
performance out of these technologies.

05_9781118539538-ch01.indd 10

1/18/13 1:30 PM

11

Chapter 1: Getting an Inside Look at Tizen

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

code to the platform is freely available, anyone can download it, and
you can use it for any purpose in any
project. We accept that this may not
meet everyones definition of open
source software, but this is our definition, and were sticking to it.

Not only does the Tizen web engine (based on WekKit2 since
Tizen 2.0) perform well, its web browser also scores highly in
web standards compliance tests, finishing first according to
the scores from http://html5test.com, which test how
well a browser supports HTML5 specifications.

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 customised 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.

Tizen is innovative
Innovation can come from many sources. It may be an idea
from an individual or an organizations R&D projects, but
most innovation comes from collaboration.

05_9781118539538-ch01.indd 11

1/18/13 1:30 PM

12

Part I: Introducing Tizen


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.

Tizen has industry support


One lesson learned from previous open source platforms is
that being open source doesnt necessarily guarantee success
or innovation. A project must have strong industry support.
The Tizen Association board includes many operators and
device manufacturers, and a strong ecosystem built around
Tizen offers opportunities far beyond smartphones. You can
look forward to your applications running not only on mobile
phones, but also on in-vehicle infotainment systems, notebooks,
tablets, and Smart TVs.
At the time of writing, the board members of the Tizen
Association are Intel, Samsung, Telefonica, Sprint, Vodafone,
Orange, NTT docomo, Sprint, Panasonic, SK Telecom, Huawei,
and NEC.

Comparing Tizen to
Other Platforms
Tizens openness contrasts with closed, proprietary platforms, such as iOS, Blackberry OS 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.
Of the open source alternatives, WebOS and Firefox OS are
both platforms with potential, but they dont have the same
level of industry support as Tizen.

05_9781118539538-ch01.indd 12

1/18/13 1:30 PM

13

Chapter 1: Getting an Inside Look at Tizen

Android is the best known open source platform, but the governance of the platform is arguably not as open, and its standards support isnt as comprehensive as Tizen.

Getting Familiar with


the Tizen Association
The Tizen Association and the Tizen Project, under the Linux
Foundation, are complementary to each other. The industry
and market-facing aspects of Tizen are driven by the Tizen
Association, while the engineering of the Tizen software platform takes place within the Tizen open source project hosted
by the Linux Foundation. The Linux Foundation runs the Tizen
Project, with a focus on platform development and delivery.
You can find out more at www.tizenassociation.org.
The board of directors decides the commercial direction of
the Tizen Association. The board decides on the platform
requirements, business strategy, application store requirements, and industry partnerships. It aims to evolve the ecosystem of the Tizen platform.
Several technical steering groups (TSGs) govern the Tizen
Project. Intel and Samsung, as the two primary platform contributors, chair the TSGs, and other interested parties can
participate.

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
only and will mainly be open to the Tizen vendors. However,
the Community Office, Localization, and some Middleware
groups will be open to participation on a merit basis.

05_9781118539538-ch01.indd 13

1/18/13 1:30 PM

14

Part I: Introducing Tizen

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.

Mailing list and IRC


Several mailing lists and an IRC channel enable community
members to share information and ask questions about the
Tizen platform.
Details of these mailing lists and how to join them are provided on the Tizen community website:
www.tizen.org/community/mailing-lists
The IRC channel is #tizen at: irc.freenode.net, and the
channels logs are available to view:
www.tizen.org/irclogs

05_9781118539538-ch01.indd 14

1/18/13 1:30 PM

Chapter 1: Getting an Inside Look at Tizen

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.

05_9781118539538-ch01.indd 15

1/18/13 1:30 PM

16

Part I: Introducing Tizen

05_9781118539538-ch01.indd 16

1/18/13 1:30 PM

Chapter 2

Exploring the Tizen


Architecture
In This Chapter
Looking at Tizens organisation
Exploring the role of the web runtime
Getting an inside look at the web APIs
Listing the Tizen device APIs

izen isnt just for smartphones and tablets; its designed


to drive a wide range of device categories from smart TVs
to netbooks and beyond. For example, the IVI project is setting standards to allow Tizen to be used as part of in-vehicle
infotainment systems in cars, planes, and buses. In the future,
you may find Tizen on Blu-ray players and digital TVs or powering a new generation of netbooks.
Because Tizen is open source and standards based, developers
in the open source community can find uses for Tizen in
devices far beyond whats available today. Maybe youll find
Tizen in your fridge or alarm clock or in a home automation
system. The possibilities are endless.
Its the incarnation of Tizen defined for smartphones and
tablets that we concentrate on in this book. Web developers
dont have to know the inner workings of Tizen in order to
create apps, but the more you know about the platform, the
more informed your development choices can be.

06_9781118539538-ch02.indd 17

1/18/13 1:30 PM

18

Part I: Introducing Tizen

Introducing Web Apps


The term web app is actually quite broad. Our definition is
apps based on web technologies that can access system
resources and that you can install on a device although
they dont have to be.
Is a website a web app? Yes, it is. Websites are built with
standard web technologies and can use W3C APIs to access
some device features. They dont have to be installed because
everything happens in the browser.
Tizen web apps are created using a combination of W3C/
HTML5 specifications, miscellaneous web specifications, and
Tizen web app device APIs. The important thing to know for
this section is that Tizen web apps are just like traditional apps:
They can access system resources.
They can launch other apps.
They provide services.
They generally behave like traditional native apps do.

The web runtime


Each web app is one Linux process. In the task manager of a
Tizen device, you can see a Tizen web app just like a native
app. You can utilise process scheduling and management, and
platform security features also apply.
The web runtime provides a framework for installable web
applications. The role of the web runtime is to install and
launch apps and provide integration with the native platform,
exposing Tizen APIs so that web apps can access device features. The web application can be integrated with the task
manager and package manager, and it can also receive some
of the system events, such as out of memory, screen orientation, and system locale change.

06_9781118539538-ch02.indd 18

1/18/13 1:30 PM

Chapter 2: Exploring the Tizen Architecture

19

The web runtime is also responsible for access control checking. Whenever a web app calls a JavaScript API, the web runtime checks that the app is allowed to access that particular
feature, returning an error if access is denied. This process
provides a high level of runtime security.
Figure 2-1 shows the components of the web runtime. As you
can see from Figure 2-1, the web application talks to the web
runtime, which then communicates with the layer below to
access the features of the device. The web runtime consists
of an installer, runtime core, plugin core, and security components. The following sections look at these areas in more
detail.

Figure 2-1: The Tizen web runtime.

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.

06_9781118539538-ch02.indd 19

1/18/13 1:30 PM

20

Part I: Introducing Tizen

Checking the specs


You can find the current status of
Tizens support for particular W3C
APIs in the online help in the Tizen
W3C API Specifications section.
HTML5 is a moving target, and
Tizens API support is evolving. By
the time you read this book, the
HTML5 support will be even better.

In fact, because Tizen provides such


good HTML5 support, you can create
many web apps without using any
Tizen-specific APIs at all. You can
still access some device features,
such as geolocation, and some
sensor features all from within a portable completely standard web app.

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.

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

06_9781118539538-ch02.indd 20

1/18/13 1:30 PM

Chapter 2: Exploring the Tizen Architecture

21

advantage of on-demand loading of plugins is that the web


app starts faster because plugins are loaded only when the
JavaScript needs them.

Using Tizen Web APIs


You create Tizen web apps using a combination of W3C/
HTML5 specifications, miscellaneous web specifications, and
Tizen-specific device APIs. Tizen provides support for many
HTML5 features, such as audio and video, offline web storage, web workers, and 3D transform and transition effects.
You can use these standard technologies in a web application.
Tizen also includes support for some APIs not specified in W3C
but that are part of miscellaneous common web standards.
Included in this list are typed arrays and the viewport metatag
definition.
Figure 2-2 shows the relationship between W3C APIs, miscellaneous APIs, and Tizen-specific device APIs. Of course,
when you build web apps, youre also likely to use various
JavaScript utility libraries, such as jQuery and jQueryMobile.
With so many libraries available for you to use, you dont
need to re-invent the wheel.

Figure 2-2: The APIs available to a Tizen web application.

06_9781118539538-ch02.indd 21

1/18/13 1:30 PM

22

Part I: Introducing Tizen

Exploring the Tizen Device APIs


So why does Tizen need its own JavaScript device APIs? Well,
it turns out that while the W3C specifications do provide a lot
of features, some gaps exist. Tizen device APIs were created to
fill these gaps. For example, you can find Tizen APIs for manipulating contacts and calendars in Chapters 12 and 13. You also
discover how to give your apps a consistent look and feel in
Chapter 7, which introduces the Tizen Web UI Framework.
These Tizen APIs are all contained within the Tizen namespace.
The idea behind these APIs isnt to compete with the W3C
APIs. In fact, Samsung and Intel participate on various standards committees that define W3C APIs. The aim is that the
Tizen device APIs will one day be absorbed into W3C so that
theyll become standards.
Tizen is still an evolving platform and Tizen device APIs are
designed to supplement, not replace, the functionality of the
W3C APIs. However, the device features provided by the W3C
APIs are also becoming more comprehensive. You might find
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
When a Tizen web app is launched, Tizen examines the apps
configuration file to determine which features are supported.
If the Tizen feature is specified, then a Tizen JavaScript object
is created which can then be used to access the rest of the
device APIs such as Contact, Calendar and NFC. You can find
more about features and the configuration file in Chapter 4.

06_9781118539538-ch02.indd 22

1/18/13 1:30 PM

Chapter 2: Exploring the Tizen Architecture

23

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.

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
service. 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 service.

Bluetooth
The Bluetooth API provides access to the Bluetooth protocol,
which can be used for transmitting files over short distances
between devices.

06_9781118539538-ch02.indd 23

1/18/13 1:30 PM

24

Part I: Introducing Tizen

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.

Call
The Call API provides access to the call history and allows
you to monitor the status of the current call.

Contacts
You use the Contacts API to manage contacts and handle
multiple address books. Chapter 12 explains the Contacts
API in detail.

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.

Geocoder
The Geocoder API is responsible for converting geographic
co-ordinates (longitude and latitude) into user-readable
addresses and the other way around. Chapter 8 explains this
API in more detail.

Media Content
The Media Content API lets you search for multimedia content on the device, either stored locally or on a memory card.
Chapter 9 shows you how to use these features.

06_9781118539538-ch02.indd 24

1/18/13 1:30 PM

Chapter 2: Exploring the Tizen Architecture

25

LBS (Location-Based Service)


The LBS API helps you manage location services, such as
geolocation and maps provided by location service providers.
The W3C APIs provide many location features. See Chapter 8
for more information.

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.

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. Limited
notification features were implemented in the version of Tizen
available at the time of writing- 2.0 alpha.

Power
Another new API introduced in Tizen API, 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.

06_9781118539538-ch02.indd 25

1/18/13 1:30 PM

26

Part I: Introducing Tizen

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.

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.

06_9781118539538-ch02.indd 26

1/18/13 1:30 PM

Part II

Getting Practical

07_9781118539538-pp02.indd 27

1/18/13 1:30 PM

In this part . . .

n this part we start to get practical. You download and


install the Tizen SDK, start to find your way round the
tools, and build your first Tizen app. In Chapter 3 you
learn enough to get up and running, while Chapter 4 takes
you through each component of a Tizen app in detail.
Youll explore some of the sample apps and discover how
theres a world of third party JavaScript libraries ready for
you to use in your apps. Chapter 5 tidies up the messy
business of testing and debugging.
You might have an existing web app that you want to port
to Tizen, in which case you will find some useful tips in
Chapter 6. We also explain how you can design your Tizen
web app to make it more portable.

07_9781118539538-pp02.indd 28

1/18/13 1:30 PM

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.

08_9781118539538-ch03.indd 29

1/18/13 1:30 PM

30

Part II: Getting Practical

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, HTML Preview, and CSS
preview. Chapter 5 introduces the
Connection Explorer, while the HTML

Preview and CSS Preview views are


covered in their own sections later
in this chapter. You can also open
up other useful views not shown in
the current perspective by choosing WindowShow View. Theres
much more detail about perspectives, views, and the workbench in
the Tizen SDK help.

Installing the IDE


The Tizen SDK provides a set of tools for developing Tizen
web applications. The IDE is based on Eclipse, which will be
familiar to you if youve done any Symbian, Android, or bada
development. The SDK also includes a tool chain to build apps
for your chosen hardware platform and lots of sample code,
tutorials, and documentation to help you get started.
This chapter refers to the 2.0 Magnolia version of the Tizen SDK.
To begin your journey into Tizen development, you first need
to download the SDK from the Tizen website at https://
developer.tizen.org/downloads/sdk.
The currently supported platforms are
Ubuntu (11.04/11.10) 32-bit & 64-bit
Windows XP 32-bit
Windows 7 32-bit & 64-bit
You can download two files for either Windows or Linux: the
installation manager and the SDK Image. The installation manager is responsible for installing the SDK, and you can use it in
one of two ways. You can download the SDK from the server
during the installation process, or you can download a separate
SDK image file and choose to install the SDK from this package.

08_9781118539538-ch03.indd 30

1/18/13 1:30 PM

31

Chapter 3: Getting Started

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.
Now youre ready to start developing apps.

Figure 3-1: The Tizen Web Perspective.

Creating Your First


Tizen Web App
The easiest way to create a new Tizen project is by using the
New Project wizard. The wizard allows you to create your
application using some predefined templates or create a project from one of the built-in sample apps. You can also use
user-defined templates, which we explain in more detail in the
User-defined templates section.
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.

08_9781118539538-ch03.indd 31

1/18/13 1:30 PM

32

Part II: Getting Practical


To launch the New Project wizard and choose a template,
follow these steps:
1. In the IDE, choose FileNewTizen Web Project.
The New Project wizard appears. You see a selection
of templates and sample applications to choose from
(see Figure 3-2).

Figure 3-2: The New Project Wizard.

2. Choose the template or sample you want to use.


Tizen offers several predefined template types:
Basic: A blank application template.
Tizen WebUI Framework: A set of templates with
all the necessary files for creating a web application
using the Tizen web UI framework.
jQuery Mobile: A set of templates containing all the
files to create a web application using the jQuery
Mobile framework.
Tizen Web UI Builder: A set of templates containing all the files to create a web application using the
Tizen Builder.
3. Name your project.
4. Click Finish.

08_9781118539538-ch03.indd 32

1/18/13 1:30 PM

33

Chapter 3: Getting Started

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.

Using a sample app


If you want to create a slightly more complicated application,
you can use one of the sample applications provided in the
SDK as a starting point. Walking through the sample code is
also a great way to become familiar with particular features.
The New Project wizard provides many sample applications
to demonstrate the use of the Tizen APIs: Alarm, Application,
Appservice, Bluetooth Client, Bluetooth Server, Calendar, Call,
Contact, Filesystem, Geocoder, Kitchen Sink, Mediacontent,
Messaging, NFC, Power, Systeminfo, and Time.
The Tizen developer website also provides other samples
that you can use to start developing an application. (See the
Importing an existing project section, later in this chapter,
for more details on how you can use these samples.)

Using your own template


If you have an existing template from another web-based
platform or youre developing several applications based on
a common structure, you may want to define your own template. The New Project wizard provides an option for creating
an application based on your own user-defined templates.
Before you can use this option, you need to create your own
application project template. You can create a user template
based on any project, using the Export wizard. To use the
Export wizard, follow these steps:
1. Right-click the project in the Project Explorer view
and choose Export.
The Export dialog box appears.
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.

08_9781118539538-ch03.indd 33

1/18/13 1:30 PM

34

Part II: Getting Practical

Figure 3-3: The Tizen user template.

3. Click Next.
The User Template Export wizard appears.
4. Enter the name and export location.
5. Select the Import a Template check box so that your
template will appear in the New Project wizard.
6. Click Next.
The icon selection screen of the User Template Export
wizard appears.
7. Add any icons that you want to be shown in the new
wizard.
8. Click Next.
The images and descriptions screen appears.
9. Add any images or descriptions that you want displayed in the new wizard.
10. Click Finish to complete the export of your user
template.

08_9781118539538-ch03.indd 34

1/18/13 1:30 PM

35

Chapter 3: Getting Started

Importing an existing project


Using the New Project wizard isnt the only way to create an
application; you can also import existing applications into
theIDE.

Tizen web application


To import an existing Tizen web app, follow these steps:
1. Choose FileImport.
The Import dialog box, shown in Figure 3-4, appears.
2. From the Select an Import Source list, double-click
Tizen and then select Projects and Widget file.
3. Click Next.
The Import Widget screen appears.
4. Enter the root directory or click the Browse button
to select the projects you want to copy into the
workspace.
5. Click Finish.
The project is imported into the workspace.

Figure 3-4: The Import dialog box of the New Project Wizard.

08_9781118539538-ch03.indd 35

1/18/13 1:30 PM

36

Part II: Getting Practical

Other web applications


If you have a web application developed for the desktop or
another mobile platform, you can import it into the IDE by following these steps:
1. Choose FileNewProject.
2. In the wizards drop-down list, double-click the
General folder and then click Project (see Figure 3-5).
3. Click Next.
4. Uncheck the use default location check box and
enter the name and location of your project.
5. Click Finish.
Your project is now created and loaded into the
workspace.

Figure 3-5: Import other web apps.

After you create the project, you need to edit two files:
.project and config.xml. You can find full instructions
onhow to edit these files on the Tizen developer website:
https://developer.tizen.org/downloads/
sample-web-applications/
load-web-app-tizen-sdk

08_9781118539538-ch03.indd 36

1/18/13 1:30 PM

37

Chapter 3: Getting Started

Writing the Code


The SDK provides many useful tools to help you write and
edit your apps code. These tools are designed to help you
throughout your development process, helping you preview
your HTML code as you create it, crafting the look of your
pages with CSS Preview, and making the JavaScript coding
process easier and more efficient.

HTML Web Page Editor


The IDE provides a WYSIWYG editor for editing HTML files.
The Web Page Editor allows you to view both the source code
and preview the HTML as youre developing your application
(see Figure 3-6).
The IDE offers several options, shown in Table 3-1, for viewing
your HTML content.

Table 3-1
HTML View Modes

Web Page Editor View Modes


Description
Show Design Page & Source Page as
Vertical panes
Show Design Page & Source Page as
Horizontal panes
Show Design Page only
Show Source Page only

You could choose to handcraft your HTML, but you can


also use the palette feature provided in the IDE. HTML4 and
HTML5 palettes are provided for you in all views except the
Source Page Only mode. To use an object from the palette,
just select a component and drag it to the required location
on either the Design or Source page.

08_9781118539538-ch03.indd 37

1/18/13 1:30 PM

38

Part II: Getting Practical

Figure 3-6: The Web Page Editor.

HTML Preview pane


You can instantly preview a HTML file in the HTML Preview
pane (see Figure 3-7). WebKit is used to display the content
in the Preview pane, so the appearance will be more accurate
than the preview in the Web Page Editor, which uses your systems default browser.

Figure 3-7: The HTML Preview pane.

This pane is visible in the default Web Perspective, or you can


view it by choosing WindowShow ViewHTML Preview.

08_9781118539538-ch03.indd 38

1/18/13 1:30 PM

Chapter 3: Getting Started

39

CSS Preview pane


You can instantly preview the look and feel of any CSS file in
the CSS Preview pane, shown in Figure 3-8. WebKit is used to
display the content in the Preview pane, and any changes will
be reflected immediately.

Figure 3-8: The CSS Preview pane.

This pane is visible in the default Web Perspective, or you can


view it by choosing WindowShow ViewCSS Preview.

Minifying CSS and JavaScript


The IDE provides tools to minify your CSS and JavaScript files
if you need to reduce the size of your code.

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.

Figure 3-9: Minify CSS.

08_9781118539538-ch03.indd 39

1/18/13 1:30 PM

40

Part II: Getting Practical

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.

Figure 3-10: Minify JavaScript.

Building Your Project


A Tizen application is packaged in a .wgt file that can be
downloaded and installed on a device or Emulator. You can
find out more information about an application package and
its content in Chapter 4.
When youre developing your application, if the Build
Automatically option is enabled, then the application package
will be rebuilt every time you save any changes. Any errors or
warnings found in your JavaScript code will be shown in the
Problems View at the bottom of the IDE.

Running Your Project


You can test whether your application works by running it in
the Simulator or Emulator environment or on a Tizen device.
For more information about how to test your project, see
Chapter 5.
If you want to, you can select one of the sample applications
introduced in the Using a sample app section, earlier in this
chapter, and try building and running the app for yourself.

08_9781118539538-ch03.indd 40

1/18/13 1:30 PM

41

Chapter 3: Getting Started

Help Is on the Way


The Tizen SDK provides a comprehensive set of Help documentation, tutorials, and sample code to help you get started.
You can find lots of other resources, too, including the developer site, wiki, forums, mailing lists, and a bug tracker. Blogs
and forums created by community members are also just a
quick Internet search away, and these resources will only
increase as the community grows.
You can access Help documentation and get information
about any APIs by hovering over the function names. The IDE
also provides an Auto completion feature to avoid making any
typing errors when using the Tizen APIs.

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.

08_9781118539538-ch03.indd 41

1/18/13 1:30 PM

42

Part II: Getting Practical


Tizen Web App Programming/Programming Guide
includes the Device API Guide, which explains 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/Web 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/
sample-web-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.

08_9781118539538-ch03.indd 42

1/18/13 1:30 PM

Chapter 4

Piecing Together the


Application Jigsaw
In This Chapter
Introducing the application package
Getting inside the configuration file
Seeing how a Tizen app fits together

s a web developer, you can count on standards, such


as the W3C APIs that form part of HTML5, but the apps
that use these APIs arent so much developed from scratch
as assembled from a jigsaw puzzle of pieces. You may have
an app that uses W3C APIs, makes use of a library (such as
jQuery), and even includes JavaScript, HTML, and CSS files
generated by a tool like Dreamweaver. The possibilities are
endless, but knowing how to piece all these parts together
and add your own code to the mix can be a challenge.
In this chapter, we examine the components of the application package, including the configuration file that contains the
app settings. We show you how to put the pieces of the puzzle
together to create a Tizen web app, from the simplest possible app to a more advanced app that makes use of the Tizen
device APIs. Armed with this information, youll understand
how a Tizen app is put together and have a solid foundation
for creating your own apps.
For full details about downloading, installing, and taking your
first steps with the Tizen SDK, go to Chapter 3. Chapter 5
covers testing and debugging.

09_9781118539538-ch04.indd 43

1/18/13 1:31 PM

44

Part II: Getting Practical

Examining the Pieces


The way you work through this chapter is up to you. You can
use it as a reference that you dip in and out of as you write
your app or follow along with the Tizen IDE in front of you.
If you want to follow along, then why not build one of the
sample apps as described in Chapter 3? This section isnt
based around one app, but if you have one of the Tizen
samples loaded into the IDE, youll be able to find the main
components as theyre explained.

The application package


When you build a Tizen app for the Simulator, Emulator,
or device, the app is packaged in the W3C standard widget
format, a zip format compressed archive that has a file type
of .wgt. This package contains all your JavaScript, HTML,
and CSS files, together with the images, configuration file, and
other resources that your app uses.
To take a closer look at the package, double-click the .wgt
file in the Project Explorer. The package contents are revealed
and look something like the app package shown in Figure 4-1.
You can find the specification of the W3C widget format at
www.w3.org/TR/widgets.

Figure 4-1: Systeminfo example application


package content and structure.

09_9781118539538-ch04.indd 44

1/18/13 1:31 PM

Chapter 4: Piecing Together the Application Jigsaw

45

If youve minified any JavaScript or CSS files to reduce the


size of your code, by default both the original and the minified
version will be included in the package. You must remember
to manually remove the original version either from the final
package or from your project and update your project files to
use the minified version of the file.

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 localization. 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.

Figure 4-2: Example application with localized contentpackage content and structure.

For each locale, you can localize as much application content


as is appropriate. For example, in Figure 4-2, the Spanish (es)
locale, unlike the French (fr) locale, only has localized content

09_9781118539538-ch04.indd 45

1/18/13 1:31 PM

46

Part II: Getting Practical


for the index.html file and will fall back to use the default
version of the icon.png file.
You can create all the necessary files and folders for localizing
your app using the Tizen Localization wizard. To launch the
wizard, right-click your project in the Project Explorer panel
and choose the LocalizationLocalization Wizard menu item.
This wizard allows you to choose which files to localize, as
well as the locales you want to support.
You can find the folder naming standards as part of the widget
specification at www.w3.org/TR/widgets.

The configuration file


The configuration file is an XML file that contains information about the features of the application. The Tizen platform
supports the configuration file as defined in the W3C widget
specification and adds some Tizen-specific extensions.
You can create or edit this XML file either by hand or by
using the Configuration Editor provided in the IDE. You must
include this configuration file in your application package.

Breaking down the config file


Listing 4-1 shows an example of a config.xml file used for a
simple Tizen web application:

Listing 4-1

Example config.xml file

<?xml version=1.0 encoding=UTF-8?>


<widget xmlns=http://www.w3.org/ns/widgets
xmlns:tizen=http://tizen.org/ns/widgets id=http://
yourdomain/SysteminfoSample version=0.13
viewmodes=fullscreen>
<name>SysteminfoSample</name>
<icon src=icon.png/>
<content src=index.html/>
<feature name=http://tizen.org/api/tizen required=true/>
<feature name=http://tizen.org/api/application.read
required=true/>
<feature name=http://tizen.org/api/systeminfo
required=true/>
<tizen:application id=samplesysi required_version=1.0/>
</widget>

09_9781118539538-ch04.indd 46

1/18/13 1:31 PM

47

Chapter 4: Piecing Together the Application Jigsaw

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.13
viewmodes=fullscreen>
</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.
<name>SysteminfoSample</name>
<icon src=icon.png/>
<content src=index.html/>
<feature name=http://tizen.org/api/tizen
required=true/>
<feature name=http://tizen.org/api/application.read
required=true/>
<feature name=http://tizen.org/api/systeminfo
required=true/>

Finally, the tizen application id and minimum platform version


attributes are defined. The tizen application id is a Tizen specific extension which is used to identify a Tizen application. It

09_9781118539538-ch04.indd 47

1/18/13 1:31 PM

48

Part II: Getting Practical


is mandatory and is represented with a 10-character alphanumeric value:
<tizen:application id=samplesysi required_version=1.0/>

config.xml the easy way: the Configuration Editor


Rather than creating the config.xml file by hand, the Tizen
IDE makes things easier by including a Configuration Editor.
This tool automatically adds all the mandatory elements and
helps you generate a valid config.xml file.
To open your config.xml file for editing in the Configuration
Editor, right-click the file in the Project Explorer panel and
choose Open WithWidget Configuration Editor. Figure 4-3
shows the Configuration Editor open at the Overview window.
(You may recognize some of the information in Figure 4-3 if
you read the last section.)

Figure 4-3: The Configuration Editor.

The Configuration Editor displays the contents of the


config.xml file in eight separate tabs: Overview, Widget,
Feature, Access, Localization, Preferences, Tizen, and Source.
The following sections describe the content of each tab.

Overview
In the Overview tab, you can enter general information about
your application.

09_9781118539538-ch04.indd 48

1/18/13 1:31 PM

49

Chapter 4: Piecing Together the Application Jigsaw


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

Attributes in the Overview Tab

Type

Description

Identifier

IRI identifier for the widget

Version

The current version of the widget

Name

Full human-readable name for a widget


(for example, for use in an application
menu)

Content

Custom start file that the user agent is


expected to use when it instantiates
the widget

Icon

Custom icon for the widget

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.

Table 4-2

Specific Information in the Widget Tab

Type

Description

Author

People or an organization associated with the


creation of the widget

E-mail

Email address associated with the author

Web Site

IRI associated with the widget for example,


your website, Facebook id, and so on

License

Software license, including copyright and


redistribution terms

License URL

Valid IRI or a valid path that points to the


detailed license information

Description

Human-readable description of the widget

09_9781118539538-ch04.indd 49

1/18/13 1:31 PM

50

Part II: Getting Practical

Table 4-3

Attribute Information in the Widget Tab

Type

Description

Width

Preferred viewport width of the instantiated


custom start file

Height

Preferred viewport height of the instantiated


custom start file

View Modes

Authors preferred view mode (full screen,


floating, windowed, maximized, minimized)

Feature
A feature is a URI-identifiable runtime component for example, an API such as http://tizen.org/api/systeminfo.
In order to access a feature or API at runtime, your application
must register it in the config.xml file. To add a new feature
to your applications config.xml file, select the Feature 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 features. Optionally, using the
other radio buttons and text boxes, you can enter a URL or
the name of a file that contains a feature definition.

Figure 4-4: Add a new feature.

09_9781118539538-ch04.indd 50

1/18/13 1:31 PM

51

Chapter 4: Piecing Together the Application Jigsaw


After you select the new features, click the Finish button. To
enable the features, you must also check the box next to the
Feature name, as shown in Figure 4-5.

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.

Figure 4-5: Enabling a new feature.

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.
To allow access to a network URL, select the Access tab
and click the Add button. Enter the network URL and select
whether the application should be able to access the URLs
subdomains.
In the Example 1: A 5-Minute Application section, later in
this chapter, we show you how to create a simple app that
displays content from the Food Networks website, as shown
in Figure 4-8. Well leave it to you to decide if were partial to
cakes.
Youll notice that http://m.foodnetwork.com and other
related sites were added to the access origin section of the
config.xml file. The app needs to access these external
resources in order to retrieve the data to display.

09_9781118539538-ch04.indd 51

1/18/13 1:31 PM

52

Part II: Getting Practical


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:
1. Right-click the element and choose Select Languages.
The Select the Locales dialog box, shown in Figure 4-6,
appears.

Figure 4-6: Locales.

2. Add any new locales you want to support.


To do so, choose the required locales from the
Available locales list and click the Add button to add
them to the Selected locales list.
3. Click OK to return to the Localization window,
shown in Figure 4-7.

09_9781118539538-ch04.indd 52

1/18/13 1:31 PM

53

Chapter 4: Piecing Together the Application Jigsaw

Figure 4-7: Localizing the application name.

Elements that can be localized appear with a triangle


icon on the left side.
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.
Figure 4-7 shows the application name expanded to
show the Italian and Korean locales. In this example,
you can provide a localized version of the application name for these locales by entering text in the box
labeled Selected Element:Name.
5. Choose a locale from the list and type the localized
text in the Selected Element box at the bottom of the
window.
6. Repeat Step 5 for all the elements and locales for
which you want to provide localized content.
7. Choose Save or close the config.xml window when
youre done.

Preferences
A preference is a persistently stored name-value pair that is
associated with the application. You usually use a preference
to store application settings, such as whether a calendar app
was last opened in month or day view, for example.

09_9781118539538-ch04.indd 53

1/18/13 1:31 PM

54

Part II: Getting Practical


To add a preference name-value pair to your applications
config.xml file, select the Preferences tab and click the
Add button. A new row is added to the Preferences table, and
youcan add the name, value, and whether the preference is
read-only.

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 platform that the
application supports, settings such as screen orientation and
context menus, and any app service information.
Table 4-4 shows the attributes that you can set in the Tizen
tab if your application provides an application service for
other applications to use.

Table 4-4

Tizen Information

Type

Description

src

Page that provides the functionality described


by operation, scheme, and mime

operation

Action to be performed by the service

scheme

URI scheme to describe what type of URI can


be handled

mime

mime type that can be handled

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.
The config.xml file must conform to the XML formatting
rules and the W3C specification requirements, so be careful
when manually editing this file.

09_9781118539538-ch04.indd 54

1/18/13 1:31 PM

55

Chapter 4: Piecing Together the Application Jigsaw

Start file
The start file is the file that is loaded by the web runtime on
application startup. It is a mandatory part of the application
package. 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/>

The start file is where you create your web applications


visual content, structure, and controls. You can edit this file
using the HTML Web Page Editor tools provided in the IDE, as
described in Chapter 3.

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>

If youre using multiple JavaScript files, dont forget to load


them all in the header section of the index.html file.
If youve minified your JavaScript files, dont forget to include
this version in the index.html file instead of the original
for example:
<script src=js/main.js.min></script>

09_9781118539538-ch04.indd 55

1/18/13 1:31 PM

56

Part II: Getting Practical

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.
If youve minified your CSS files, dont forget to load this version
in the index.html file instead of the original for example:
<link rel=stylesheet href=css/style.css.min />

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.

09_9781118539538-ch04.indd 56

1/18/13 1:31 PM

57

Chapter 4: Piecing Together the Application Jigsaw

This file isnt mandatory in the package, but if the application


is signed by the author, only one author-signature.xml
file can exist.
Check out the SDK Help for more details about creating an
author signature.

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.
Before making use of any third-party source code or libraries
in your application, please ensure that you check the license
thoroughly and comply with the terms and conditions of use.

09_9781118539538-ch04.indd 57

1/18/13 1:31 PM

58

Part II: Getting Practical

Adding source code or libraries to a project


You can add source code or libraries to your application
project in several ways:
You can add a new file by right-clicking your project
in the Project Explorer panel and choosing New from
the menu. You can then choose to add a new folder or
source file (html, css, and so on) to the project.
You can add existing files to your project by right-clicking the required project folder in the Project Explorer
panel and choosing ImportGeneralFile System. Then
choose the files you want to import. Alternatively, you
can add files by dragging and dropping them into the
project via the Project Explorer panel.

Adding source code or libraries in index.html


In order to use any external source code or libraries in an
application, you need to load them in the applications start
file, index.html. In this example, all the external source
code and libraries shown in Listing 4-2 are loaded in the head
section of the index.html document.

Listing 4-2 Loading External Source in index.html


<link href=css/wijmo/jquery.wijmo.wijprogressbar.css
rel=stylesheet type=text/css />
<link href=css/wijmo/jquery.wijmo.wijutil.css rel=stylesheet
type=text/css />
<link href=css/wijmo/jquery.wijmo.wijexpander.css
rel=stylesheet type=text/css />
<link href=css/wijmo/jquery-wijmo.css rel=stylesheet
type=text/css />
<link href=css/style.css rel=stylesheet type=text/css />
<script src=js/jquery-1.7.min.js></script>
<script src=js/jquery-ui-1.8.12.custom.min.js></script>
<script src=js/wijmo/jquery.wijmo.wijutil.min.js type=text/
javascript></script>
<script src=js/wijmo/jquery.wijmo.wijtooltip.min.js
type=text/javascript></script>
<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>

09_9781118539538-ch04.indd 58

1/18/13 1:31 PM

59

Chapter 4: Piecing Together the Application Jigsaw

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.

Putting the Pieces Together


In the previous section, we identify the role of each piece of
the Tizen application jigsaw. In this section, we explain how
you can slot together this mix of your own JavaScript code,
third-party JavaScript libraries, and services provided by
websites and even other applications to create your own
Tizen web app.
We introduce two sample apps to demonstrate what you
can do with Tizen. The first is one of the simplest possible
web apps, while the other is a more complex example. These
examples should give you a good idea of how different types
of Tizen applications are put together so that youre ready to
create your own.

Example 1: A 5-minute
application
The minimum requirement for a Tizen web application is
a package that contains a start file and a configuration file.
These are the only mandatory parts of an application. In this
example, we show you how to quickly create a simple webapplication 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.

Creating the application project


Create an application using the Basic Template as described
in Chapter 3. Because this template contains more parts than
you actually need, you can delete the css, js, and images
folders in the project from the Project Explorer panel.

09_9781118539538-ch04.indd 59

1/18/13 1:31 PM

60

Part II: Getting Practical

Editing the icon file


Although its not a mandatory element, you should create an
icon file with an image or logo representing your application
so that it can be displayed in the menu.
The size and format of this icon depends on the platform
youre developing for.
Replace the default icon.png file in your project with the
new icon.

Editing the configuration document


Open the Configuration Editor and modify the default
config.xml file.
Add the application identifier, name, version, and any other
information you want to include. On the Access tab, add any
relevant network resource URLs for ensuring that your application has access to the website.
When complete, your config.xml should look similar to the
one shown in Listing 4-3.

Listing 4-3 config.xml


<?xml version=1.0 encoding=UTF-8?>
<widget xmlns=http://www.w3.org/ns/widgets
xmlns:tizen=http://tizen.org/ns/widgets
id=http://yourdomain/My-App version=1.0
viewmodes=fullscreen>
<icon src=icon.png/>
<content src=index.html/>
<name>My-App</name>
<description>Hosted web application example</description>
<access origin=http://m.foodnetwork.com
subdomains=true/>
<access origin=http://admarvel.s3.amazonaws.com
subdomains=true/>
<tizen:application id=NylyS9tSdz required_version=1.0/>
</widget>

09_9781118539538-ch04.indd 60

1/18/13 1:31 PM

Chapter 4: Piecing Together the Application Jigsaw

61

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.

Editing the start file


Open the index.html and replace the content with the code
shown in Listing 4-4, substituting the URL for your required
website in the script to set the window.location.

Listing 4-4 index.html


<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<meta name=viewport content=width=device-width,
initialscale=1.0, maximum-scale=1.0>
<meta name=description content=5-minute application/>
<title></title>
<script type=text/javascript>
window.location=http://m.foodnetwork.com;
</script>
</head>
<body></body>
</html>

Running the application


After you make these changes, you can build the application
and run it on your device, the Emulator (see Figure 4-8), or
the Simulator. For instructions on running the application, see
Chapter 5.

09_9781118539538-ch04.indd 61

1/18/13 1:31 PM

62

Part II: Getting Practical

Figure 4-8: Simple app running in the Emulator.

If you havent set the network URL(s) correctly in the


config.xml file, the application wont be able to display the
web page, and the system will launch the devices browser
and display it there instead.

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.

09_9781118539538-ch04.indd 62

1/18/13 1:31 PM

Chapter 4: Piecing Together the Application Jigsaw

63

First, you need to build and run the Systeminfo app from
the Tizen SDK. You can find detailed instructions in the
Chapter 3.
If you already know your way around, just choose FileNew
Tizen Web Project from the menu. Then choose Systeminfo
from the list of samples and build and run the app in the
Simulator or Emulator. The opening screen is shown in
Figure 4-9.
This sample application uses the Tizen Web UI Framework
and demonstrates how to use the System Info Tizen APIs. Its
a good starting point to understand how to include JavaScript
and CSS functionality in a web application and also to see how
to use the Tizen APIs.

Figure 4-9: Systeminfo sample application.

09_9781118539538-ch04.indd 63

1/18/13 1:31 PM

64

Part II: Getting Practical

Using the Tizen APIs


Because this application is using Tizen APIs to get information
from the device, the following features are registered in the
config.xml file:
<feature name=http://tizen.org/api/systeminfo
required=true/>
<feature name=http://tizen.org/api/tizen required=true/>

When these features are registered, the application can immediately access the functionality provided by the Tizen and
SystemInfo objects. So for example, to retrieve the current
battery level on the device, the following code is used:
tizen.systeminfo.getPropertyValue(Power, onPowerSucess,
onError);

The getPropertyValue() method is an asynchronous


method, which returns immediately. The platform attempts to
retrieve the battery level and either returns the value in the
onPowerSuccess() callback function, or an error is returned
in the onError() callback function. Many of the device APIs
provided in the Tizen platform use this common technique.

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>
<script src=tizen-web-ui-fw/latest/js/tizen-webui-fw-libs.
js></script>

09_9781118539538-ch04.indd 64

1/18/13 1:31 PM

Chapter 4: Piecing Together the Application Jigsaw

65

<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>

This index.html file is a little more complicated than the


one in Example 1 because it also contains some elements in
the document body. The application contains two pages: one
for the list of System Info items and the other for displaying
the data.
The first page, with the id main, contains text in the header
area, a list element in the content area, and control bar element in the footer area:
<div data-role=page id=main>
<div data-role=header dataposition=fixed>
<h1>System Information</h1>
</div>
<div data-role=content>
<ul data-role=listview>
<li id=storageinfo>Storage</li>
<li id=powerinfo>Power</li>
<li id=cpu-info>CPU</li>
<li id=displayinfo>Display</li>
<li id=deviceinfo>Device</li>
<li id=networkinfo>Network</li>
<li id=wifiinfo>Wifi</li>
<li id=cellularinfo>Cellular network</li>
<li id=sim-info>SIM</li>
</ul>
</div>

09_9781118539538-ch04.indd 65

1/18/13 1:31 PM

66

Part II: Getting Practical


<div data-role=footer dataposition=fixed>
<div data-role=controlbar datastyle=toolbar>
<ul>
<li><a id=battery>Battery level watching</
a></li>
</ul>
</div>
</div>
</div>

The second page, with the id info, contains text in the


header area and a list element in the content area:
<div data-role=page id=info>
<div data-role=header dataposition=fixed>
<h1 id=info-title></h1>
</div>
<div data-role=content>
<ul data-role=listview id=info-list>
</ul>
</div>
</div>

In Figure 4-10, although we dont define a footer area on the


info page, a footer area actually appears. This footer area
appears because unless otherwise specified for example, by
disabling the data-footer-exist feature the Tizen Web
UI Framework automatically adds a footer area with a back
button to every page.

Figuring out what is in main.js


JavaScript code is event driven, triggered by a user action or
an external event, so JavaScript files mainly contain a collection of related functions. Any variables that are defined in a
JavaScript file will get initialised when the JavaScript file is
loaded from the index.html file.

09_9781118539538-ch04.indd 66

1/18/13 1:31 PM

Chapter 4: Piecing Together the Application Jigsaw

67

Figure 4-10: Systeminfo Display view.

If your application needs to perform any initialisation actions


on startup, you can do this when the page is loaded. Because
this example uses the Tizen Web UI Framework, which
is based on jQueryMobile, initialisation occurs when the
pageinit event is fired. So, for example, to handle the back
button being pressed, you add the following code in your
main.js file:
$(document).delegate(#main, pageinit, function() {
$(#main .ui-btn-back).bind(vclick, function() {
tizen.application.exit();
return false;
});
});

09_9781118539538-ch04.indd 67

1/18/13 1:31 PM

68

Part II: Getting Practical


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, function() {
getSystemProperty(Display, onDisplaySuccess);
return false;
});

The remainder of the main.js file contains the functions for


retrieving system information and formatting it for display on
the page. These functions are all invoked by the actions that
were bound to the user events during initialisation. This is
how the appropriate piece of system information is displayed
when the user clicks an item in the list.

Defining style attributes in style.css


In a Tizen Web UI Framework application, the style attributes
are defined in theme files for example, in the tizen-webui-fw-theme.css file. If you want to override any of these
style or layout attributes or add any custom ones, you can do
so in the style.css file.
For example, in this application, the following colour attribute
is set for the list label element:
li>label {
color:#646464;
}

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.

09_9781118539538-ch04.indd 68

1/18/13 1:31 PM

69

Chapter 4: Piecing Together the Application Jigsaw

Looking at other options


Performing initialisation when handling the pageinit event is just
one way to write your initialisation
code. You can also take several other
approaches. If youre using jQuery,
then you usually perform your initialisation when the document-ready
event is triggered, which is when all
the HTML elements in the page have
finished loading.
Alternatively, you may decide to do
your initialisation when the standard
window onload event is triggered.
The drawback of the onload event

09_9781118539538-ch04.indd 69

is that its generated only when


all the content of a page, including images, has loaded. This situation may be a problem if your page
contains images and other content
stored on remote servers, which may
take a while to load.
Ultimately, you should choose
whichever method is suitable for
your application, based on the application type, the quantity of content
that it displays, and the type of initialisation actions you need to perform.

1/18/13 1:31 PM

70

Part II: Getting Practical

09_9781118539538-ch04.indd 70

1/18/13 1:31 PM

Chapter 5

Testing and Debugging


In This Chapter
Testing your app on the Simulator, Emulator, and a device
Debugging your application

n an ideal world, your application will emerge fully formed,


free from bugs and working smoothly on all released
devices some of which may not have even been thought of
yet. But because you probably dont live in an ideal world, its
vital to test your app at all stages of the development process.
From adding the first few elements of functionality and user
interface ideas right through to the final finishing touches
before release, you need to ensure that your app is tested on
as many devices and in as many situations as possible.
The Tizen SDK includes a set of tools to help you with testing
and debugging throughout your development process. The
Simulator and Emulator let you test your application before
you run it on a device, while the Remote Web Inspector helps
you track down the bugs that creep into even the most carefully written project.
In this chapter, we give you a tour of these tools and explain
how you can use them to make sure that your app is a well
prepared as possible when you, as its proud parent, send it
out into the wide world.
This chapter refers to the tools included with the 2.0 Magnolia
release of the Tizen SDK.

10_9781118539538-ch05.indd 71

1/18/13 1:31 PM

72

Part II: Getting Practical

Testing Your App


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.0 release, the
Bluetooth APIs arent supported. In addition, the implementation of other APIs may be incomplete.

Running in the Simulator


To run your application in the Simulator, right-click your
project in the Project Explorer window and choose Run As
Tizen Web Simulator Application or click the Run icon at the
top of the IDE window and choose Simulator from the Run As
dialog box, shown in Figure 5-1.

Figure 5-1: Run As dialog box.

10_9781118539538-ch05.indd 72

1/18/13 1:31 PM

Chapter 5: Testing and Debugging

73

Figure 5-2 shows the Simulator running in a Google Chrome


browser window.
The Simulator lets you control device settings so that the
simulated environment is closer to the one youre developing for. You can also inject events, such as incoming calls,
location information, and sensor values, to check that your
app responds to these events correctly. The Tizen Emulators
Event Injector is even more powerful; we discuss it in more
detail in the Using the Event Injector section, later in this
chapter.
Press F12 to launch the Web Inspector to debug your code
and view console log messages.

Figure 5-2: The Simulator.

Testing with the Emulator


The Simulator is best used for perfecting the look and feel of
your app and testing functionality that isnt Tizen specific.
For testing device specific functions, youll want to turn to the
Emulator.

10_9781118539538-ch05.indd 73

1/18/13 1:31 PM

74

Part II: Getting Practical


The Emulator in the Tizen SDK is based on the open source
QEMU project. You can think of the Emulator as a strict implementation of a device specification, matching the device much
more closely than the Simulator. It emulates the entire platform, including built-in applications, user settings, and access
to the file system, including movies and images, just like a real
device.
You can also control the screen size and pixel density of
the Emulator image, inject events into your application, and
create multiple Emulator images, all of which help ensure
your app is running smoothly before you run it on a real
device.
Of course, you still encounter differences when testing on the
Emulator versus a device for example, Bluetooth and Wi-Fi
arent supported in the current version. However, if you dont
have access to a device, the Emulator is the next best thing.
In version 2.0 of the Tizen SDK, the Emulator supports only
images that use the x86 architecture, but later versions will
support ARM.
You can enhance the performance of x86 Emulator images on
the host machine using hardware virtualisation support built
into Intel processors that support Virtualization Technology
(VT). If youre running on Windows, youll need to install the
HAXM (Intel Hardware Accelerated Executed Manager) software to enable this feature, while on Linux, you need to use
a Kernel Based Virtual Machine (KVM). This feature really
makes a big difference to the performance of the Emulator.
You can find the system requirements and instructions for
installing the Intel HAXM on your Windows machine on the
developer website at https://developer.tizen.org/
downloads/sdk/installing-sdk/hardwareaccelerated-execution-manager.

Using the Emulator Manager to create an image


Before you can launch your application in the Emulator, you
need to use the Emulator Manager to create an Emulator
image. To launch the Emulator Manager, click the Emulator
Manager icon in the Connection Explorer panel. The Emulator
Manager window appears, as shown in Figure 5-3.

10_9781118539538-ch05.indd 74

1/18/13 1:31 PM

Chapter 5: Testing and Debugging

75

You can also launch the Emulator Manager from the command line or from the application menu.

Figure 5-3: The Emulator Manager.

To create a new Emulator image:


1. In the Emulator Manager, click the Create New option
for the version of the platform youre targeting.
The detail panel on the right of the window now
includes a Create button.
2. Click the Create button and give the Emulator a name.
Confirm and Cancel buttons now appear at the bottom
of the window.
You can configure several options for the Emulator,
including the display resolution and density.
If your system supports hardware acceleration
through KVM or HAXM, make sure that the HW
Virtualization option is marked as Supported.
3. Click Confirm.
Your new Emulator appears in the Emulator Manager
list.

Launching an Emulator instance


To launch an Emulator instance, select the required Emulator
image in the Emulator Manager list and click the Launch
button. The Emulator launches. After the Emulator is connected, it appears in the Connection Explorer panel.

10_9781118539538-ch05.indd 75

1/18/13 1:31 PM

76

Part II: Getting Practical


You can configure several options of the running Emulator.
Simply right-click the Emulator and choose items from the
menu shown in Figure 5-4. You can set the device rotation
and the scale, take screenshots, and set the USB keyboard
options. You can also launch an sdb shell command window
by clicking the shell option. For more about the Smart
Development Bridge (SDB), see the section The Smart
Development Bridge, later in this chapter.

Figure 5-4: The Emulator configuration menu.

Using the Connection Explorer


The Connection Explorer is used to view and manage connected devices both Emulator instances and actual devices.
You can also use the Connection Explorer to view and modify
the contents of the device or Emulators file system. Figure 5-5
shows the file system of a connected device.

10_9781118539538-ch05.indd 76

1/18/13 1:31 PM

77

Chapter 5: Testing and Debugging

Figure 5-5: Viewing and modifying the Emulator


file system.

A great feature of the SDK is that it allows you to test your


application on multiple Emulators and devices simultaneously. This ability is really useful when you want to compare your UI design running on multiple different screen
resolutions. When you use this feature, the currently active
device or Emulator instance is highlighted in the Connection
Explorer, as shown in Figure 5-6.

Figure 5-6: The Connection Explorer.

This highlighting is important because it helps you ensure


that youre launching your application or injecting events into
the correct Emulator instance.

10_9781118539538-ch05.indd 77

1/18/13 1:31 PM

78

Part II: Getting Practical

Running your application in the Emulator


To run your application in the Emulator, right-click your project in the Project Explorer window and choose Run AsTizen
Web Application or click the Run icon at the top of the IDE
window and choose web application from the Run As dialog
box, shown in Figure 5-7.

Figure 5-7: The Run As dialog box.

Your application is then copied, installed, and run on the


currently active running Emulator. Figure 5-8 shows the
Systeminfo sample application launched in the Emulator.
While your app is being installed on the Emulator, you can see
the status of the operation in the Progress panel.

10_9781118539538-ch05.indd 78

1/18/13 1:31 PM

79

Chapter 5: Testing and Debugging

Figure 5-8: Application running in the Emulator.

Using the Event Injector


While your app is running in the Emulator, you can use the
Event Injector to inject real device events into the Emulator to
see how your app responds. If you have a location-aware app,
for example, you can test it by injecting a latitude and longitude
value into the Emulator.
In Version 2.0 of the Tizen SDK, the Event Injector can simulate device, location, NFC, sensor, and telephony events.
Figure 5-9 shows the Event Injector window.

10_9781118539538-ch05.indd 79

1/18/13 1:31 PM

80

Part II: Getting Practical

Figure 5-9: Event Injector.

The Event Injector is located in the IDE on the right-hand side


of the default Tizen Web Perspective, as shown in Figure 5-10.
If you dont see the Event Injector, go to the Window menu in
the IDE and choose Show ViewEvent Injector.

Figure 5-10: The Tizen Web Perspective.

10_9781118539538-ch05.indd 80

1/18/13 1:31 PM

81

Chapter 5: Testing and Debugging

The Event Injector is a very powerful testing tool. You can


inject events into the currently active Emulator instance by
selecting various options from the different tabs in the Event
Injector. The device events you can send to the Emulator
include simulating battery and RSSI levels, ear jack and
USB connections, and mounting SD card images. From the
Locations tab, you can choose to enter a manual location
or prelogged GPS data from a log file. You can simulate the
detection of NFC tags, inject values for the accelerometer,
magnetic, proximity, and other sensors, and even simulate
receiving and sending sms messages and calls.

Testing your app on a device


Testing your app using the Simulator and Emulator can only
take you so far. Before your app is finished, you need to test it
on a real Tizen device. The Tizen SDK makes testing your app
on a device relatively easy, and its a very similar process to
testing using the Emulator.
You must set your device date and time to the current date,
or youll be unable to deploy any web applications to it.

Connecting the device


If youre using the Windows version of the SDK, you need to
download and install the Windows USB driver from www.
samsung.com/sec/support/pcApplication/USB.
When the Windows USB driver is installed correctly or youre
using the Linux version of the SDK, you can connect the device
to the computer using a USB cable. The connected device
appears in the Connection Explorer, as shown in Figure 5-11.
To select the device, highlight it in the Connection Explorer.

Running your app on the device


Running your app on the device is just like running on the
Emulator: Right-click your project in the Project Explorer
window and choose Run AsTizen Web Application or click
the Run icon at the top of the IDE window.
Your application is copied, installed, and run on the device.

10_9781118539538-ch05.indd 81

1/18/13 1:31 PM

82

Part II: Getting Practical

Figure 5-11: The Tizen device shown in Connection Explorer.

Tracking Down the Bugs


If you live in an ideal world, you dont even need to read this
section. Your code will perform flawlessly on the Emulator
and device, and you wont need to even launch the debugger.
For those of you that arent so talented, the presence of powerful, easy-to-use development tools is vital when developing
for any platform. Fortunately, Tizen provides a range of
debugging options.
The Tizen SDK includes the Remote Inspector tool, which
allows you to remotely debug and profile your web application running in the Emulator and on the device. The Remote
Inspector is based on the WebKit Web Inspector and has been
enhanced to support remote debugging. You can also debug
applications running on the Simulator, which supports the
standard WebKit Web Inspector.
You can use both the Remote Web Inspector and the Simulator
Web Inspector to debug JavaScript and inspect the Document
Object Model (DOM), CSS, and resources. It also provides
profiling based tools such as stack analysis and storage usage
analysis.
The key bindings of the Web Inspector conflict with the key
bindings of Eclipse, with Eclipse taking precedence. So if you
want to use the Web Inspector shortcut keys, you need to
unmap the Eclipse key bindings. You can find more information by searching for key bindings in the SDK Help.

10_9781118539538-ch05.indd 82

1/18/13 1:31 PM

83

Chapter 5: Testing and Debugging

Debugging in the Simulator


To debug your web application in the Simulator using the
Web Inspector, you first need to launch it using one of the
methods described in the earlier Running in the Simulator
section. Then you can launch the Web Inspector by pressing
the F12 function key (see Figure 5-12).
After you open the Web Inspector, youre ready to debug your
JavaScript as described in the Debugging JavaScript section,
later in this chapter.

Figure 5-12: The Web Inspector.

Debugging in the Emulator


To debug your application in the Emulator with the Remote
Inspector, right-click your project in Project Explorer and
choose Debug AsTizen Web Application or click the Debug
icon at the top of the IDE window.

10_9781118539538-ch05.indd 83

1/18/13 1:31 PM

84

Part II: Getting Practical


Your application is then copied, installed, and launched in the
currently active Emulator, and the Remote Inspector is displayed in the IDE, as shown in Figure 5-13.

Figure 5-13: The Remote Inspector.

To use the Remote Inspector in Windows, you must have


QuickTime player Version 7.7.1 or higher installed.

Debugging on the device


To debug your application on the device, you just perform
the same operations as if youre using the Emulator: Rightclick your project in the Project Explorer window and choose
Debug AsTizen Web Application or click the Debug icon at
the top of the IDE window.
Your application is then copied, installed, and launched on
the device, and the Remote Inspector appears in the IDE.

10_9781118539538-ch05.indd 84

1/18/13 1:31 PM

85

Chapter 5: Testing and Debugging

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.

Figure 5-14: The Remote Inspector sources view.

To set a breakpoint in the JavaScript, right-click the number


next to the line of code you want to add the break point to
and choose the Add Breakpoint from the menu, as shown in
Figure 5-15.
Then perform the operation in the Emulator that will execute
the code where youve added the breakpoint. When the
breakpoint is hit, the code execution pauses (see Figure 5-16),
and you can inspect variables, view the call stack, and step
through the code.

10_9781118539538-ch05.indd 85

1/18/13 1:31 PM

86

Part II: Getting Practical

Figure 5-15: Setting a breakpoint.

Figure 5-16: Hitting a breakpoint.

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.

10_9781118539538-ch05.indd 86

1/18/13 1:31 PM

87

Chapter 5: Testing and Debugging

Using the Smart


Development Bridge
The SDK includes a device management tool called Smart
Development Bridge (SDB). You can use this command line
tool to manage multiple device connections and provide basic
commands useful for application development.
You can use SDB with either the Emulator or a Tizen device.
To use SDB with a Tizen device, you must set the device to SDB
mode. You can set this mode from the device by choosing
SettingsMore System SettingsDeveloper Options from the
menu and enabling the USB Debugging mode
To use SDB commands to communicate with your device or
Emulator instances, you need to open a terminal window on
your computer and either navigate to the $INSTALL_LOC/
tools folder or add this directory to your $PATH environment variable.

Using SDB commands


Table 5-1 shows a list of SDB commands that you can use to
interact with a device or Emulator instance.

Table 5-1

SDB Commands

Command

Description

sdb push <local> <remote>

Copy file/dir to device

sdb pull <remote> [<local>]

Copy file/dir from device

sdb shell

Run remote shell interactively

sdb shell <command>

Run remote shell command

sdb dlog [option] [<filter-spec>]

View device log

sdb forward <local> <remote>

Forward socket connections, such


as sdb forward tcp:26102 tcp:9999

sdb help

Show the Help message

sdb version

Show version number

sdb start-server

Start the server

sdb kill-server

Stop the server if its running


(continued)

10_9781118539538-ch05.indd 87

1/18/13 1:31 PM

88

Part II: Getting Practical

Table 5-1 (continued)


Command

Description

sdb get-state

Print the target device connection status

sdb get-serialno

Print <serial-number>

sdb status-window

Continuously print device status


for a specified device

In the Emulator, you can also open an SDB shell from the
Emulator configuration menu (refer to Figure 5-4).

Discovering the connected devices


You can find out what devices or Emulator instances are connected using this command:
sdb devices

This command returns a list of the devices attached. This


list is the same as the list of devices displayed in the IDEs
Connection Explorer (refer to Figure 5-11).
If you have more than one device or Emulator instance connected, you need to specify which instance to direct the SDB
command to:
sdb s emulator-26100 shell

Table 5-2 shows the options that you can use to direct the
commands to the required device or Emulator instance.

Table 5-2

SDB Options

Option

Description

-d

Directs the command to the only connected


USB device; returns an error if more than one
USB device is present

-e

Directs the command to the only running


Emulator; returns an error if more than one
Emulator is present

-s <serial number> Directs the command to the USB device or


Emulator with the given serial number

10_9781118539538-ch05.indd 88

1/18/13 1:31 PM

Chapter 6

Porting Your Web


App to Tizen
In This Chapter
Getting a web app primer
Solving common porting problems

s any mobile developer knows, the write-once, runanywhere 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.

11_9781118539538-ch06.indd 89

1/18/13 1:31 PM

90

Part II: Getting Practical

Everything You Wanted to Know


about Web Apps (But Were
Afraid to Ask)
With the improvement in the performance and capability of
HTML5, web applications are booming on mobile. Theyre
easy to install and maintain, and they allow developers to
create platform independent apps. On one hand, the popularity of mobile web applications brings a lot of focus and interest. On the other, the landscape and ecosystem are becoming
very crowded. (Figure 6-1 shows you just how crowded.)
Before you jump onto the bandwagon, its worth considering
all the aspects of mobile web app landscape.

Figure 6-1: The web app landscape.

Web apps on different platforms


Tizen isnt the first platform to provide an environment for
web apps, and it wont be the last. Many platforms support
web apps to some extent, including Blackberry OS, iOS,
Android, Windows Phone, Firefox OS (formerly Boot2Gecko),
and WebOS. Each of these platforms takes a different
approach to web app support.

11_9781118539538-ch06.indd 90

1/18/13 1:31 PM

91

Chapter 6: Porting Your Web App to Tizen

The origins of web apps


The web application (or web app)
concept was first introduced in the
Java world as a collection of servlets, HTML pages, classes, and other
resources that can be bundled and
run on multiple containers from
multiple vendors. This is defined in
the Java Servlet Specification v2.2.
When the XMLHttpRequest (XHR)
and asynchronous web technologies,

such as Asynchronous JavaScript


and XML (AJAX), became popular,
a web application was redefined as
a client application using the web
browser as a runtime (sometime
referring to as a thin client) to access
the information from web server
or local storage. The early popular
web applications included webmail,
online stores, and wikis.

For example, on iOS and Android, the primary development


environment is native applications, and web apps are very
much second-class citizens by comparison. Device access for
these web apps is limited to the features provided by the W3C
device APIs.
On Tizen, by contrast, the primary development environment
is HTML5. Web apps work just like normal apps. Using W3C
device APIs and extended Tizen APIs, you can do pretty much
everything you need to do from within a web app.

Tools and frameworks


One big advantage of creating apps using web technologies
is the huge range of existing tools available. You can use
frameworks to build your UI and make it suitable for mobile
devices. These frameworks include jQuery Mobile and Zepto.
js, which contain utility functions to make your job easier.
Some UI frameworks, such as SenchaTouch, even make your
web app look exactly a native app on certain platforms.
You can also use JavaScript libraries to add particular functionality for example, Box2DJS, a physics engine used in a
lot of games, and RGraph, which you can use to create pie
charts, bar charts, and other good-looking graphs. Another

11_9781118539538-ch06.indd 91

1/18/13 1:31 PM

92

Part II: Getting Practical


useful JavaScript library is Modernizr, which detects whether
particular HTML5 and CSS3 features are supported by your
browser.
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 Wholesale Application Community (WAC), which
is now integrated into the GSM Association (GSMA), publish
requirements and APIs for web apps.
WAC defines operator APIs and includes device APIs from the
Open Mobile Terminal Platform (OMTP) BONDI project and
Joint Innovation Lab (JIL). The goal of WAC is to allow developers to create platform independent apps that include features such as the WAC Payment API with billing features that
work for all network operators.
Some platforms extend the W3C device APIs by defining their
own proprietary device APIs. However, using these APIs makes
your web app less portable, so you gain features at the expense
of compatibility. Its the web app developers dilemma.

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.

11_9781118539538-ch06.indd 92

1/18/13 1:31 PM

Chapter 6: Porting Your Web App to Tizen

93

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.

Porting Problems Solved


Creating a web app that provides a consistent user experience and performs well across all platforms is still a challenge
for developers. The reasons are varied, from different mobile
web browsers, web engines, and varying implementations
of WebKit and W3C standards to device-specific differences,
such as screen size and ratio.
In this section, you find solutions to some of the most
common porting problems and discover how to make your
web app work well on Tizen.

Handling different
package formats
Table 6-1 shows the packaging formats used by different platforms. To port your web app from one of these platforms to
Tizen, you need to package your files as in the standard W3C
web widget format, a .wgt file.

11_9781118539538-ch06.indd 93

1/18/13 1:31 PM

11_9781118539538-ch06.indd 94

(installable bundle)

myscript.js *

* This file/folder is optional

.crx

.xpi

options.xul*

main.html

Format

install.rdf*

icon.png

/img folder *

manifest.webapp

manifest.json

Content

.zip

splash
screen.png

/img folder*

/css folder

/js folder

default.html

package.appx
manifest

Mozilla Marketplace Windows Phone

Chrome Store

icon.png*

icon.png

.ipk

sources.json

/img folder

/css folder

/js folder

.wgt

/img folder*

/css folder*

/js folder*

index.html

config.xml

appinfo.json

index.html

Tizen

webOS

Web App Package Formats

Stores

Table 6-1

94
Part II: Getting Practical

1/18/13 1:31 PM

Chapter 6: Porting Your Web App to Tizen

95

.xpi stands for Mozilla Cross-platform Installer. .crx stands


for Google Chrome Extension.
Web apps come in three different styles:
A hosted web app hosts its content on a web server
and is accessed using a browser. Its easy to maintain
and doesnt need anything installed on the device, but it
requires a network connection to retrieve its content.
A packaged web app, such as a Tizen web app, is
installed on the device, works just like a native app, and
can work offline without a network connection. Many of
these apps also access content from remote web servers,
which, of course, requires a network connection.
A hybrid app is built using the same web technologies as
hosted and packaged apps, but wrapped up in a native
app shell from within which your web code is run. The
iOS App Store and Google Play only accept native apps,
so to sell your app in these stores, you must build it as a
hybrid app.

Making your layout flexible


If you use hard-coded values for the layout design in your CSS
file, your app will probably not display correctly when running on a device with a different screen resolution or ratio
(16:9 compared to 4:3, for example).
The solution to this layout problem is to use percentage
values (fluid layout) or em values (elastic layout) for the
layout or to adjust the viewport using the media queries provided by CSS3.
Figure 6-2 shows an example of a web page with a fixed layout.
The elements inside the container have a fixed width, and the
layout wont be adjusted when the app is run on a device with
a different screen resolution or ratio.

11_9781118539538-ch06.indd 95

1/18/13 1:31 PM

96

Part II: Getting Practical

Figure 6-2: Fixed layout design.

If you run the original Aura sample on a device with greater


horizontal and vertical resolution, the layout wont use the
full screen, and the results will look something like Figure 6-3.
The following CSS code is taken from the main.css file of an
open source application called Aura:
.stage {
width: 1024px;
height: 600px;
position: relative;
overflow: hidden;
-webkit-transform: translateZ(0);
}

You can download the original Aura source code from


https://github.com/blackberry/WebWorks-Samples/
tree/master/Aura.
The preceding code was initially designed for the Blackberry
PlayBook, which has a screen resolution of 1024x600. If you
run the same application on the Tizen reference device, which
has a higher resolution of 1280x720, the background image
occupies only part of the screen, as shown in Figure 6-3. To
solve this problem, you can use the percentage values for
the DOM elements, and the fluid layout example is shown in
Figure 6-4.

11_9781118539538-ch06.indd 96

1/18/13 1:31 PM

Chapter 6: Porting Your Web App to Tizen

97

Figure 6-3: Aura on Tizen.

Figure 6-4: Fluid layout design.

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);
}

11_9781118539538-ch06.indd 97

1/18/13 1:31 PM

98

Part II: Getting Practical


The principle of a fluid layout is to use percentage values to
accommodate a change in screen resolution. Because the
percentage value is a relative value, it refers to the size of its
parent element. In Figure 6-4, you can see that the width of
each element is specified as a percentage of the width of the
containing block.
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:
@media screen and (max-width: 1024px){
.stage {
width: 1024px;
height: 600px;
position: relative;
overflow: hidden;
-webkit-transform: translateZ(0);
}
}
@media screen and (max-width: 1280px){
.stage {
width: 100%;
position: relative;
overflow: hidden;
-webkit-transform: translateZ(0);
}
}

Fixing inconsistent behavior


One common reason that you may have problems when porting your web app to Tizen is the inconsistent behavior of
HTML5 device APIs.

11_9781118539538-ch06.indd 98

1/18/13 1:31 PM

99

Chapter 6: Porting Your Web App to Tizen

The WebKit comparison table created by Peter-Paul Koch


(available on his blog at www.quirksmode.org) illustrates
that none of the current mobile platforms provides an identical implementation of WebKit. Koch ran compatibility tests
on 19 different versions of WebKit running on browsers on
platforms including iOS, Android, Blackberry, and Symbian,
and the inconsistent results he received led him to declare,
There is no WebKit on Mobile. Just because a browser or
web runtime is based on WebKit, you cant rely on consistent
behavior when you port your web app between platforms.
When Aura was first ported from the Blackberry Playbook
to Tizen, the behavior of the accelerometer produced some
interesting results. In Figure 6-5, notice that the clouds are
flying at a 90-degree angle instead of falling straight down.
Either some quite unexpected weather was on the way, or
the code that used the accelerometer was producing some
strange results.
Digging into Auras JavaScript code of rope.js, we found the
explanation: The PlayBook implements the accelerometers x,
y, and z axes differently to Tizen (and most other platforms).
The W3C device orientation API definition states that The
device coordinates frame is defined relative to the screen in
its standard orientation, typically portrait. But the portrait
mode as implemented by the PlayBook corresponds to the
landscape mode of most other devices.
When it comes to the implementation of gravity and acceleration in Aura, on Playbook, it looks like this:
//rope.js
...
var gravity = new Vector(0, 9.8);
var acc = new Vector(0, 0);
...
window.addEventListener(devicemotion, function(event) {
acc.x = event.accelerationIncludingGravity.x;
acc.y = -event.accelerationIncludingGravity.y;
}, true);
...
function draw(){
...
if(acc.x * acc.x + acc.y * acc.y > 9) {
var accAngle = Math.atan2(acc.y, acc.x);
gravity.x = Math.cos(accAngle) * 9.82;

11_9781118539538-ch06.indd 99

1/18/13 1:31 PM

100

Part II: Getting Practical


gravity.y = Math.sin(accAngle) * 9.82;
} else {
gravity.x = 0;
gravity.y = 9.82;
}
...
}

Figure 6-5: Accelerometer performance.

The variable accAngle represents the angle between the


rope and the x axis. To fix the cloud problem on a Tizen reference device that is implemented according to the W3C standards, you have to change one line of the JavaScript to this:
var accAngle = Math.atan2(-acc.x, acc.y);

This is just one real-life example of the pitfalls of porting web


apps between platforms. Other inconsistencies may include the
availability of JavaScript code acceleration, which may affect
performance, or the permissions required to access device APIs.

Porting device specific libraries


Some platforms include particular frameworks and libraries to
make web app development easier, but this can create a porting problem. For example, webOS uses the Enyo framework,
which was previously used only by webOS apps. Now Enyo is
a cross-platform framework that you can use on different platforms, such as Tizen.
In this section, we show you how to port OnyxSampler, which
is the Enyo UI library sample, to Tizen.

11_9781118539538-ch06.indd 100

1/18/13 1:31 PM

Chapter 6: Porting Your Web App to Tizen

101

Figure 6-6 shows OnyxSampler running on Tizen.


To port OnyxSampler to Tizen, follow these steps:
1. Download the Onyx source code and the
OnyxSample source.
You can find the Onyx source code at https://
github.com/enyojs/onyx.
You can download the OnyxSampler source from
https://github.com/enyojs/onyx/tree/2.0beta5/examples/OnyxSampler.
2. Create an enyo folder inside your Tizen project and
copy enyo.js and enyo.css to that folder.
3. Copy index.html from the OnyxSampler source
code and replace the auto-generated index.html
template

Figure 6-6: OnyxSampler on Tizen.

4. Copy the App.js file to js folder in your Tizen


project.
5. Update the JavaScript paths in index.html.

11_9781118539538-ch06.indd 101

1/18/13 1:31 PM

102

Part II: Getting Practical


For example:
<script src=enyo/enyo.js type=text/Javascript>)

6. Run it on the Simulator or device from within the


Tizen IDE.
The advantage of the preceding approach is that it doesnt
require an Internet connection to download the Enyo JavaScript
library and launch the application. The disadvantage is it
increases the memory footprint of your app, and the library
included may not be the most up-to-date one. An alternative
approach is to skip Step 2, and include the URLs of enyo.js and
enyo.css in the index.html header as mentioned in Step 5.
For example:
<link rel=stylesheet href=http://enyojs.com/enyo-2.1/enyo.
css>
<script src=http://enyojs.com/enyo-2.1/enyo.js></script>

This will ensure that you always use the latest version of the
libraries, but of course you will need an Internet connection.

Making your app more portable


Unfortunately, you cant rely on web browsers to implement
HTML5 features in a consistent fashion. To allow for this variation, you need to ensure that your JavaScript code is adaptable.
For example, the following code shows how to implement support for the vibration API in a browser-independent way:
function getVibrationFunc() {
var vibrate = function() {};
if (navigator.vibrate)
vibrate = function(p) { navigator.vibrate(p);};
if (navigator.mozVibrate)
vibrate = function(p) { navigator.mozVibrate(p);};
if (navigator.webkitVibrate)
vibrate = function(p) {navigator.webkitVibrate(p);};
return vibrate;
}

You can also use the mondernizr.js library to detect


whether certain HTML5 and CSS3 features are supported by
your browser. Modernizr makes it easier to write conditional
JavaScript and CSS to handle different situations. You can find
out more from http://modernizr.com.

11_9781118539538-ch06.indd 102

1/23/13 8:32 AM

Part III

Tizen in Detail

12_9781118539538-pp03.indd 103

1/18/13 1:31 PM

In this part . . .

n this part we look at the Tizen device APIs in detail.


You develop code using a mixture of Tizen-specific
features and HTML5 APIs. We focus on what you need to
know to develop a fully-featured web app, together with
hints and tips to make your development easier.
You learn how to use the Tizen UI Framework to build a
great looking user interface and how to make use of
features such as location and sensors. You find out how to
access the devices contacts and calendars, and how to
playback audio and video using a mixture of Tizen-specific
features and the HTML5 APIs.

12_9781118539538-pp03.indd 104

1/18/13 1:31 PM

Chapter 7

Building Your UI
In This Chapter
Introducing jQuery Mobile
Using basic controls
Taking advantage of UI building tools
Creating advanced UIs

f all the ingredients that go to make up that killer app, a


well-designed, attractive and fluid user interface is the
most important. No matter how great your app may be, if the
user interface is cluttered, slow, or difficult to navigate, then
your app will gather virtual dust on the shelves of your favourite app store. Take the time to create a great UI, and your
app will stand out from the crowd. Users will discover its features and will be more likely to recommend your app to their
friends. Your app will be well on its way to bestseller status,
and you can look forward to lying on a beach, being brought
drinks with their own little umbrellas.
Creating the user interface for a touch-based device represents its own set of challenges. Your application needs to be
consistent, but it should also be innovative and stand out
from the crowd. One example is the Flipboard app, which has
been a success on both iOS and Android.
In this chapter, we introduce Tizens web UI Framework and
show you how you can create apps with simple and easy-to-use
UIs. We explain the basic UI elements, how to implement features like search and swiping, and how Tizens support for the
latest CSS features allow you to create a Flipboard-like effects.
This chapter puts you well on the way to creating a great UI.
We leave the rest of killer app to you.

13_9781118539538-ch07.indd 105

1/18/13 1:32 PM

106

Part III: Tizen in Detail

Delving into the Nuts, Bolts,


and jQuery Mobile
Tizens UI Framework is built on jQuery Mobile, an open
source framework that makes use of the features of the jQuery
and jQuery UI open source frameworks. Using jQuery Mobile,
developers can create cross-platform UIs for mobile web
apps. Tizen adds its own features and user interface elements
to give your apps a unique Tizen flavour.
To understand the jQuery Mobile framework, you should know
some of the basic concepts first. So, without further ado, the
following sections examine the important nuts and bolts.

Embedded custom data attributes


In the HTML5 specification, custom data attributes are
intended to be used to store custom data private to a web
page or app. The jQuery Mobile framework makes heavy use
of custom data attributes to embed data into HTML5 markup.
These data attributes are used to initialize and configure UI
elements, as shown in the Building a Contacts UI section,
later in this chapter.

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. We explain the
page elements in more detail in the upcoming Example:
Building a Contacts UI section.

13_9781118539538-ch07.indd 106

1/18/13 1:32 PM

Chapter 7: Building Your UI

107

Figure 7-1: Page structure.

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,
tabhold, swipe, swipeleft, and swiperight.
To assign the event to your UI, you just use the bind method:
$(document).bind(swipeleft, function(event, data){
//your implementation of swipe event
});

While we explain some of the basic concepts of jQuery Mobile,


for much more detail, visit http://jquerymobile.com.
jQuery is also included with and used by Tizen. Its official
website is http://jquery.com.

13_9781118539538-ch07.indd 107

1/18/13 1:32 PM

108

Part III: Tizen in Detail

Exploring the Tizen UI Widgets


The Tizen Web UI Framework is an extension of jQuery and
jQuery Mobile plus other open source components, such as
Globalize and jLayout.
It adapts a lot of common concepts and widgets from the
jQuery Mobile library and adds Tizen-specific UI widgets and
themes to make your Tizen web app look just like a native app.
Table 7-1 shows the widgets available in the Tizen UI
Framework. Some widgets are provided by jQuery Mobile
(marked as JQM), while Tizen-specific widgets are marked
as New.
As you can see, quite a few new widgets are specifically
designed to match the native UI of Tizen, including a controlbar, data time picker, and a multimedia view.

Table 7-1

Widgets in the Tizen UI Framework

Name

From

Description

Checkbox

JQM

Basic check box

Radio Button

JQM

Radio button

Button

JQM

Basic buttons

Searchbar

JQM

Input form for text search

Segment Control

JQM

Set of buttons appearing as a


single button

Selection Info

JQM

Day of the week selector

Slider

JQM

Set values as drag the handle

Progressbar

jQuery UI

Bar showing progress

Lists

JQM

List of items

Virtual List

New

List with dynamic data management

Extendable List

New

List that can be extended

Swipe List

New

List item that can be swiped out

Popup

New

Pop-up window

Context Popup

New

Small pop-up containing a list

Toggle Switch

New

Simple two-state switch

13_9781118539538-ch07.indd 108

1/18/13 1:32 PM

Chapter 7: Building Your UI

109

Name

From

Description

Notification

New

Small pop-up indicating device


events

Image Slider

New

Image collection (gallery)

Page Control

New

Indicator button with page number

Control Bar

New

Grouped button in the header or


footer

Day Selector

New

Grouped button supporting weekday selection

Date Time Picker

New

Date and time picker

Color

New

Color palette and color picker

No Contents

New

Displayed when a list has no items

Handler

New

Touch-friendly scroll bar

Multi Button Entry

New

Button containing a text entry

Multimedia View

New

Video and audio player

Virtual Grid

New

Grid with dynamic data management

Note: These are the UI elements available at the time of writing.

Example: Building a Contacts UI


In this section, you get practical and create a real UI. We use
the native Contacts app from the Tizen development device
as an example and show you how to create a Tizen web app
with the same look and feel. The Contacts app is shown in
Figure 7-2.
The Contacts UI contains a control bar with three tabs, a
search bar, a grouped list, and a toolbar at the bottom. By
selecting the tab, you can switch between contacts, groups,
and favorites.
The toolbar provides access to features such as adding new
contacts, selecting contacts, or viewing contacts with particular criteria. The toolbar changes according to the setting of
the tab at the top of the window.

13_9781118539538-ch07.indd 109

1/18/13 1:32 PM

110

Part III: Tizen in Detail

Figure 7-2: Tizen native Contact app.

You can use the Tizen Web UI Framework to create the same
UI in your web app. Figure 7-3 shows a web version of the
native contacts app.
Implementing the Tizen web user experience is simple. The
top level view widget is a page in jQuery Mobile, consisting of
header, content, and footer. Our Contacts web app uses the
controlbar, searchbar, and swipelist widgets to implement the application functionality.

13_9781118539538-ch07.indd 110

1/18/13 1:32 PM

Chapter 7: Building Your UI

111

Figure 7-3: Web UI Framework app.

The following sections show how to build this UI step by step.

Using the control bar as a tab bar


The control bar is a widget supporting the grouped button
style in the header or footer area. You can use two styles for
the controlbar: tabbar or toolbar, as shown as Figures
7-4 and 7-5.
To use these styles in your app, just create a div with
data-role=controlbar and specify the style as datastyle=tabbar or data-style=toolbar.

Figure 7-4: Controlbar Tab bar style.

Figure 7-5: Controlbar Toolbar style.

13_9781118539538-ch07.indd 111

1/18/13 1:32 PM

112

Part III: Tizen in Detail


Listing 7-1 shows a fully functional example of creating three
tabs in the header. The same pattern applies to the footer as
well.

Listing 7-1 Controlbar Toolbar Style


<div style=height:222px data-role=header
dataposition=fixed>
<div data-role=controlbar id=controlbar1
datastyle=tabbar>
<ul id=tabbar>
<li id=tab-item1 >
<a href=#two data-icon=ctrlbar-contacts
class=ui-btn-active>Contacts</a>
</li>
<li id=tab-item2>
<a data-icon=ctrlbar-groups>Groups</a>
</li>
<li id=tab-item3>
<a data-icon=ctrlbar-favorite>Favorites</a>
</li>
</ul>
</div>
</div>

Adding a search bar


There are two types of search bar you can use in Tizen: one is
defined in the jQuery Mobile library with a type=search,
while the Tizen UI Framework defines its own searchbar with
type=tizen-search. (See Chapter 9 for another
example of using the Tizen search bar.)
You can add a search bar at different places on the page for
example, in the header, footer, or content. Theres no particular place where you should put the search bar, but the effects
are different.
To ensure that the search bar is always visible, place it in a
fixed header or footer where it wont scroll when the page
scrolls.
If you want the search bar to scroll with your content, you can
add it to the list area so that the search bar will scroll when
the list scrolls.

13_9781118539538-ch07.indd 112

1/23/13 8:35 AM

Chapter 7: Building Your UI

113

In our example, we add the search bar to the header:


<div data-role=page id=one data-add-back-btn=footer
data-footer-exit=true>
<div style=height:222px data-role=header
dataposition=fixed>
<!-- controlbar -->
<input class=input-search-bar
type=tizensearchvalue=/>
</div>
</div>

If you have both the control bar and search bar in the header,
as shown in Figure 7-6, you have to add the following code to
your CSS file because the height of the control bar (114px)
isnt automatically calculated by the Tizen web UI Framework:
.input-search-bar {
top: 114px;
}

If you dont make this change to your CSS file, then the search
bar wont appear in the right place. You need to apply the
same CSS styling to the page content as well.

Figure 7-6: Search bar with control bar.

Implementing the Swipe List


A Swipe List is a new UI widget provided by the Tizen Web UI
Framework. It works in the same way as the normal List View
provided by the jQuery Mobile library, but you can also swipe
the list item left or right.
Figure 7-7 shows the effect of swiping the list item cover to
the right. Notice that the two icon widgets appear where the
list item used to be.

13_9781118539538-ch07.indd 113

1/23/13 8:35 AM

114

Part III: Tizen in Detail

Figure 7-7: Swiping the list item cover to the right.

The following code shows how to implement the Swipe List


functionality:
<ul data-role=swipelist>
<li>
<div data-role=button data-inline=true
data-icon=ctrlbarcall></div>
<div data-role=button data-inline=true
data-icon=ctrlbardelete></div>
<div data-role=swipelist-item-cover>Andy Costa</div>
</li>
</ul>

Because the Swipe List is derived from the List View, all
options for the List View are also applicable to the Swipe List.
This includes list items with multi-lines of text, large icons,
toggle buttons, text buttons, circle buttons, thumbnails, or
even more complex ones with fixed with icons and buttons.

Adding the finishing touches


Youll notice that we use some icons in our UI. These icons
are provided by the Tizen Web UI Framework, which helps to
ensure consistency between web apps and the native UI.
Figure 7-8 shows the icons defined by the Tizen Web UI
Framework.
Using these icons in your UI is simple. For example, to use
the check icon, you just need to add data-icon=ctrlbarcall in your div.
<div data-role=button data-inline=true data-icon=ctrlbar-call></div>

13_9781118539538-ch07.indd 114

1/23/13 8:35 AM

Chapter 7: Building Your UI

115

Figure 7-8: Icons defined by the Tizen Web UI Framework.

The UI Builder: Just


Drag and Drop
The UI Builder, introduced in Tizen 2.0, lets you build your
user interface visually. Now you can build your UI by dragging
and dropping rather than manually coding HTML. You can
use the UI Builder to create most of the UI for the contacts
example we show in the preceding section.
To use the UI Builder, you first need to create a new Tizen web
project in the IDE (choose FileNew Tizen Web Project) and
choose Tizen Web UI Builder from the list of templates. Go
through the steps to create the new project, and you see that
a file called page1.page has been created inside your projects page folder. You use this file with UI Builder to create
your UI.

13_9781118539538-ch07.indd 115

1/18/13 1:32 PM

116

Part III: Tizen in Detail

Choosing your widgets


Getting to grips with the UI Builder is easy, especially if youve
used similar tools for desktop or mobile development. Figure
7-9 shows the UI Builder interface, while Figure 7-10 shows the
page folder and page files in the Project Explorer.
The Palette, which is shown on the left of the Page Design
View in Figure 7-9, contains all the widgets and elements that
are available to use in your app. These widgets are grouped
into different categories, such as List Views, Buttons, and
HTML. You drag and drop widgets from the palette to the
Page Design View to construct your UI. (For more detail about
the IDE, see Chapter 4.)

Figure 7-9: Page Design View.

Two tabs appear at the bottom of the Page Design View:


Design: Select the Design tab while youre building the UI.
Preview: Select Preview to see the result as your design
develops.

13_9781118539538-ch07.indd 116

1/18/13 1:32 PM

Chapter 7: Building Your UI

117

Figure 7-10: The UI Builder.

The Outline and Property Views, which are shown on the


right-hand side of Figure 7-10, are used a lot during the UI
design process. The Outline View shows the hierarchy of div
elements within the page. For example, in the Outline View
shown in Figure 7-11, the controlbar is inside the header
div and the controlbar items are under the controlbar
div. This view provides easy access to elements on the page.

Figure 7-11: The Outline View.

13_9781118539538-ch07.indd 117

1/18/13 1:32 PM

118

Part III: Tizen in Detail


After you drag the UI widget to the page, you can adjust its
default properties from the Property View. In the example shown
in the Figure 7-12, we change the text of the controlbar item to
Contacts and set the icon to ctrlbar-contacts.
Note: The version of UI Builder provided in the Tizen 2.0 alpha
SDK is still in development and provides a limited set of widgets. Some widgets, such as the list-divider, are not yet
supported by the UI Builder, and youll need to add your own
HTML and JavaScript code to include these in your app. By
the time you read this book, widget support in the UI Builder
should have been improved.

Figure 7-12: Widget Property View.

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, the
Swipe List item supports the Animationend event, and you
can generate the skeleton JavaScript code to handle this event
from within UI Builder.

13_9781118539538-ch07.indd 118

1/18/13 1:32 PM

Chapter 7: Building Your UI

119

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 swipelist widget supports. Choose Animationend to assign this event to the
swipelist item and click the triangle that appears below
the menu, as shown in Figure 7-13.

Figure 7-13: Adding the Animationend handler to the swipelist.


Clicking the triangle will generate the code to handle this event.

The UI Builder will generate the skeleton code to handle this


event and add it to the JavaScript file page1.js
/**
* @param {Object} event
* @base _page1_page
* @returns {Boolean}
*/
_page1_page.prototype.swipelistitem2_onanimationend =
function(event) {
};

13_9781118539538-ch07.indd 119

1/18/13 1:32 PM

120

Part III: Tizen in Detail

Adding Some Flourish to Your UI


Tizen supports the latest HTML5 CSS3 features, which allow
you to build some slick user interface effects into your apps.
In this section, we show you how to create a UI using the CSS3
3D animation features. While these features arent Tizen specific, they do demonstrate the compatibility and performance
of the Tizen web runtime. (You can find more details about
CSS3 support in Tizen in the W3C API Specifications section of
the SDK Help.)
The Flipboard app is an example of a successful mobile app
with an innovative user interface. Flipboard is an app that
creates your own social news magazine from your Twitter,
Facebook, Google+, and other news feeds. Flipboard makes
use of the flipping gesture as the primary way to navigate
through content. Flipboard is consistent, easy to use, and
fun a lot of the reason that the app was successful.
There is an open source project that provides an experimental
Flipboard layout and user experience. Its primarily designed
for mobile web sites, but thanks to the HTML5 capabilities of
Tizen web apps, its easy to integrate into your own app.
You can download the project source code at
https://github.com/botelho/flipboard-layout

The project provides a plugin for the jQuery library called


jquery.flips.js. This plugin defines several classes for
the page elements:
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.

13_9781118539538-ch07.indd 120

1/18/13 1:32 PM

Chapter 7: Building Your UI

121

A sample HTML page looks like this:


<div id=flip class=container>
<div class=f-page f-cover>
<!-- ... -->
</div>
<div 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-14 and 7-15 show the final code running on the Tizen
development device. The cover page contains the image and
flip text.

Figure 7-14: Cover page f-cover on the Tizen developer device.

13_9781118539538-ch07.indd 121

1/18/13 1:32 PM

122

Part III: Tizen in Detail

Figure 7-15: Flip pages - f-page on the Tizen developer device

The Flipboard type page layout example uses some other


open source elements to provide extra functionality, including
modernizr.js for checking your browser support of
CSS properties
jquery.touchSwipe.js for dragging and swiping the
pages
jquery.history.js for keeping track of the current
state/pages

13_9781118539538-ch07.indd 122

1/18/13 1:32 PM

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

ith GPS now a standard feature on smartphones, app


stores are heaving under the weight of apps taking
advantage of the opportunities offered by location-based
services. There are navigation apps, location-based social
networking services (such as FourSquare, Path, and Google
Latitude), and even apps designed for local search.
Users love location-based services because they provide a
sense of connection with the world around them. You can
discover whats happening at your current location, find
where your friends are, and even be notified of offers at a
nearby store. Location is about far more than finding your
way home.
In this chapter, we introduce some of the location-based
features you can use in your Tizen web apps. We show you
how to display a map based on your current location,
translate an address to a location specified by longitude and
latitude, and display a marker on a map.

14_9781118539538-ch08.indd 123

1/18/13 1:32 PM

124

Part III: Tizen in Detail

Location, Location, Location


The Tizen 2.0 alpha release includes two device APIs for
location-related features: Geocoder and Location Based
Service (LBS). At the time of writing, only the geocoding and
reverse geocoding features are included in the SDK.
The good news is that the lots of third-party solutions make
it easy to add features, such as maps and geocoding, to your
web apps. We show you how to use one such service Google
Maps to display your current location on a map.

Finding Your Way


Map data normally refers to the geographic data and mapping
information that is collected by location service providers,
such as Navteq, Telemap, Tele Atlas, and Open Street Map
(OSM). These companies provide geographic databases and
mapping services to third parties.
Location service providers define APIs, which let you access
services such as mapping, routing, and POIs. Some of these
APIs are highly dependent on the services of a particular
provider, such as Google Maps, OSM, and Navteq. The
OpenLayer and deCarta APIs are more flexible and aggregate
the services of many different providers.
For more information about the location services provided by
OpenLayer and deCarta, visit their websites:
OpenLayer JavaScript APIs:
http://dev.openlayers.org/releases/
OpenLayers-2.12/doc/apidocs/
files/OpenLayers-js.html
deCarta JavaScript APIs:
http://developer.decarta.com/Apis/
JavaScript

14_9781118539538-ch08.indd 124

1/18/13 1:32 PM

Chapter 8: Taking Advantage of Location-Based Services

125

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:
1. Get your current location.
You need to use the W3C geolocation API to retrieve
the longitude and latitude of the devices current
location:
navigator.geolocation.getCurrentPosition(
function(position) {
var mapCentre = position;
console.log('Latitude: + position.coords.
latitude+ Longitude: +
position.coords.longitude);
},
function(error) {
console.err(Failed to get current position);
}
);

2. Create the map options.


After you have your current position from Step 1,
make sure that the map is centred on these co-ordinates.
The Google Maps API lets you specify a set of map
Options for specifying how the map is displayed.
This includes the map centre, zoom level, map type,
and Google Street View options:
var mapOptions = {
center : new google.maps.LatLng
(position.coords.latitude,position.coords.longitude),
zoom : 6, // zoom value from 0 up to 18
mapTypeId : google.maps.MapTypeId.HYBRID,
streetViewControl : false
};

3. Display the map.


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>

14_9781118539538-ch08.indd 125

1/18/13 1:32 PM

126

Part III: Tizen in Detail


Then create the map object in your JavaScript code:
var map = new google.maps.Map(document.
getElementById(map), mapOptions);

Figure 8-1 shows a map displayed in the Tizen Emulator.

Figure 8-1: Displaying a map in the Tizen Emulator using the Google map
APIs.

You need to request an API key in order to use the Google


Maps API. You can find more information here:
https://developers.google.com/maps/documentation/javascript/
tutorial

You also need to include the Map API URL in your Tizen
project config.xml file because its an external resource
that is accessed from your Tizen app. See Chapter 4 for more
details about how to add a URL to the access section of
config.xml.

Finding an Address
Displaying a map given a longitude and latitude is relatively
simple, but sometimes all you have is a human-readable

14_9781118539538-ch08.indd 126

1/18/13 1:32 PM

Chapter 8: Taking Advantage of Location-Based Services

127

address. Converting this address into a longitude and latitude


is known as geocoding, while the process of translating
co-ordinates to a human-readable form is referred to as
reverse geocoding.
In Tizen, geocoding services are provided by the Geocoder
APIs, although you can use the APIs from other service
providers, such as Google, if you choose to.
In this section, we show you how to make use of both the
Tizen and Google geocoding services.

Tizen Geocoder API


To use the Geocoder API in Tizen, you need to add the
following permission to your config.xml file:
<feature name=http://tizen.org/api/geocoder required=true>

With this permission set, when you launch your application, a


Geocoder object is created and stored in the geocoder
property of your apps tizen object. You then use this object
to access geocoding functionality.
For more information about the configuration file, see Chapter 4.
You can retrieve the geocoder provider object by calling
var geocoder = tizen.lbs.geocoder.getDefaultProvider();

Optionally, you can use the following code to return a list of


available providers:
var geocoderList = tizen.lbs.geocoder.getProviders();

and select the one you want to use from the list.
The Tizen Geocoder APIs provide two methods: geocode()
and reverseGeocode().
The geocode() method takes up to four parameters: a
DOMString or address that you want to geocode, callback
functions for success and error handling, and a Geocode
Options object that you use to specify the sorting order and
maximum number of results returned. The last two parameters
are optional.

14_9781118539538-ch08.indd 127

1/18/13 1:32 PM

128

Part III: Tizen in Detail


Heres how you can use the geocode() function to convert
an address to co-ordinates:
var address = {
country: UK,
city: Staines,
street: South Street
};
geocoder.geocode(
address,
function(results){
var position = results[0].coordinates;
},
function(){
console.log(There is a error when geocoding the
givenaddress);
}
);

When you run this code, results will contain an array of


GeocodeResult objects. The GeocodeResult object
contains two properties: a SimpleCoordinates object and
the toGeoJSON() method.

Google Geocoder API


The Google geocoding APIs are used in a very similar way
to the Tizen APIs, although Google does offer a few more
advanced geocoding features.
The Google Maps API provide a geocoder class for geocoding
addresses dynamically from user input using the google.
maps.Geocoder object.
Suppose that you have a text input bar <input
id=address type=textbox> in your HTML code.
Listing 8-1 shows how you would translate the user input into
coordinates.

Listing 8-1 Geocoding an Address to Co-Ordinates


var geocoder;
function codeAddress() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById(address).value;
geocoder.geocode(
{ address: address},

14_9781118539538-ch08.indd 128

1/18/13 1:32 PM

Chapter 8: Taking Advantage of Location-Based Services

129

function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location});
}
else {
alert(Geocode was not successful for the
following reason: + status);
}
}
);
}

As shown in Listing 8-1, the google.maps.Geocoder()


method is used to create a new Geocoder object. The
geocode() method then translates the address that the user
entered, with the results returned via a callback function.
Two objects are returned in the callback function: GeocoderResult and GeocoderStatus. The
GeocodeResult has four properties:
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.

14_9781118539538-ch08.indd 129

1/18/13 1:32 PM

130

Part III: Tizen in Detail


For more information about Google Maps Geocoder API, go to
https://developers.google.com/maps/documentation/javascript/3.
exp/reference#Geocoder

X Marks the Spot


You need to pin the location you searched (or geocoded) with
a marker on the map. Because no Tizen map device API is
available at the time of writing, we use the Google Maps
overlay API to display the marker on the map.
To create the marker in Google Maps API, you need two
objects: the map where the marker will be displayed and the
location for the marker. The following code creates a marker
at the specified co-ordinates on a map you created in the
Displaying a Map section.
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});

The marker appears on the map, as shown in Figure 8-2.

Figure 8-2: Displaying a marker on a map.

14_9781118539538-ch08.indd 130

1/18/13 1:32 PM

Chapter 8: Taking Advantage of Location-Based Services

131

If the map property isnt specified when the marker object is


created, you can use the setMap() method to display the
marker once the map object is available:
marker.setMap(map)

The Tizen Geocoder service uses the Tizen Simple


Coordinates object. To convert these coordinates into the
LatLng object used by the Google APIs, use the following
code:
var location = new google.maps.LatLng(tizenResults[0].
coordinates.latitude, result[0].coordinates.
longitute);

You can then use the LatLng object co-ordinates to display a


marker on a map displayed using the Google APIs.

14_9781118539538-ch08.indd 131

1/18/13 1:32 PM

132

Part III: Tizen in Detail

14_9781118539538-ch08.indd 132

1/18/13 1:32 PM

Chapter 9

Working with Multimedia


In This Chapter
Discovering multimedia content
Capturing audio, images, and video
Playing video and audio
Streaming from the camera and microphone

hile the calendar and contacts of a smartphone hold


the key to organizing our lives, its the multimedia
features that help us relax. We carry the latest movies with
us on long journeys, listen to our favourite songs on our daily
commute, and use the camera to capture pictures of our
friends, with outfits and hairstyles that may come back to
haunt them in years to come. Multimedia features are vital for
any smart device platform.
In Tizen, multimedia support is implemented using a mixture
of device APIs and W3C APIs. Multimedia is a fast moving
area, so much so that some of the information in this chapter
is subject to change. But its also one of the most exciting
areas of web app development.
In this chapter, we explain how to use Tizens multimedia
content features to search for media on your device. We show
you how to play back audio and video files, capture images
using the camera, and push the boundaries of W3C features
by implementing video conferencing type features.
So, hold on to your hats or failing that, make sure that
youre sitting comfortably and enjoy a practical ride through
the latest multimedia possibilities for your Tizen web apps.

15_9781118539538-ch09.indd 133

1/18/13 1:32 PM

134

Part III: Tizen in Detail

Introducing the Multimedia APIs


Note: Some of the features mentioned in this chapter are
based on draft versions of W3C specifications, so they may
change in the future due to the evolving nature of these
specifications.
Table 9-1 shows APIs you need to use to implement various
multimedia features in your Tizen web apps. Some of these
are Tizen-device APIs, and some, like getusermedia, are at a
very experimental stage.

Table 9-1

Multimedia Features

Feature

Recommended API

Multimedia content discovery

Tizen Device API: MediaContent

Capturing audio

Not currently supported

Capturing images

Tizen Device API:


ApplicationService

Capturing video

Tizen Device API:


ApplicationService

Playback of audio files

HTML5 audio element

Playback of video files

HTML5 video element

Streaming video from the


devices camera

W3C API: getUserMedia

If you dont have access to a Tizen device, you can use a


webcam with the Emulator to try out the multimedia functionality described in this chapter. See the SDK Help documentation for more information about how to set up a webcam with
your system.

Discovering Content
The Tizen MediaContent API provides functionality for
searching for multimedia content stored either locally on your
device or an external memory card.

15_9781118539538-ch09.indd 134

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

135

You dont want this sensitive information falling into the


wrong hands, and the Tizen platform restricts app access to
the multimedia content by using permissions. There are
different permission levels, which your app will set depending
on whether you want to just find a media item or modify a
media 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 MediaSource
Manager object is created and stored in the mediacontent
property of your apps tizen object. You then use this
MediaSourceManager to locate multimedia content.

Media source
To use the functionality provided by the MediaContent API,
you must retrieve the media source of the platform using the
following in your code:
var mediaSource = tizen.mediacontent.getLocalMediaSource();

You can think of the MediaSource object as managing a


database of all the multimedia content stored on the device
or memory card. Its the gatekeeper of your devices media
content.
Using this MediaSource object, you can search for media
folders and media items. If the correct permissions are set,
you can also update any media items editable attributes. You
can find details of the available methods and the editable
attributes in the SDK Help documentation.

Media item
A media item is an object that contains all the attributes of
a single piece of multimedia content; it doesnt contain the
multimedia content itself. The MediaItem interface is used to
provide an application access to an items attributes.
In the Tizen platform, the MediaItem interface is extended by
the MediaAudio, MediaImage, and MediaVideo interfaces
with attributes specific to the content type. Table 9-2 lists
these attributes.

15_9781118539538-ch09.indd 135

1/18/13 1:32 PM

136

Part III: Tizen in Detail

Table 9-2

Attributes Supported by
Multimedia Content

Content Type

Attributes

MediaItem

id, type, mimeType, title, itemURI,


thumbnailURIs, releaseDate,
modifiedDate, size, description, and
rating

MediaAudio

album, genres, artists, composers,


lyrics, copyright, bitrate, track
Number, duration, playedTime, and
playCount

MediaImage

geolocation, width, height, and


orientation

MediaVideo

geolocation, album, artists,


duration, width, height, playedTime,
and playCount

Getting permission
Because multimedia 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 multimedia content:
Adding http://tizen.org/api/mediacontent.
read to your permissions gives you access to the
methods in the API for retrieving folders and searching
for content.
Adding http://tizen.org/api/mediacontent.write
to your permissions gives you access to the methods in
the API for updating the attributes of media items.
Adding http://tizen.org/api/mediacontent
allows you access to all the features of the API.

15_9781118539538-ch09.indd 136

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

137

Example: Creating a playlist


In this example, we show you how to create a playlist of
your ten most frequently played audio rock tracks, using
the MediaContent APIs. You need to use the findItems()
method to search through all the multimedia content,
specifying some filters and a sort mode to narrow down the
result to your most played tracks.
Before you start to use the MediaContent APIs, you must
set the correct permission in your applications config.
xml file. In this example, you need to set the http://tizen.
org/api/mediacontent.read permission level to use the
MediaContent APIs and the http://tizen.org/api/
tizen permission level to use filters.
Then you create a couple of attribute filters to narrow down
your search to audio content and tracks classified as rock:
var audioFilter = new tizen.AttributeFilter(type, EXACTLY,
AUDIO);
var genreFilter = new tizen.AttributeFilter(genres,
CONTAINS, rock);

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]);

Because you want to create a list of the most frequently


played tracks, you need to create a sort mode for sorting the
items based on the playCount attribute, presenting the data
in a descending order:
var sortMode = new tizen.SortMode(playCount, DESC);

Before you can use any of the MediaContent APIs, you need
to get the mediasource object from the platform:
var mediaSource = tizen.mediacontent.getLocalMediaSource();

15_9781118539538-ch09.indd 137

1/18/13 1:32 PM

138

Part III: Tizen in Detail


Then you can use the findItems() method to search for the
first ten items that match your search requirements:
mediaSource.findItems(audioFoundCb, errCb, null, searchFilter,
sortMode, 10);

As the findItems() method is asynchronous, you must


define a success callback in which to handle the response:
function audioFoundCb(media) {
// List the audio files found
for (var i=0; i<media.length; i++) {
console.log(Location: + media[i].itemURI
+ Track title: + media[i].title);
}
}

The success callback returns an array of MediaItem objects,


which you can use to create your playlist. You can determine
the location of the audio content on the device from the
itemURI attribute of the MediaItem object.
If you have any errors in the search criteria for example, if
the filters used contain an incorrect parameter the error is
returned in the error callback:
function errCb(err) {
console.log(Error: + err.message);
}

Capturing Images and Video


The Tizen web API doesnt currently provide direct access to
the devices camera. If you want to take pictures and record
video in your app, you need to launch the built-in Camera
application by using the Tizen Application Service feature.
In this section, we introduce the Application Service feature
and show you how you can launch the Camera app to take a
photograph.

15_9781118539538-ch09.indd 138

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

139

Using the Application


Service feature
The Tizen Application Service feature provides a way for you
to use another application to perform a specific function, such
as viewing images or sending emails. The great thing about
this feature is that you just request a service and let the
platform do the rest; you dont need to know which application
will be launched to fulfill your request.
If you do happen to know the application ID of the app you
want to launch, you can also do so explicitly using the Tizen
Application launchService() method. You can find out
more information about how to use this method in this
situation in the SDK Help documentation.
The Application Service feature is provided by the Tizen
Application API. When the appropriate permissions are set,
an Application object is created and stored in the application property of your apps tizen object. You can then use
this object to launch an Application Service.
To use this feature, you need to edit the application permissions
in the config.xml file to include the http://tizen.org/
api/application.launch permission.

ApplicationService object
To launch an Application Service, you first need to create an
Application Service object that describes the type of service
you require.
An Application Service object consists of an operation, URI,
MIME type, and data array:
The operation is a string that defines the action to be
performed by the Application Service.
The URI defines the data on which the operation will be
performed for example, the location of a picture to be
viewed.
The MIME type defines the specific type of the URI for
example, the type of image.

15_9781118539538-ch09.indd 139

1/18/13 1:32 PM

140

Part III: Tizen in Detail


The data array contains any data, in key-value pairs,
needed by the service, such as keywords to search for.
The type of operations available through the Application
Service feature depends on the platform youre developing
for. See the SDK Help documentation for more information
about some of the basic services available.

Launching a service
The application object provides a launchService()
method, which your app calls to launch the service defined in
the Application Service object.
When the system receives the launch request, it processes
the parameters of the Application Service 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 Service object.
The launchService() 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
image chosen by the user in the gallery app, for example.
The reply callback uses the ApplicationServiceData
ArrayReplyCallback interface, which specifies two methods: onsuccess() and onfail(). The onsuccess()
method will contain an array with any data passed back from
the Application Service, such as the URIs of the selected
images.

Example: Taking a photo


This section shows you the Application Service feature in
action. We launch an Application Service to take a photo using
the devices camera.
First ensure that you have the application launch permission
set in your config.xml file, as explained in the earlier Using
the Application Service feature section.

15_9781118539538-ch09.indd 140

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

141

Create an Application Service object with the operation


parameter http://tizen.org/appcontrol/operation/
create_content and the MIME type set to image/jpg:
var service = new tizen.ApplicationService(
http://tizen.org/appcontrol/operation/create_content,
null,
image/jpg);

You dont need to set a URI or any data for this camera
Application Service request.
After you create the Application Service object, your app
requests that this service is launched using the launch
Service() method:
tizen.application.launchService(service, null, successCb, errCb,
serviceReplyCb);

The launchService() method is asynchronous, so you


should define callback functions to get status information and
any data returned from the camera application.
The success callback tells your app that the camera application
has been launched successfully:
function successCb() {
console.log(Camera application launched successfully);
}

If problems occur with the launch request, if the app cant be


found, or if it fails for some other reason, it will be reported to
the error callback:
function errCb(err) {
console.log(Error: + err.message);
}

Once launched from your app, the Camera application opens


in image capture mode, as shown in Figure 9-1.
If you want to launch the camera in video recording mode, you
should set the Application Service objects operation parameter to http://tizen.org/appcontrol/operation/
create_content and the MIME type to video/3gp.

15_9781118539538-ch09.indd 141

1/18/13 1:32 PM

142

Part III: Tizen in Detail

Figure 9-1: The Camera application.

When the user exits the camera application, the appropriate


reply callback is triggered.
The Camera application triggers the success reply callback if
the user has captured a photograph and it has been saved in
the filesystem. The data array returns the location of the photograph. Your application can parse the data and retrieve the
location of the photograph.
If an error occurs or the user has exited the Camera application without taking a photograph, the fail reply callback is
triggered instead.

Playing Audio and Video


Tizen supports the playback of audio and video using the
HTML5 audio and video elements. These elements allow you
to embed audio and video playback functionality within a web
application.
You can find detailed information about the HTML5 audio
and video elements in the W3C specification at http://dev.
w3.org/html5/spec, and you can use the examples in this
chapter to help you get started.
The codecs available on a target device for audio and video
playback are manufacturer dependent, but in the Emulator,
the following codecs are supported:

15_9781118539538-ch09.indd 142

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

143

For audio: AAC, AMR-NB, AMR-WB, MP3, WMA, and


VORBIS.
For video: H.263, H.264, MPEG-1, MPEG-4, and THEORA.

Example: Playing local audio files


In this example, we show you how to play a local audio file in
your web application. Combine this with the playlist example
shown in the earlier Example: Creating a playlist section,
and you have a media player for your favourite tracks.
The code shown here plays an audio file called test.mp3
that is contained in a folder called audio within the application package. You can also play a file from a location such as
/opt/media/Music/test.mp3 in the file system.
To add an HTML5 audio element to your application, put the
following code in your applications start file:
<audio id=audioPlayer src=audio/test.mp3 autoplay></audio>

This code adds an audio element to your application, with the


id audioPlayer, and it plays the test.mp3 file automatically
when the application starts.
If you dont want your audio to play automatically and want to
provide the user with default controls to start and stop, use
the following code:
<audio id=audioPlayer src=audio/test.mp3 controls></audio>

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.
If you want to display any visual elements (such as subtitles),
you can also play your audio file through the HTML5 video
element.

15_9781118539538-ch09.indd 143

1/18/13 1:32 PM

144

Part III: Tizen in Detail


To set the audio file to be played programmatically, simply
add a JavaScript function to set the audio source.
The following code shows you how to assign an audio source
when a button is clicked. You can create the audio element
and the button in your start file
<audio id=audioPlayer></audio>
<div id=playButton>
<button onclick=playAudio();>Play</button>
</div>

and then implement the JavaScript function to assign the


audio source:
function playAudio() {
var audioPlayer = document.
querySelector(#audioPlayer);
audioPlayer.src = audio/test.mp3;
audioPlayer.play();
}

When the user clicks the Play button, the audio file is loaded
into the audio element and starts playing.

Example: Playing local video files


This code example demonstrates how to play a video file
stored locally on the devices file system.
Using a video element in your application is very similar to
using the audio element. The main difference, other than the
content type, is that when using a video element, you need to
set the size of your playback area.
To add an HTML5 video element to your application, add the
following code to your applications start file:
<video id=videoPlayer src=/opt/media/Videos/Helicopter.mp4
width=300 height=150 autoplay></video>

This code adds a video element of size 300x150 to your


application, with the id videoPlayer. It starts playing the
Helicopter.mp4 file automatically when the application is
started.

15_9781118539538-ch09.indd 144

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

145

As with the audio element, you can configure the behaviour


of your video player using attributes such as controls and
autoplay.
Another feature you can use is the poster attribute. You can
use this attribute to set an image to be displayed while no
video is available. You can create the video element, with the
poster attribute and a button, in your start file:
<video id=videoPlayer poster=/opt/media/Images/Helicopter.
jpg width=300 height=150></video>
<div id=playButton>
<button onclick=playVideo();>Play</button>
</div>

Then implement the JavaScript function to assign the video


source and start playback:
function playVideo() {
var videoPlayer = document.
querySelector(#videoPlayer);
videoPlayer.src = /opt/media/Videos/Helicopter.mp4;
videoPlayer.play();
}

Until the user starts playing the video, the Helicopter.jpg


image is displayed in the video player.

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 specification and may work differently in later versions of Tizen.

15_9781118539538-ch09.indd 145

1/18/13 1:32 PM

146

Part III: Tizen in Detail

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.
Note: The user interface for granting user permission to
access the video and audio streams is still being refined at the
time of writing (the 2.0 alpha version of the Tizen SDK).
The local media stream object generated by the webkit
GetUserMedia API can be saved to a file, displayed in a video
element, or transmitted to a remote peer. In this section, we
focus on how to display the local media stream in a video
element.
For more information about media streams and how you can
use them in your web application, see the W3C WebRTC
specification at www.w3.org/TR/webrtc.
In order to display the local media stream in a video element
the stream needs to be converted into a format that is
compatible with the video element. The video element
requires the input media resource for display to be in the
format of a URL.
The WebRTC specification defines a URL interface which
provides a createObjectURL() method that you can use
to create a Blob URL from a media stream object. As with the
getUserMedia API, the WebKit project has implemented its
own version of this specification and provides a webkitURL
interface containing a createObjectURL() method.
This createObjectURL() method takes the media stream
object generated by the webkitGetUserMedia API and
creates a URL that is suitable as an input for the video
elements source attribute.

15_9781118539538-ch09.indd 146

1/18/13 1:32 PM

Chapter 9: Working with Multimedia

147

Example: Streaming video from


your devices camera
In this example, we show you how to stream video from
your devices camera to a video element displayed in your
application. You can use this feature in a video conferencing
app so that the user can see and hear her own video feed as
well as the remote one.
First, add a video element to your start file:
<video id=videoPlayer autoplay width=300 height=150></
video>

When using getUserMedia with a video element, you must


create your video element with the autoplay attribute;
without this attribute, you see only the first frame of the video
stream.
Add the webkitGetUserMedia method call to your
JavaScript function, setting the media stream options to both
audio and video:
navigator.webkitGetUserMedia({video:true, audio:true},
playStream, errCb);

In your success callback, you need to set the video elements


source attribute to the stream from the video camera. You
can set this attribute using the createObjectURL() method,
which outputs a Blob URL for the media stream in a format
compatible with the video element:
function playStream(stream) {
var videoPlayer = document.querySelector(#videoPlayer);
videoPlayer.src = window.webkitURL.createObjectURL(stream);
localMediaStream = stream;
}

The video and audio from the devices camera is now


streamed live in the video element.

15_9781118539538-ch09.indd 147

1/18/13 1:32 PM

148

Part III: Tizen in Detail


If you store a reference to the local media stream, you can use
it to stop the stream from the camera:
localMediaStream.stop();

The optional error callback is for the scenario when access to


the camera is refused:
function errCb(err) {
console.log(Error: + err.message);
}

15_9781118539538-ch09.indd 148

1/18/13 1:32 PM

Chapter 10

Using Hardware in Tizen


In This Chapter
Discovering what you need to know about NFC
Understanding device orientation and motion
Working with the Vibration API

he smart device in your pocket or car, TV, or tablet


has become a navigation unit, a games console, a high
quality camera, and now, thanks to the rising popularity of
Near Field Communication (NFC) technology, an electronic
wallet. Advancements in hardware, such as sensors, have
transformed mobile devices. From the first phone equipped
with an accelerometer, the N95, to todays devices packed
with hardware such as a digital compass, ambient light
sensor, proximity sensor and NFC, the hardware in a smart
device has helped to make it a key part of our work and play.
Sensors are what help you interact with smart devices,
collecting information about the device and the surrounding
environment. The accelerometer sensor monitors the
orientation and movement of the phone, the proximity sensor
detects the distance between phone and other objects, the
ambient light sensor detects the level of environmental light,
and the magnetic sensor reports the direction of device.
Then there is NFC, a technology for short range wireless
communication, which is exploding in popularity and is well
supported by the Tizen device APIs. This chapter shows how
to use NFC in Tizen and also explains how Tizen supports
standard W3C sensor APIs.
Not everything we talk about in this chapter is a sensor. We
also explain the Vibration API, which provides access to the
devices vibration hardware.

16_9781118539538-ch10.indd 149

1/18/13 1:32 PM

150

Part III: Tizen in Detail

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.

16_9781118539538-ch10.indd 150

1/18/13 1:32 PM

Chapter 10: Using Hardware in Tizen

151

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.

Figure 10-1: Components used in the different uses of NFC.

16_9781118539538-ch10.indd 151

1/18/13 1:32 PM

152

Part III: Tizen in Detail

NFC the low level details


Figure 10-1 shows the components
and protocols used in the different
NFC use cases. The components are
organised into layers:
The radio frequency (RF) layer
is based on two International
Standards: ISO 18092 and ISO
14443. ISO 18092 defines the
interface and protocol for NFC.
ISO 14443 defines the proximity
identification cards or objects
that are tags.

is the message encapsulation format uses to exchange


information, and Record Type
Definition (RTD) defines the
detail of a NDEF message. It
gives the guidelines for reserved
well-known types and third-party
extension types. The Logic Link
Control Protocol (LLCP) defines
the format of bi-direction communication in peer-to-peer
mode. Its based on network protocols such as TCP/IP and OBEX.

In the data link layer, the NFC


Data Exchange Format (NDEF)

Using NFC in your Tizen Apps


W3C doesnt define a standard NFC JavaScript API, so most of
the existing NFC APIs are platform specific. Java APIs exist for
Android and Blackberry devices, and to that list, we can now
add the JavaScript API provided by Tizen.
The Tizen NFC APIs support two modes: read/write and peerto-peer. The card emulation mode requires additional security
and isnt available on Tizen at the moment.
To use NFC features in your app, the first thing you need to do
is add the required permissions to the config.xml file. For
example, if you use the tag feature, add
<feature name=http://tizen.org/api/nfc required=true/>

and
<feature name=http://tizen.org/api/nfc.tag" required="true"/>

to config.xml.

16_9781118539538-ch10.indd 152

1/18/13 1:32 PM

Chapter 10: Using Hardware in Tizen

153

If the required permissions are set, an NFCManager object is


created and stored in your apps tizen object. You use
this object, stored in tizen.nfc, to access the Tizen NFC
functionality.

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();

This code returns the default NFC adaptor on the device.


Because there is no error callback for this method, you can
also check the error message by using a try and catch
block:
try { nfcAdapter = tizen.nfc.getDefaultAdapter();
}
catch(error){
console.log(error.name + : + error.message);
}

Next you need to turn the NFC adapter on by calling


setPowered(). This function takes three parameters: a
Boolean value indicating on/off, a callback function for
successful completion and an error handling callback.
nfcAdapter.setPowered(
true,
function(){
//SuccessCallback
},
function(){
//ErrorCallback
//e.g. ServiceNotAvailableError: NFC service is busy
}
);

Setting up the listeners


After you successfully turn on the adapter, you need to set the
appropriate listeners to communicate with other devices. A
tag listener allows the device to detect attaching and detaching
of NFC tags, while a peer listener allows the device to detect
another available peer when using peer-to-peer mode.

16_9781118539538-ch10.indd 153

1/18/13 1:32 PM

154

Part III: Tizen in Detail


To set the tag listener, you need to set up at least one
NFCTagDectectCallback function to handle tag events:
onattach and ondetach. There are two optional parameters:
an error handling callback function and a tag filter array. If
the tag filter isnt provided, the listener is set to detect all tag
types.
nfcAdapter.setTagListener(
function(){
//handle the onattach and ondetach events
},
function(){
//handle errors
}
);

To set the peer listener, you need only one


NFCPeerDetectCallback function and an optional error
handling callback function.
nfcAdapter.setPeerListener(
function(){
//handle onattach or ondetach events
},
function(){
//handle errors
}
);

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.

Listing 10-1 Read record


var onTagDetect = {
onattach: function(tag){
if(tag.isSupportedNDEF){
tag.readNDEF({
onsuccess: function(message){
for(var i=0; i < message.recordCount; i++){
switch(message.records[i].tnf){
case tizen.nfc.NFC_RECORD_TNF_EMPTY:
//go through different records

16_9781118539538-ch10.indd 154

1/18/13 1:32 PM

Chapter 10: Using Hardware in Tizen

155

}
}
}
},
function(){
//error callback of readNDEF()
}
);
}
}
};

Listing 10-1 gives a typical example of how to read a NDEF


message. The readNDEF function takes two parameters: a
compulsory NDEFMessageReadCallback and an optional
ErrorCallback. A NDEF message may contain multiple
records. Each NDEF record consists of a high level TNF
Record, a second level of type, an ID, and payload, as shown
in Figure 10-2.

Figure 10-2: NDEF message.

Tizen defines three types of NDEFRecord: NDEFRecordText,


NDEFRecordURI, and NDEFRecordMedia. For a known type
of record, instead of using the general payload property from
the NDEFRecord, you can use the more specific property
according to the type of record. For example, you can use the
text property if you know the record type is text:
if( record instanceof tizen.NDEFRecordText)
document.getElementById(Payload).innerText = record.text;

Otherwise, you can use the payload property of an unknown


type record, which is a buffer.

16_9781118539538-ch10.indd 155

1/18/13 1:32 PM

156

Part III: Tizen in Detail

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
}
);
}
}
};

The writeNDEF method takes three parameters. The first


parameter is the NDEF message needed to write to the tag. The
optional second and third parameters are callback functions,
which handle the success and error situations.
To create the NDEF message, you need to create an
NDEFMessage object ndefMessage. The NDEF message
encapsulates one or multiple NDEF records. In Tizen, an
NDEFMessage object has two properties: a record count and
a record array
var ndefRecord = new tizen.NDEFRecordText(Text Payload, enUS,
UTF16);
var recordArray = new Array(ndefRecord);
var ndefMessage = new tizen.NDEFMessage(recordArray);

After you create the NDEF message, you can pass it to the
writeNDEF method.

16_9781118539538-ch10.indd 156

1/18/13 1:32 PM

Chapter 10: Using Hardware in Tizen

157

Using NFC in peer-to-peer mode


The last NFC use case you can implement on Tizen is the
peer-to-peer mode. Peer-to-peer mode always involves two or
more NFC devices (peers), and its a two-way communication.
Tizen provides both send and receive NDEF message
functionality for the peer-to-peer mode. One peer can send a
NDEF message proactively, but can only receive an incoming
NDEF message if the receive listener is set.
To implement peer-to-peer mode, you first need to detect the
peer. After you set the NFCPeerDetectCallback (see the
earlier Writing a tag section), you receive an attached event
when a peer is detected and a detached event when a peer is
lost.
The second step is to the setReceiveNDEFListener to the
adapter itself to enable the app to receive incoming messages
from another peer.
When a peer is detected, you always need to check whether
the peer is connected or not. If its connected, you then
can send the message to that peer. Figure 10-3 shows the
sequence of how two peers (A and B) exchange information.

Figure 10-3: Peer-to-peer communication flow chart.

16_9781118539538-ch10.indd 157

1/18/13 1:32 PM

158

Part III: Tizen in Detail


Listing 10-2 Peer-to-Peer Sending and Receiving
Messages
nfcAdapter.setPeerDetectListener(
{
onattach: function(peer){
if(peer.isConnected){
var ndefMessage;
var recordArray = new Array(new tizen.
NDEFRecordText(test, en-US, UTF16));
ndefMessage = new tizen.
NDEFMessage(recordArray);
sendNDEF(ndefMessage);
peer.setReceiveNDEFListener(
{
onsuccess: function(message){
for(var i = 0; i < message.
recordCount; i++){
switch(message.records[i].tnf ){
case tizen.nfc.NFC_RECORD_
TNF_EMPTY:
// read the record
}
}
}
}
);
}
else{
//peer not connected
}
},
ondetach:function(){
//peer lost
}
}
);

Listing 10-2 shows the JavaScript code to allow peer A to send


and receive messages from peer B.

Detecting Device Orientation


Unlike NFC, which uses platform-specific APIs, the accelerometer
on Tizen uses only the standard W3C device orientation APIs.
As defined in the W3C specification, the deviceorientation
event supplies the physical orientation of the device, expressed
as a series of rotations of a local coordinate frame with three
axes x, y, and z, shown as Figure 10-4.

16_9781118539538-ch10.indd 158

1/18/13 1:32 PM

Chapter 10: Using Hardware in Tizen

159

To get orientation information, you just need to add the


listener to the DOM node:
window.addEventListener(deviceorientation, function(data){
this.direction = data.alpha;
this.tiltFB = data.beta;
this.tiltLR = data.gamma;
}, true);

Figure 10-4: Device coordinates.

The event listener takes three parameters:


The event type: A string representing the event for which
the handler is being registered.
Listener: A callback function to fire when the event is
received
Use capture: A Boolean indicating whether to bind the
event to its target element or bubble the event up the
DOM tree of targets.
Event capturing and event bubbling refers to the order of event
handling when one DOM element is inside another and both
are handling the same event. You can find out more about
event capturing, event bubbling, and the document object
model (DOM) in general here:
http://www.w3.org/TR/DOM-Level-2-Events/
events.html

16_9781118539538-ch10.indd 159

1/18/13 1:32 PM

160

Part III: Tizen in Detail


When the device orientation is changed, the listener function
is triggered. The orientation event returns the rotation data,
which includes how much the device is rotated around the z
axis by alpha degree (compass direction); around the x axis
by beta degree (tilt the device front-back); and around the y
axis by gamma degree (tilt the device left-right).
After you have the orientation data, you can use it to control
the UI element for example, an image rotating according to
the device orientation using CSS animation:
// Apply the transform to the image
document.getElementById(imgLogo).style.webkitTransform =
rotate(+ tiltLR +deg) rotate3d(1,0,0, +
(tiltFB*-1)+deg);
document.getElementById(imgLogo).style.MozTransform =
rotate(+ tiltLR +deg);
document.getElementById(imgLogo).style.transform = rotate(+
tiltLR +deg) rotate3d(1,0,0, + (tiltFB*1)+deg);

In the Tizen 2.0 alpha release, a new property called System


InfoDeviceOrientation was added to the SystemInfo
API. You can use this property to determine whether the
device is in portrait, landscape, reverse portrait, or reverse
landscape orientation.
This feature is a very recent addition to the Tizen API, so look
in the System Information section of Device Information in the
SDK Help for more details.

Detecting Device Motion


In a similar fashion to getting device orientation information,
motion data is also provided by the accelerometer sensor.
The devicemotion event is a superset of the device
orientation event. The acceleration data is returned in
three axes: x, y and z. These are measured in meters per
second squared (m/s^2).
To get the motion data, you need to add the devicemotion
event listener to your window object:
window.addEventListener(devicemotion, function(data){
var acceleration = data.accelerationIncludingGravity;

16_9781118539538-ch10.indd 160

1/18/13 1:32 PM

Chapter 10: Using Hardware in Tizen

161

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;
}

The difference between these two properties is shown in


Table 10-1. This shows the values for a device face up and
then moved upwards, forward, left and up and to the right.

Table 10-1

Acceleration Data Sample


Not
Accelerating

Accelerating Accelerating
Up
Forward

acceleration

{0, 0, 0}

{0, 0, 5}

{0, 2, 0}

acceleration
IncludingGravity

{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
IncludingGravity

{3, 0, 9.81}

{5, 0, 11}

Using the Vibration API


The vibrator is a tiny motor that drives a piece of uneven
metal and causes the vibration. Tizen uses the WebKit variation of vibrator APIs for its vibrator. The vibrator interface
is implemented by the Navigator type, and theres only one
vibration method:
navigator.webkitVibrate(1000)

This method accepts either an integer parameter representing


vibration time in milliseconds or a series of integers
representing the patterns of vibration. Odd entries represent

16_9781118539538-ch10.indd 161

1/18/13 1:32 PM

162

Part III: Tizen in Detail


vibration time in milliseconds, even entries still periods in
milliseconds between the vibrations.
navigator.webkitVibrate([1000, 500, 1500]);

If you want to achieve cross-platform code for the vibration


code, you can use following code for detecting the right API
to use:
var getVibrateFunc = function(){
var vibrate = function() {};
if (navigator.vibrate)
vibrate = function(p){
navigator.vibrate(p);
};
if (navigator.mozVibrate)
vibrate = function(p) {
navigator.mozVibrate(p);
};
if (navigator.webkitVibrate)
vibrate = function(p) {
navigator.webkitVibrate(p);
};
return vibrate;
};

At the time of writing, the vibration API isnt supported by the


Tizen reference device.

16_9781118539538-ch10.indd 162

1/18/13 1:32 PM

Chapter 11

Messaging
In This Chapter
Creating and sending messages
Searching for messages
Building a User Interface for message searching

ts often said that the smarter smartphones get, the less


they are used for actual voice calls. Walk around any
town, and youre likely to see smartphone users deep in
concentration, tapping at their screens as they send SMS,
email, and other forms of messages to friends and colleagues
who may actually be standing right next to them.
These days, people like to message more than talk, and the
Messaging API is a vital part of any smart device. The W3C
specifications dont contain any Messaging APIs, and Tizen
fills that gap by providing its own Messaging API.
The Tizen Messaging API allows you to create an application
with integrated messaging functionality, using SMS, MMS, or
email messages. You can use these Messaging APIs to create
and send messages, read messages, and manage stored
messages and their attachments.

In this chapter, we introduce the Messaging API, explain how


to create and send SMS and email messages, and then get
practical by introducing an SMS search example. This example
shows you how to search SMS messages on the device and also
demonstrates the use of some of the UI features introduced in
Chapter 7.

17_9781118539538-ch11.indd 163

1/18/13 1:33 PM

164

Part III: Tizen in Detail

Introducing the Messaging API


As with all the other Tizen APIs, due to the fact that messages
contain a users private data, access to the messaging
functionality is controlled using permission levels in the
config.xml file. (See the upcoming Getting Permission
section for more detail.)
If the appropriate permissions are set, a MessageManager
object is created and stored in the messaging property of
your apps tizen object. You can then use this object to
retrieve the messaging services provided by the platform.

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.

17_9781118539538-ch11.indd 164

1/18/13 1:33 PM

Chapter 11: Messaging

165

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.

17_9781118539538-ch11.indd 165

1/18/13 1:33 PM

166

Part III: Tizen in Detail


The first thing to check is whether the message body has
been downloaded. If it hasnt, then the attachments array
will be empty. After the message body has been downloaded,
check the attachments filePath attribute. If its null, the
attachment hasnt been downloaded, and you should use the
loadMessageAttachment() method to retrieve it.

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/api/messaging.send to
your permissions gives you access to the message sending
functionality.
Adding http://tizen.org/api/messaging.read to
your permissions lets you read from the message storage
Adding http://tizen.org/api/messaging.write
to your permissions lets you write to the message storage
Adding http://tizen.org/api/messaging allows
you access to all the features of the API.

Getting Practical: Searching


for Messages
In this example, we combine some of the messaging
functionality introduced in this chapter with some Tizen UI
Framework components and show you how to create an
application that finds all your SMS messages that contain a
specified word.

17_9781118539538-ch11.indd 166

1/18/13 1:33 PM

Chapter 11: Messaging

167

The application consists of a single page displaying a search


bar in the header area with the messages displayed in the
content area, as shown in Figure 11-1.

Figure 11-1: Message search app.

Creating the page


This example uses the Tizen Web UI Framework Single-Page
Application template. (For more information on templates and
how to create a project using one see the Getting Started
chapter.)
This template includes all the Tizen Web UI Framework
JavaScript files and style sheets you need to create a simple
single page application. These files are loaded in the head
section of the start file (index.html).
To create the UI similar to that shown in Figure 11-1, replace
the body section of the index.html file with the code shown
in Listing 11-1.

17_9781118539538-ch11.indd 167

1/18/13 1:33 PM

168

Part III: Tizen in Detail


Listing 11-1 index.html
<body>
<div data-role=page id=main>
<div data-role=header data-position=fixed>
<h1>Messages</h1>
<input type=tizen-search id=searchBox/>
</div><!-- /header -->
<div data-role=content>
<ul id=msgList data-role=listview></ul>
</div><!-- /content -->
<div data-role=footer data-position=fixed>
</div><!-- /footer -->
</div><!-- /page -->
</body>

Our application contains a header, content, and footer section


within the page area.
Header: The header contains a title and search bar and
is fixed to the top of the page. The search bar used is an
input element of type tizen-search.
Content: The content section contains a list of the SMS
messages. The list element uses the data-role listview
to apply all the necessary styles and list functionality
provided by the UI framework. Because the actual
content of the list will be dynamically created based
on the search result, you dont need to add any other
information to this index.html file.
Footer: The Footer contains the default back button and
is fixed to the bottom of the page.
Thats all you need to do to create the application page. The
next two sections look at how to fill the message list and
implement the search functionality.

Filling the message list


The content section of the page contains a list of all the SMS
messages on the device that meet the search criteria.
When the application is started, no search string is entered,
so all the SMS messages stored on the device are displayed in
the list.

17_9781118539538-ch11.indd 168

1/18/13 1:33 PM

Chapter 11: Messaging

169

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.

Listing 11-2 Page Initialisation


$(document).delegate(#main, pageinit, function() {
console.log(init);
// get message service
tizen.messaging.
getMessageServices(messaging.sms,
msgServiceCb, errCb);
$(#main .ui-btn-back).bind(vclick, function()
{
tizen.application.exit();
return false;
});
$(#searchBox).bind(input, updateList);
$(#searchBox).bind(change, updateList);
});

To use the exit() method, when the back button is clicked,


you must set the http://tizen.org/api/application
permission in your config.xml file.

Searching for messages


The message service callback function returns an array
containing message service objects. In this example, the SMS
message service object is retrieved from the array and stored
in a local variable.
To search for all the SMS messages on the device, you need to
use the message storage objects findMessages() method
with a tizen filter. In this example, you should create an
attribute filter to narrow down your search to SMS messages
only, as shown in Listing 11-3.

17_9781118539538-ch11.indd 169

1/18/13 1:33 PM

170

Part III: Tizen in Detail


Listing 11-3 Message SERVICE Callback
var msgService = null;
var msgStore = null;
function errCb(err) {
console.log(Error: + err.message);
}
function msgServiceCb(services) {
msgService = services[0];
msgStore = msgService.messageStorage;
var typeFilter = new tizen.AttributeFilter(type,
EXACTLY, messaging.sms);
msgStore.findMessages(typeFilter, msgFoundCb, errCb);
}

Drawing the list


The findMessages() method is asynchronous, so when the
action is completed, the callback function is returned with an
array containing all the messages that meet the search criteria.
At this point, all the SMS messages stored on the device are
returned within the array.
If no SMS messages are found, the success callback is invoked
with an empty array. If any errors occur while searching for
contacts, the optional error callback is invoked.
To display the messages as shown in Figure 11-1, you need
to populate the msgList list element that was defined in the
index.html file.
The list items are displayed using Tizen UI Framework bubble
class elements, with incoming messages displayed on the
left-hand side and outgoing messages displayed on the
right-hand side.
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

17_9781118539538-ch11.indd 170

1/18/13 1:33 PM

Chapter 11: Messaging

171

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.

Listing 11-4 List Drawing


var msgData = null;
function drawList() {
// Clear the list
$(#msgList li).remove();
// Draw the bubble list
if(msgData){
for(var i=0; i<msgData.length; i++){
if(msgData[i].from == ){
$(#msgList).append(<li class=ui-li-bubbleright>
+ msgData[i].body.plainBody
+ <span class=ui-li-bubble-time>
+ msgData[i].timestamp.toLocaleString()
+ </span></li>);
} else {
$(#msgList).append(<li class=ui-li-bubbleleft>
+ msgData[i].body.plainBody
+ <span class=ui-li-bubble-time>
+ msgData[i].timestamp.toLocaleString()
+ </span></li>);
}
}
// Refresh the list
$(#msgList).listview(refresh);
}
}
function msgFoundCb(messages) {
msgData = messages;
drawList();
}

Searching the message list


So far, the example app finds all the SMS messages stored on
the device and displays them in a list. Now you need to add
functionality to search for messages containing a specified
string.

17_9781118539538-ch11.indd 171

1/18/13 1:33 PM

172

Part III: Tizen in Detail


For this, you use the tizen-search input element, displayed
in the header section of the page, to accept user input and the
message storage objects findMessages() method to find
the messages.

Processing user input


The tizen-search UI element is used to get user input.
When the input element is activated, the user can enter his
search string. Theres no Accept or Submit button, so the list
needs to be updated after each letter is entered in the search
bar. Figure 11-2 shows a search in progress.

Figure 11-2: Searching for the word address.

When the user enters a character in the search bar, the input
elements input event is triggered.
To update the list to display only the messages containing
the search string, you need to handle this event. In the
initialisation code in the main.js file, you already defined a
method to handle this input event. The code in Listing 11-5
shows how to implement this updateList() method.
updateList() checks whether the search string has
changed; if it has, the findString() method is called.

17_9781118539538-ch11.indd 172

1/18/13 1:33 PM

Chapter 11: Messaging

173

In addition to the search bar, the tizen-search input


element also provides a Cancel button. When the Cancel
button is selected, the contents of the search bar are cleared
automatically, and the list needs to be reset. Unlike user entry
in the search bar, clicking the Cancel button doesnt trigger an
input event. Instead, it triggers a change event. So in order
to reset the list, you also need to implement a method to
handle this change event.
In this example, both the input and change events are
handled by the updateList() method.

Searching for messages


When the updateList() method is called, it retrieves the
current value of the tizen-search input element, which is
the string the user entered. This value is used to filter the SMS
message list, to display only those messages that contain the
search string.
To find all the SMS messages containing the search string, you
should create an attribute filter for the message type and one
for the search string and combine them using a composite
filter with the INTERSECTION filter type, as shown in the
findString() method in Listing 11-5. You can then use this
filter with the findMessages() method to get the messages.
Any messages found will be returned in the callback function
and displayed using the same method as described in the
Filling the message list section, earlier in this chapter.

Listing 11-5 Updating the List


var 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

17_9781118539538-ch11.indd 173

1/18/13 1:33 PM

174

Part III: Tizen in Detail


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;
}
}

17_9781118539538-ch11.indd 174

1/18/13 1:33 PM

Chapter 12

Working with Contacts


In This Chapter
Exploring the Contacts API
Manipulating contacts
Exporting and sharing contacts

eres a little exercise for you. Choose five people that


you talk to regularly, by phone, text, email, instant
messenger, or on some new social network that has become
inexorably popular since we wrote this book. Without sneaking
a look at your phone, write down the contact details of your
chosen friends, family, or colleagues. If youre like us, then
youll soon be guessing email addresses and trying to
pluck phone numbers out of thin air. The treasure trove of
information stored within your devices address books is hard
to do without.
The W3C APIs dont include the functionality for manipulating
address books and contacts, but you can access it by using
the Tizen-specific Contacts API. You can access multiple
address books, search for, update, and delete contacts, and
import and export from vCard format. The API is documented
in detail in the SDK Help, but in this chapter, you find practical
examples that will give you a head start in implementing
contacts functionality in your web apps.

Meeting the Key Personnel


The Contacts API in Tizen is responsible for managing contact
information and address books. Because this type of information is sensitive and you dont want this falling into the wrong
hands, the Tizen platform restricts app access to the address

18_9781118539538-ch12.indd 175

1/18/13 1:33 PM

176

Part III: Tizen in Detail


book by using permissions. Your app sets different permission levels in the config.xml file, depending on whether
you want to just read the contents of address books or make
changes. (See the Getting Permission section, later in this
chapter, for more detail.)
If the appropriate permissions are set, a ContactManager
object is created and stored in the contact property of your
apps tizen object. You then use this ContactManager to
access the devices address books.

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 default address book, you use the
following in your code:
var addressBook = tizen.contact.getDefaultAddressBook();

The default address book is set automatically by the


system, so if you want to access a specific address book,
use the getAddressBook(AddressBookId) method.
Alternatively, to get all the address books on the device,
use the getAddressBooks() method.
Depending on which ContactManager method you use,
the address book information will either be returned as an
AddressBook object or as an array of AddressBook objects.
The AddressBook interface provides the methods to get,
find, add, update, delete, and watch contacts within the
address book. As mentioned in the Getting Permission
section, later in this chapter, access to some of these methods
may be restricted depending on which permission you have
set for your application.

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.

18_9781118539538-ch12.indd 176

1/18/13 1:33 PM

Chapter 12: Working with Contacts

177

Doing everything at once


Whenever you make changes
to the address book, such as
adding, modifying, and deleting
contacts, the JavaScript API needs
to communicate with the native
platform, which can affect your
apps performance. If you have
multiple operations to perform,
its better to combine these into
a batch operation using the
addBatch, deleteBatch,
and updateBatch functions.

These operations are processed


asynchronously so that your app
doesnt have to hang around waiting
for a response.
Note that batch operations dont
give any progress information;
their success or failure callbacks
are invoked only when the whole
operation is complete. So if youre
performing a large number of
operations, you should break these
into batches of around ten contacts.

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: name,
addresses, photoURI, phoneNumbers, emails, birthday,
anniversaries, organization, notes, urls, isFavor
ite, ringtoneURI, and categories.
The Tizen Contacts API supports the standard vCard versions
2.1 and 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.

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/api/contact.read to
your permissions gives you access to all the methods in
the API, but you cant add, modify, or delete contacts.

18_9781118539538-ch12.indd 177

1/18/13 1:33 PM

178

Part III: Tizen in Detail


Adding http://tizen.org/api/contact.write
gives you access to everything except methods used to find
contacts or watch the address book.
Adding http://tizen.org/api/contact.contact
allows you access to all the features of the API.

Managing Your Contacts


This section takes a practical approach to demonstrating the
Contacts API by showing you code to create, search for, and
delete your contacts. Youll then be well prepared to add this
functionality to your own apps.

Adding a contact
In this example, we show you how to add a single contact to
the default address book.
Before you can perform any operations on an address book,
you must first retrieve it from the system. Heres how to get
the default address book:
var addressBook = tizen.contact.getDefaultAddressBook();

You then need to create and initialise a new Contact object


by calling the tizen.Contact constructor function and
specifying the properties of the contact:
var contact = new tizen.Contact({
name: new tizen.ContactName({firstName: Walter,
lastName: Bishop}),
emails: [new tizen.ContactEmailAddress(walter@
email.com)],
phoneNumbers: [new tizen.
ContactPhoneNumber(5552773, [HOME])]
});

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, ContactBirthday, and other
properties. See the Tizen SDK Help for a full list of properties
available.

18_9781118539538-ch12.indd 178

1/18/13 1:33 PM

Chapter 12: Working with Contacts

179

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,
VCARD_30);

After you create your contact, you can then add it to the
address book:
addressBook.add(contact);

This example shows how to add a single contact to the


address book using the synchronous add() method. If you
want to adding a number of items at once, use the asynchronous
addBatch method for better performance. (See the section
Doing everything at once for more details).

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

18_9781118539538-ch12.indd 179

1/18/13 1:33 PM

180

Part III: Tizen in Detail


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);

If you dont know the ContactRef of the contact you want,


you can use a filter to search for contacts with specific
attributes. The Tizen object provides several filter options
that you can use when searching for a contact.
In this example, we show how to search for a contact using
an AttributeFilter based on the value of the contacts
firstName attribute:
var attrFilter = new tizen.AttributeFilter(name.firstName,
CONTAINS, Walter);

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);

The find() method is an asynchronous method, which


searches for any contacts in the address book that match the
conditions in the filter and returns them in the defined
success callback. If no contacts are found matching the
conditions, the success callback is invoked with an empty
array. If any errors occur while searching for contacts, the
optional error callback is invoked.
function successCB(contacts) {
console.log(Number of contacts found:
+ contacts.length);
for (var i=0; i<contacts.length; i++){
console.log(Name:
+ contacts[i].name.firstName +
+ contacts[i].name.lastName
+ Email:
+ contacts[i].emails[0].email
+ Tel:
+ contacts[i].phoneNumbers[0].number);

18_9781118539538-ch12.indd 180

1/18/13 1:33 PM

Chapter 12: Working with Contacts

181

}
}
function errorCB(err) {
console.log(Error: + err.message);
}

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.
To get all the contacts in the address book, you can use the
find() method:
addressBook.find(successCB, 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);
}
}

18_9781118539538-ch12.indd 181

1/18/13 1:33 PM

182

Part III: Tizen in Detail


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.
If youre going to do something like this in your application,
we recommend that you ask the users permission first. Its
the polite thing to do.

Exporting a contact
In this example, we show you how to export a contact in the
vCard format. The Contact API supports vCard versions 2.1
and 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.
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 addressBook = tizen.contact.getAddressBook(contactRef.
addressBookId);
var contact = addressBook.get(contactRef.contactId);
var vCard = contact.convertToString(VCARD_30);
console.log(vCard);

In the current SDK release (Magnolia), the Simulator


JavaScript backend doesnt have an implementation for the
convertToString() method. So its currently not possible
to test this feature in the Simulator environment.

18_9781118539538-ch12.indd 182

1/18/13 1:33 PM

Chapter 13

Getting Organized
with Calendars
In This Chapter
Using the Calendar API
Creating and retrieving tasks
Adding reminders to a task

well-managed calendar on a device takes on the role of


your very efficient personal assistant. It helps you balance your family and work life and reminds you of everything
from birthdays and anniversaries to flight check-in dates and
project deadlines. This is one assistant that helps keep your
life organized without ever asking for time off.
Like contacts, which we discuss in Chapter 12, calendar
functionality isnt included in the W3C APIs, so the Tizen
Calendar APIs are designed to fill in the gap. Tizen has two
types of Calendar: a calendar for storing events that acts as a
schedule and a calendar for storing tasks that fills the role of
a to-do list.
The SDK Help tutorials include example code for manipulating
calendar events, so in this chapter, we introduce the Calendar
API and then get practical with some code for manipulating
calendar tasks.

Introducing the Calendar API


The Calendar API allows you to manage calendars and the
events and tasks stored within them. Because youll want to

19_9781118539538-ch13.indd 183

1/18/13 1:33 PM

184

Part III: Tizen in Detail


protect this sensitive information, the Tizen platform restricts
access to this data through different permission levels.
Permissions are set in the config.xml file. (See the upcoming Getting Permission section for more details).
If the appropriate permissions are set, a CalendarManager
object is created and stored in the calendar property of your
apps tizen object. You then use this CalendarManager to
access the devices calendars.

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);

You should always use the default calendar for new items.

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.

19_9781118539538-ch13.indd 184

1/18/13 1:33 PM

Chapter 13: Staying on Track with Calendars

185

Supported properties
The following properties are
supported for all calendar item types:
id, lastModificationDate,
description, summary,
isAllDay, startDate,
duration, location,
geolocation, organizer,
visibility, status,
priority, alarms,
categories, and attendees.

The calendar event type


supports the following additional
properties: i s D e t a c h e d ,
endDate, availability, and
recurrenceRule.
The calendar task type supports
the following additional properties:
dueDate, completedDate, and
progress.

To retrieve a specific calendar item from the calendar, you


can use the calendars get() method. This method returns
either a CalendarEvent or a CalendarTask object,
depending on whether youve performed the get() operation
on an event calendar or a task calendar.

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/api/calendar.read
gives you access to all the methods in the API, except for
any methods that add, modify, or delete events or tasks.
Adding http://tizen.org/api/calendar.write
gives you access to all the methods in the API, except for
any methods used to find events or tasks or watch the
calendar.
Adding http://tizen.org/api/calendar gives you
access to all the features in the API.
To use any of the Tizen Time objects, such as for setting the
date and time of calendar events and tasks, you need to set
one of the http://tizen.org/api/time permissions. See
the SDK Help for more details.

19_9781118539538-ch13.indd 185

1/18/13 1:33 PM

186

Part III: Tizen in Detail

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);

You then need to create your task using a tizen.


CalendarTask constructor.
You can specify the initial values for a new task in two ways:
using a CalendarTaskInit object or from a string formatted
in the iCalendar todo format VTODO. Look at the Support
for iCalendar sidebar in this chapter for more details about
Tizens support for this standard.
You can create a task using a CalendarTaskInit object
with the following code:
var task = new tizen.CalendarTask({
description:Chapter 13,
summary:Write Chapter 13 of the book,
dueDate:new tizen.TZDate(2012,5,15,15,0),
});

The month parameter of the TZDate constructor supports


values in the range 011, so in order to represent the month of
June, you need to set the month parameter to 5.
Alternatively, you can create a task by passing a formatted
VTODO string and the format parameter:
var task = new tizen.CalendarTask(BEGIN:VCALENDAR\r\n
+ VERSION:1.0\r\n
+ BEGIN:VTODO\r\n
+ DESCRIPTION:Chapter 13\r\n
+ SUMMARY:Write Chapter 13 of the book\r\n
+ DUE:20120615T150000\r\n
+ END:VTODO\r\n
+ END:VCALENDAR\r\n,
ICALENDAR_20);

After you create your task, you can then add it to the calendar:
calendar.add(task);

19_9781118539538-ch13.indd 186

1/18/13 1:33 PM

Chapter 13: Staying on Track with Calendars

187

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,

and removing events or tasks, into


batch operations.
These functions are asynchronous,
so you supply a callback function
that will be invoked when the
operation is complete. Your app
continues processing and stays
responsive without having to wait
for the changes to the calendar to be
completed.

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; // Value initialised with known data
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.

19_9781118539538-ch13.indd 187

1/18/13 1:33 PM

188

Part III: Tizen in Detail


In this example, we use an AttributeRange filter and the
tasks dueDate attribute to look for all tasks that are due in
the next 30 days:
var currentDateTime = tizen.time.getCurrentDateTime();
var endDate = currentDateTime.addDuration(
new tizen.TimeDuration(30, DAYS));
var dateFilter = new tizen.AttributeRangeFilter(dueDate,
currentDateTime, endDate);

The addDuration() method adds the specified duration value


to the TZDate object. If you want a date or time earlier than
the current value, you should set the length unit to be a
negative value for example, new tizen.TimeDuration
(-30, DAYS).
This attribute range filter gets used within the find()
method:
calendar.find(successCB, errorCB, dateFilter);

The find() method is an asynchronous method, which will


search for any tasks in the calendar that match the conditions
in the filter and return them in the defined success callback.
If no tasks are found matching the conditions, the success
callback is invoked with an empty array. If any errors occur
while searching for tasks, the optional error callback is
invoked:
function successCB(tasks) {
console.log(Number of tasks found:
+ tasks.length);
for (var i=0; i<tasks.length; i++){
console.log(Description:
+ tasks[i].description
+ Summary:
+ tasks[i].summary
+ Due Date:
+ tasks[i].dueDate);
}
}
function errorCB(err) {
console.log(Error: + err.message);
}

19_9781118539538-ch13.indd 188

1/18/13 1:33 PM

Chapter 13: Staying on Track with Calendars

189

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);

You then need to create an alarm using the tizen.


CalendarAlarm constructor.
We set an alarm to be triggered on an absolute date, specified
using a TZDate object:
var dueDate = task.dueDate;
var alarmDate = dueDate.addDuration(
new tizen.TimeDuration(-5, HOURS));
var alarm = new tizen.CalendarAlarm(alarmDate,
DISPLAY,
Reminder: Chapter 13 due in 5 hours!);

We set the alarm to be triggered at an absolute time, which


was calculated as 5 hours prior to the tasks due date.
Alternatively, you can create an alarm that is triggered at a
specified duration before the items start time:
var alarm = new tizen.CalendarAlarm(new tizen.TimeDuration(15,
MINS), DISPLAY,
Reminder: Task about to start in 15 minutes!);

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
lastModificationDate attribute or the alarms attribute.

19_9781118539538-ch13.indd 189

1/18/13 1:33 PM

190

Part III: Tizen in Detail

Support for the iCalendar format


iCalendar is a standard calendar
format supported by Google
Calendar, iCal, Lotus Notes,
Thunderbird, and many other
applications. You can recognize
iCalendar format files by the .ics
suffix.
The Tizen Calendar API supports the
iCalendar format as documented
in the RFC5545 standard. The

19_9781118539538-ch13.indd 190

mapping of the Tizen event and


task attributes to the VEVENT and
VTODO attributes in the iCalendar
specifications are detailed in the
SDK documentation.
The CalendarItem interface
also provides a couple of methods to
clone a calendar item or convert it to
iCalendar version 2.0 format.

1/18/13 1:33 PM

Part IV

The Part of Tens

20_9781118539538-pp04.indd 191

1/18/13 1:33 PM

In this part . . .

o For Dummies book is complete without a Part of


Tens.

Here youll find ten resources that were helpful to us when


we learned and tuned our JavaScript skills.
We also present ten reasons why you should develop for
Tizen.

20_9781118539538-pp04.indd 192

1/18/13 1:33 PM

Chapter 14

Ten Really Useful


Resources
In This Chapter
Blogs, videos and talks from the experts
JavaScript libraries to lighten the load
HTML5 tips, tricks and gotchas

his is a personal list of resources that we found useful


when learning JavaScript and HTML5, including tools that
we used when writing this book. The great thing about web
development is that youll find a lot of resources freely
available and just a click away.
We dont claim this is an exhaustive list and youre sure to
find many more resources as your web development adventures
continue, but we think youll find some valuable information
in this list.

JavaScript: The Definitive Guide


There are many JavaScript books out there, but this is one,
written by David Flanagan and published by OReilly (ISBN
978-0-596-80552-4) is one that weve found to be particularly
comprehensive, practical and useful. It currently weighs in at
over 1000 pages, so try not to drop it on your foot.

21_9781118539538-ch14.indd 193

1/18/13 1:34 PM

194

Part IV: The Part of Tens

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: The Good Parts


This book (OReilly ISBN: 978-0-596-51774-8), also by Douglas
Crockford, has helped us out of many a sticky coding situation.
It starts from the premise that JavaScript was designed in a
hurry, before it was refined, leaving behind a lot of bad parts.
Its a small book, but concentrates on correct coding and bad
habits to avoid.
You can also find a lot of information covered in the book
here: http://javascript.crockford.com/

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.

21_9781118539538-ch14.indd 194

1/18/13 1:34 PM

Chapter 14: Ten Really Useful Resources

195

Browser Developer Tools


There are some great developer tools built right into your
browser, which can help you debug your web applications.
Google Chrome includes a set of tools based on the WebKit
Web Inspector (as used for the Tizen Simulator, see Chapter
5). You can find more details here: https://developers.
google.com/chrome-developer-tools/
One of the most powerful tools is Firebug (http://
getfirebug.com/) which works with the Firefox browser
and allows you to debug JavaScript and also modify HTML
and CSS in real time.
Real-time preview of changes to HTML is also a feature of the
Safari development tools (https://developer.apple.
com/technologies/safari/developer-tools.html).
Since Safari is a WebKit based browser, these tools are also
based on Web Inspector.

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 based on jQuery.

21_9781118539538-ch14.indd 195

1/18/13 1:34 PM

196

Part IV: The Part of Tens


These are just a few libraries we found especially useful;
youre sure to find many more to assist your development
efforts.

Keeping up with HTML5


Keeping up with the HTML5 APIs can be a full time job, but
there are some websites which we can recommend:
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.

21_9781118539538-ch14.indd 196

1/18/13 1:34 PM

Chapter 14: Ten Really Useful Resources

197

The Linux Foundation


on YouTube
You can find the Linux Foundation channel at www.youtube.
com/user/TheLinuxFoundation
Type Tizen into the search bar and youll find videos of
presentations from various conferences (including some
featuring the authors of this book!) and up-to-date Tizen news
and demos.

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.

21_9781118539538-ch14.indd 197

1/18/13 1:34 PM

198

Part IV: The Part of Tens

21_9781118539538-ch14.indd 198

1/18/13 1:34 PM

Chapter 15

Ten Reasons You Should


Develop for Tizen
In This Chapter
Taking advantage of an easy-to-use interface
Getting Help when you need it
Breaking the boundaries of mobile

f youre one of those people who turns to the back of a


book to find out whodunnit, think of this chapter as ten
reasons why you should read the rest of the book.
If youve read through everything cover to cover, think of this
chapter as ten reasons to put down this book, launch the IDE,
and start developing Tizen apps.
If youre somewhere in between, then think of this chapter as
ten reasons to reward yourself with a cup of tea or coffee (and
perhaps a biscuit) before reading something else in the book.

Tizen Is Easy to Learn


Tizen web apps are developed using the language of the
web - JavaScript for the code, HTML for the layout, and CSS
for the UI. If you can create a website, you can build a Tizen
web app.

22_9781118539538-ch15.indd 199

1/18/13 1:34 PM

200

Part IV: The Part of Tens

Tizen Doesnt Reinvent


the Wheel
Tizen makes uses of popular JavaScript libraries, such as
jQuery and jQuery Mobile, which are used in many websites
and web apps. If you already know these libraries, youre well
on the way to developing Tizen apps.

Tizen Supports the Latest


Standards
If its part of the W3C/ HTML5 specifications, Tizen will
support it (at least partially in the case of some of the draft
specifications). For web developers, Tizen is the platform to
develop for.

Tizen Supports These


Standards Very Well
Tizen scores very high on the HTML5 standards compliance tests at http://html5test.com/. Visit this site from
a Tizen browser to see how well the standards are implemented. (Were that confident in the results!)

Tizen Fills in the Gaps


While many features are provided by the W3C APIs, standards
dont cover everything. Tizen fills in these gaps with devicespecific APIs covering calendars, contacts, and many other
features smart devices need to access, including Bluetooth
and power management.

22_9781118539538-ch15.indd 200

1/18/13 1:34 PM

Chapter 15: Ten Reasons You Should Develop for Tizen

201

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.

You Can Easily Get Help


Like many other open source projects, a whole community is
out there to help you. There are forums, an IRC channel, and a
wiki, and websites are springing up all the time. If you have a
question, the answer is out there.

You Can Give Back


You can give back to the Tizen community by reporting bugs,
suggesting changes and new features, and even influencing
the future of the project.

Tizen Isnt Just for Mobile


Tizen is for smartphones and tablets but also for TV set top
boxes and even cars, via the IVI (in-vehicle infotainment)
project. Maybe you have your own idea for a Tizen smart
device.

Tizen Isnt Just for Web


Developers
Tizen is evolving quickly, and while web apps are a great
solution, they wont always be the only way to create Tizen
apps.
Think of the Tizen story as to be continued.

22_9781118539538-ch15.indd 201

1/18/13 1:34 PM

202

Part IV: The Part of Tens

22_9781118539538-ch15.indd 202

1/18/13 1:34 PM

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.
Finally, we would like to thank our colleagues in our team at
SERI 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.

23_9781118539538-bother01.indd 203

1/18/13 1:34 PM

23_9781118539538-bother01.indd 204

1/18/13 1:34 PM

24_9781118539538-badvert01.indd 205

1/18/13 1:34 PM

SAMSUNG DEVELOPERS
JOIN US AND START CREATING GREAT APPS TODAY

SAMSUNG DEVELOPERS
Samsung Developers (http://developer.samsung.com)
provides a wealth of technical information and tools to
help you create apps for Samsung smart devices. Get up to
speed with the latest information on our mobile and Smart
TV platforms. Register as a Samsung Developer to get
regular updates on our various offline events, app
contests and software releases.

SAMSUNG APPS
Choose Samsung Apps to publish your app and reach
a global audience of millions. Accessible from every
Samsung smart device around the world, Samsung Apps
provides its customers with reliable high quality content
and its developers with localized support services. Make
the most of our in-app revenue generators to increase
your development ROI.

SELLER OFFICE
Seller Office is the administration system required to
distribute apps, from app registration and certification, to
deployment of your app through Samsung Apps. Seller
Office will guide you through the whole process and once
your app is live, buyer comments, sales/profit reports and
other vital statistical information can be easily viewed.

SAMSUNG DEVELOPERS
Realize your Imagination with
Samsung Developers
http://developer.samsung.com

24_9781118539538-badvert01.indd 206

Keep in touch with Samsung Developers!


Twitter
@samsung_dev
YouTube
youtube.com/SMInnov8
Facebook facebook.com/groups/samsungdevelopers

1/18/13 1:34 PM

También podría gustarte