Вы находитесь на странице: 1из 350

Development Guide

BlackBerry WebWorks 2.2

Published: 2015-03-13
SWD-20150313105458214

Contents
Getting Started ........................................................................................................................................... 5
What's a BlackBerry WebWorks app?..............................................................................................................5
Components of the BlackBerry 10 WebWorks SDK..........................................................................................7
Setting up your system................................................................................................................................. 12
Creating a WebWorks project........................................................................................................................21
Creating your first app.................................................................................................................................. 24
Porting and Upgrading............................................................................................................................... 27
Upgrading from WebWorks 1.0.....................................................................................................................27
Updating your WebWorks project................................................................................................................. 34
Porting from Cordova................................................................................................................................... 35
Porting to other platforms.............................................................................................................................37
Porting AIR apps to WebWorks..................................................................................................................... 38
Adding Features........................................................................................................................................ 43
Adding and removing plugins....................................................................................................................... 43
Using custom plugins................................................................................................................................... 48
Modifying your app configuration..................................................................................................................56
Creating headless WebWorks apps............................................................................................................. 108
App integration.......................................................................................................................................... 114
BBM Social Platform.................................................................................................................................. 225
Payment Service........................................................................................................................................ 232
Push Service.............................................................................................................................................. 247
Frameworks............................................................................................................................................. 267
jQuery ....................................................................................................................................................... 267
Sencha Touch 2......................................................................................................................................... 270
Dojo Toolkit................................................................................................................................................272
Enyo 2.0.................................................................................................................................................... 275
Construct 2................................................................................................................................................ 277
bbUI toolkit................................................................................................................................................ 281
Building and Testing................................................................................................................................ 283
Setting up test targets................................................................................................................................ 283
Previewing your app in a browser................................................................................................................286
Building your app in debug mode............................................................................................................... 286
Deploying your app to a simulator...............................................................................................................287
Deploying your app to a device................................................................................................................... 289

Debugging using Web Inspector................................................................................................................. 292


Testing and debugging apps in the work space .......................................................................................... 315
Building and signing your completed app................................................................................................... 316
Distributing your app..................................................................................................................................321
Best Practices......................................................................................................................................... 323
UI guidelines..............................................................................................................................................323
Personally identifiable information..............................................................................................................323
HTML best practices.................................................................................................................................. 324
CSS best practices..................................................................................................................................... 331
JavaScript best practices........................................................................................................................... 336
Legal notice............................................................................................................................................. 347

Getting Started
Learn what HTML5 and the Cordova for BlackBerry platform have to offer, and build your first app.
In this section, you can find resources to help you get started developing applications for the BlackBerry
WebWorks platform.

What's a BlackBerry WebWorks app?


A BlackBerry WebWorks app is a web application that runs on a BlackBerry device.
As of BlackBerry WebWorks 2.0, the BlackBerry 10 WebWorks SDK is now built on Apache Cordova, an opensource development framework that lets you create applications using web technologies. Be sure to check out
some of the BlackBerry WebWorks Samples.
Although adopting Cordova as the development standard has resulted in some changes to the way WebWorks
applications are structured, the process is not complicated. Creating a BlackBerry WebWorks app involves the
following high-level steps:
1. Create your project: Use the BlackBerry 10 WebWorks SDK web tool or the command line tool to create the
folder structure and template files for your new WebWorks project.
2. Design and develop your app logic and resources: Create the HTML, CSS, JavaScript files and other
resources, or reuse existing ones, and save them in the appropriate locations in your project's /www folder.
3. Add the required plugins: A plugin represents a set of APIs that allow your app to access the features of the
platform by binding the JavaScript functions to the native methods of the device code.
4. Build and test your app: Use the web tool or the command line to test your app in a simulator or on a
device.
5. Distribute your app: Build and sign your completed app and submit it to BlackBerry World.
Why create a BlackBerry WebWorks app? Some reasons to consider are:
portability
integration with core BlackBerry apps
ease of access, even when users do not have an Internet connection available

Portability
Because you create them using common web standards, BlackBerry WebWorks apps are not platformdependent. When you port to other mobile platforms, such as iOS or Android, you can reuse many of your
existing web assets.
By aligning with Apache Cordova for BlackBerry WebWorks 2.0, your WebWorks apps will now have an even
greater level of compatibility. Cordova provides a common development layer, and makes adapting the output
Getting Started

to multiple mobile platforms much simpler. You create an app using the languages you know, and Cordova
handles the bindings to the native layer of the various platforms.
You can also take advantage of popular mobile web frameworks, such as Sencha Touch, jQuery Mobile, Dojo,
and others. These frameworks provide a wide range of useful APIs that can greatly simplify cross-browser web
development. Many of these frameworks also provide a BlackBerry theme to help you achieve the same look
and feel as apps written in C/C++. See Frameworks on page 267 for more information.

Integration
BlackBerry WebWorks APIs let you integrate your app with BlackBerry hardware, core apps, and services.
Standard HTML5 provides access to some BlackBerry device features, such as geolocation information and
device orientation, but the BlackBerry WebWorks APIs allow you to access BlackBerry specific data. For
example, you can check the battery power level, find out whether the device is holstered, or get brightness
information from the light sensor.
BlackBerry WebWorks APIs let you integrate with many of the core BlackBerry applications. For example, you
can integrate your app with BBM, Calendar, or Contacts.
You can invoke a single screen (called a card) from another app while in your app. This lets users interact with
another application to perform a specific task, such as picking a contact, composing an email, or previewing
an image, without leaving your app.
You can use BlackBerry WebWorks APIs to access:
App Integration: Launch another application in your app's UI.
Payment Service: Offer digital goods for sale in your app.
Push Service: Enable direct, near real-time content delivery to your application users.
For more information, see Adding Features on page 43.

Ease of access
An app packaged with BlackBerry WebWorks can use server data if it needs to. Load times can be reduced
because most of the logic and presentation layer of the app are already on the device. If you can make your
application's resources local to the BlackBerry device, users will be able to access your content even when
they don't have an Internet connection.
When you package your web app as a BlackBerry WebWorks app, you can publish it to BlackBerry World,
where users can find and buy it. No registration fees or submission fees are required to become a BlackBerry
World vendor. To learn more about publishing your app, see BlackBerry World on the BlackBerry Developer
website.

Getting Started

Components of the BlackBerry 10 WebWorks SDK


The BlackBerry 10 WebWorks SDK provides the tools and plugins you need to configure and build a WebWorks
app. You create web assets using your preferred tools, and then use the SDK to package the assets into a .bar
file that can be installed onto a BlackBerry device.
Installing the BlackBerry 10 WebWorks SDK gives you:
tools to help you create, build, test, and sign your apps
the complete set of BlackBerry and Cordova plugins
The BlackBerry 10 WebWorks SDK is built on Apache Cordova, an open-source development framework that
lets you create applications using web technologies. This lets you take the resources that you used to create an
app for one platform, and, with some slight modifications, port that app to other platforms, such as Android or
iOS.

The BlackBerry 10 WebWorks SDK web tool


The BlackBerry 10 WebWorks SDK web tool is a UI that allows you to:

create an app
specify configuration settings
add plugins
build and deploy your app for testing
build and sign your app for production

By default, the UI displays only the projects you created with the web tool in your current browser. If you have a
project that was created outside the web tool or in a different browser, you can import it at any time. For more
information about importing projects, see Importing a WebWorks 2.0 project into the SDK web tool on page
23.
Note: To use the The BlackBerry 10 WebWorks SDK web tool, your browser must accept cookies. All
WebWorks project content that appears in the tool is stored in browser cookies. Deleting these cookies
removes the project data from the web tool, but leaves the project folders intact. No project information is lost,
but you have to import your projects to work with them in the web tool.

BlackBerry 10 WebWorks SDK command-line interface


The BlackBerry 10 WebWorks SDK command-line interface provides a number of commands that allow you to
create projects, add plugins, and build and test your app.
The available commands are:

Getting Started

Command

Description

Global commands (may be used from within any folder)


create

Creates a WebWorks project.

create-headless

Creates a WebWorks project with a headless service component.

target

Manages devices and simulators for testing.

help

Describes the usage of the WebWorks commands. Entering webworks help


<command> provides usage information about that command.

Project-based commands (may be used within a project folder)


build

Packages the app into a .bar file. You can choose to package the app for testing
(debug mode) or to package and sign the app for production (release mode).

run

Builds the app and deploys it onto a BlackBerry device. You can choose to
deploy the app for testing (debug mode) or sign and deploy the app for
production (release mode).

emulate

Builds the app and deploys it onto the simulator for testing.

plugin

Manages the app's plugins.

serve

Serves the app so you can preview it in your local browser.

Plugins installed with BlackBerry 10 WebWorks SDK


The BlackBerry 10 WebWorks SDK includes all the standard WebWorks and Cordova plugins.
Plugins represent the layer that connects JavaScript to the native C/C++ layer of the BlackBerry 10 OS. They
allow you to access the native functionality of the device (for example, accessing accelerometer data, or using
the camera) without the need to code in the device's native language.
To use a plugin to access native functionality, you must:
Use the methods, properties, and events for an API in your JavaScript code as described in the API
Reference.
Add the appropriate plugins to your app to bind your JavaScript code to the native C/C++ code.
Getting Started

Note: Some plugins require you to add certain permissions to the app configuration in order to access native
functionality. In most cases, when you add a plugin that requires a permission, the permission is added
automatically to the configuration by the tools. In some cases, however, the permission is only required to
access a subset of the native functionality. In these cases, the permission is not added automatically; you must
add the permission yourself. For more information about adding permissions, see Adding and removing app
permissions.

BlackBerry WebWorks plugins


Plugin ID

Name

Description

com.blackberry.app

Application

Provides basic app support.

com.blackberry.bbm.platfor BBM Platform


m

Lets you access the social features and


functionality of BBM.
Required permission: bbm_connect

com.blackberry.connection

Connection

Lets you access the cellular and Wi-Fi


connection information for the BlackBerry
device.

com.blackberry.display

Display

Allows you to control whether the screen dims


while the app is in the foreground.

com.blackberry.identity

Identity

Provides information about the user's identity


and accounts.
Required permission:
read_device_identitying_information

com.blackberry.ui.input

Input

Lets your app respond to user events on a


touch-enabled keyboard. This is a new input
event layer for use with touch-enabled
keyboards beginning with BlackBerry 10.3. It is
unrelated to DOM mouse events or HTML5
touch events on the screen.

com.blackberry.invoke

Invoke

Lets your app invoke and interact with other


apps on the device.

com.blackberry.invoke.card Card

Lets your app invoke a screen of another app on


the device.

com.blackberry.invoked

Lets your app be invoked by other apps on the


device.

Invoked

Getting Started

Plugin ID

Name

Description

com.blackberry.io

IO

Provides access to folders on the device.

com.blackberry.io.filetransfe
r

Deprecated since BlackBerry WebWorks 2.2.


Use org.apache.cordova.file-transfer instead.

com.blackberry.notification

Lets your app provide notifications to the user.

Notification

Required permission: post_notification


com.blackberry.payment

Payment

com.blackberry.pim.calenda Calendar
r

Lets you sell digital goods in your app.


Lets you access and manage entries in the
Calendar application.
Required permission:
access_pimdomain_calendars

com.blackberry.pim.contact Contacts
s

Lets you create and find contacts.

com.blackberry.push

Lets you access the BlackBerry push


architecture to receive push content in your
app.

PushPayload
PushService

Required permission:
access_pimdomain_contacts

Required permissions:
sys_use_consumer_push
run_when_backgrounded
com.blackberry.screenshot

Screenshot

Lets you capture an image of the device screen.

com.blackberry.sensors

Sensors

Lets you get access to system level sensors and


attributes of the BlackBerry device.

com.blackberry.system

System

Lets you access system level functions and


attributes of the BlackBerry device.

com.blackberry.ui.contextm Context Menu


enu

Lets you control whether context menus are


enabled, listen to events, add items to appear
based on the context, and set the theme of the
context menu.

com.blackberry.ui.cover

Lets you modify the app's window cover, which


is displayed when the app is in thumbnail mode.

Window Covers

Getting Started

10

Plugin ID

Name

Description

com.blackberry.ui.dialog

Dialog

Lets you manipulate system dialog boxes.

com.blackberry.ui.toast

Toast

Lets you display system toasts in your app.

com.blackberry.user.identity User Identity

Lets you access the user's personal information


stored in the identity provider's account system,
and provide user authentication/authorization
to access the identity provider's apps and
services.

Cordova plugins installed with BlackBerry WebWorks SDK


Plugin ID

Name

Description

org.apache.cordova.battery- Events (Battery Status)


status

Provides an implementation of an old version of


the Battery Status Events API.

org.apache.cordova.camera Camera

Provides access to the device's default camera


application.

org.apache.cordova.contact Contacts
s

Provides access to the device's contact


database.

org.apache.cordova.device

Describes the device's hardware and software.

Device

org.apache.cordova.device- Device Motion


motion
(Accelerometer)

Captures device motion along the x, y, and z


axes.

org.apache.cordova.device- Device Orientation


orientation
(Compass)

Obtains the direction that the device is pointing.

org.apache.cordova.dialogs

Notification (Dialogs)

Lets your app create visual, audible, and tactile


notifications.

org.apache.cordova.file

File System

Provides the functionality to read, write, and


navigate file system hierarchies.

org.apache.cordova.filetransfer

File Transfer

Lets you upload and download files.

org.apache.cordova.geoloca Geolocation
tion

Provides access to location information based


on the device's GPS sensor or inferred from
network signals.

Getting Started

11

Plugin ID

Name

Description

org.apache.cordova.inappbr InAppBrowser
owser

Provides a browser view that displays when


calling window.open(), or when opening a
link formed as <a target="_blank">.

org.apache.cordova.media

Media

Lets your app play back audio and video files on


a device.

org.apache.cordova.mediacapture

Media Capture

Provides access to the device's audio, image,


and video capture capabilities.

org.apache.cordova.network Network Information


-information
(Connection)

Provides information about the device's cellular


and Wi-Fi connection.

org.apache.cordova.splashs Splashscreen
creen

Lets your app hide and show the splash screen.

org.apache.cordova.vibratio Notification (Vibration)


n

Lets your app create visual, audible, and tactile


notifications.

Setting up your system


The BlackBerry WebWorks SDK provides a set of tools that you can use to create apps using web technologies.

System requirements
Before downloading and using the BlackBerry 10 WebWorks SDK, make sure that your system meets the
following requirements:
Runtime environment

Java Runtime Environment 1.6 (32-bit)

Processor

Intel Pentium or AMD Athlon desktop processor 2 GHz or faster

Virtual environment

BlackBerry 10 Device Simulator requires VMware Player on Windows or


VMware Fusion on Mac OS X

Storage space

1 GB or more available hard disk space

RAM

2 GB RAM or more

Monitor

Resolution of 1024 x 768 or higher

Getting Started

12

OS

Windows XP SP3 32-bit


Windows 7 32-bit or 64-bit
Mac OS X 10.6.4 or Latest Version
Ubuntu 12.04

BlackBerry 10 WebWorks SDK browser requirements


Note the following requirements if you intend to use the BlackBerry 10 WebWorks SDK web tool to configure
and build your projects:

Supported browsers
The BlackBerry 10 WebWorks SDK web tool has been tested against the following browsers:

Google Chrome
Mozilla Firefox
Safari (version 6 or later)
Internet Explorer (version 8 or later)

Cookie settings
To use the The BlackBerry 10 WebWorks SDK web tool, your browser must accept cookies. All WebWorks
project content that appears in the tool is stored in browser cookies. Deleting these cookies removes the
project data from the web tool, but leaves the project folders intact. No project information is lost, but you have
to import your projects to work with them in the web tool. For more information about importing projects, see
Importing a WebWorks 2.0 project into the SDK web tool on page 23.

Setting up the tools


To set up the BlackBerry 10 WebWorks SDK, follow these steps:
1. Download and install the BlackBerry 10 WebWorks SDK.
Note:
If you are installing to Ubuntu, after downloading the installer, you'll need to make it executable by running
the following commands:
$ chmod u+x ./ BB10-WebWorks-SDK_<version>.bin
$ ./BB10-WebWorks-SDK_<version>.bin
2. Download and install the BlackBerry 10 Device Simulator. If you have a BlackBerry 10 device available for
testing, downloading a simulator isn't required.
3. Set up your computer for testing and signing. Use your BlackBerry ID to create your BlackBerry ID token
and then use your BlackBerry ID token to create your developer certificate.
Getting Started

13

Note: The BlackBerry ID token is used to create the debug token that allows you to install and test an
unsigned app on a BlackBerry 10 device. If you don't have a BlackBerry ID token, you cannot test your app
on a device.

Setting up your computer for debugging and signing


Before you can test your app on a BlackBerry 10 device or sign it for distribution through BlackBerry World,
you need to set up your computer for debugging and signing. To get your computer set up, you need use your
BlackBerry ID to request a BlackBerry ID token. You can then use that BlackBerry ID token to create a
developer certificate.
Before you begin:
To request a BlackBerry ID token, you first need a BlackBerry ID. A BlackBerry ID identifies you to BlackBerry,
whether you are accessing BlackBerry websites, apps, or services from your computer or your device. End
users as well as developers need to have a BlackBerry ID. If you don't already have one, you can get one at
http://us.blackberry.com/bbid.html.
Note: Using the BlackBerry ID token is new in BlackBerry WebWorks 2.0. If you are updating an app created
using an earlier version of WebWorks, you can link your legacy token (barsigner.csk) to your new BlackBerry ID
token (bbidtoken.csk) to maintain continuity. For more information, see Linking your BlackBerry ID token to a
signing authority account on page 33.
Questions about signing and debugging? Check out the Frequently Asked Questions.

Request your BlackBerry ID token


1. Go to https://developer.blackberry.com/codesigning and login using your BlackBerry ID credentials.
You can also access this page from the Certificates page of SDK web tool.
2. Enter and confirm the password you want to use to secure your BlackBerry ID token, and then click Get
Token. The password is also used to create your developer certificate. Provide this password whenever you
want to sign a completed app, or test an unsigned app on a BlackBerry 10 device.
Note: If you forget this password, we can't retrieve or reset it for you. To recover from a forgotten password,
you must request another BlackBerry ID token, then recreate your developer certificate.
3. Accept the license agreement and click Get Token.
The Signing Authority Service uses thisBlackBerry ID token (bbidtoken.csk) file for authentication when you
sign your app using the associated developer certificate. Signing your app helps verify the integrity and
authenticity of your app to users and to the BlackBerry 10 OS. The BlackBerry 10 WebWorks SDK also uses the
BlackBerry ID token to create a debug token that allows you to test your unsigned apps on a BlackBerry 10
device.
Your BlackBerry ID token is valid for one year. When it expires, you need to request a new one.

Create your developer certificate


To sign apps and create debug tokens, you must use your BlackBerry ID token to create a developer
certificate. Each time you request a new BlackBerry ID token, you must create a new developer certificate.
Getting Started

14

Create your developer certificate using the SDK web tool


1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click Certificates.
3. In the Location field of the Install group, enter the full path to your bbidtoken.csk file. For example, c:\users
\<name>\downloads\bbidtoken.csk.
4. Click Install Signing Token. The signing key (bbidtoken.csk) is installed to the following location:
Windows XP: %HOMEPATH%\Local Settings\Application Data\Research In Motion
Windows Vista, Windows 7, and Windows 8: %HOMEPATH%\AppData\Local\Research In Motion
Mac OS: ~/Library/Research In Motion
Ubuntu: ~/.rim
5. In the Keystore Password field, enter your BlackBerry ID token password.
6. In the Company name field, type the name of the organization you want to associate with the developer
certificate.
7. Click Create Certificate. The developer certificate (the author.p12 file) is created in the same location as
your signing key.

Create your developer certificate from the command line


1. Copy your BlackBerry ID token (bbidtoken.csk) to the following directory:
Windows XP: %HOMEPATH%\Local Settings\Application Data\Research In Motion
Windows Vista, Windows 7, and Windows 8: %HOMEPATH%\AppData\Local\Research In Motion
Mac OS: ~/Library/Research In Motion
Ubuntu: ~/.rim
2. From the command line, navigate to the cordova-blackberry/bin/dependencies/bb-tools/bin subfolder of
your BlackBerry 10 WebWorks SDK installation folder.
3. Run the blackberry-keytool command to create your developer certificate (author.p12 file).
blackberry-keytool -genkeypair -storepass <bbidtoken_pw> -dname
"cn=<company_name>"
When you run this command, the author.p12 file is created in the same folder where you installed the
bbidtoken.csk in Step 1.
Check the table below for parameter details:

Getting Started

15

Parameters

Description

-genkeypair

Generates a key pair that consists of a private key and a public


key.

-storepass <bbidtoken_pw>

Specifies the password you defined for your BlackBerry ID


token.

-dname "cn=<company_name>"

Specifies the name to associate with the certificate that the


tool creates.

Signing and debugging: Frequently Asked Questions


Why must I sign my app?
Signing your app is an important security step. Normally, every app that is installed on a BlackBerry 10 device
must be signed.
Signing adds cryptographic hash values to your application .bar file, which help to verify the authorship of your
app to other users and to the BlackBerry 10 OS. This process allows users to trace the origin of the app and
feel confident that it is a safe app to use.
When must I sign my app?
Signing is the final step when you are ready to build the release version of your app. Each time you sign your
app, you must increment the version of the app.
How do I sign my app?
With the BlackBerry WebWorks SDK, your app is automatically signed when you build a release version of the
app using either the SDK web tool or the command-line tools. For information on signing your app, see Building
and signing your completed app on page 316.
How do I test an app without increasing the version number?
During development, you can deploy an unsigned (debug) version of your app to a device for testing. To deploy
an unsigned (debug) version of an app to a BlackBerry device, the device must have a valid debug token
installed on it. For information on deploying an unsigned app to a device, see Deploying your app to a device on
page 289.
What is a debug token?
A debug token allows you to install and run unsigned apps on a BlackBerry 10 device so you can debug your
apps. Debug tokens are valid for 30 days. When a debug token expires, the BlackBerry 10 OS no longer allows
unsigned apps that rely on that token to run.
You are limited to a total of 100 device PINs across the active debug tokens associated with the same keystore
password. This restriction means that if you create and install debug tokens on 100 devices, you must wait for
some of your debug tokens to expire before you create more.
Getting Started

16

How do I create a debug token?


With the BlackBerry WebWorks SDK, a debug token is created and installed automatically whenever it is
required. If a valid token doesn't exist on the target device when you try to deploy your app, the SDK tools
create and install the debug token for you. For more information about deploying your app to a BlackBerry 10
device, see Deploying your app to a device on page 289.
Do I have to create a debug token for every app I create?
Debug tokens are not specific to a single app. When you have a valid debug token installed on your BlackBerry
10 device, you can deploy any unsigned app that you have created to the device for testing until that debug
token expires.

Defining proxy server settings


Occasionaly, the SDK tools might need to communicate with the Signing Authority Service to allow it to create
debug tokens and sign your app. If your computer connects to the Internet through a proxy server, the tools
might need some additional information to communicate with the Signing Authority Service.
The command-line tools allow you to add proxy server information to the commands to facilitate this
communication. However, if you choose to, you can save your proxy server settings within the SDK web tool.
When you provide and save this information, the tools automatically append these settings to commands
whenever they need to communicate through the proxy server. This behavior affects both the web tool and the
command-line tools.
Note: When you save your proxy settings, the SDK web tool does not encrypt any password settings you set.
This value is saved in human-readable text. If you require a proxy server password and do not want to risk
having this value exposed, you should use the command-line tools and add the proxy options as necessary.
Define proxy settings using the SDK web tool
To define proxy settings:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the navigation panel, click Global Settings.
3. In the Proxy host field, specify the network server that provides the proxy service. The value can be an IP
address or a fully qualified domain name.
4. In the Proxy port field, specify the port number on your proxy server through which the tool should
communicate with the Signing Authority Service.
5. In the Proxy username field, specify your username on the proxy server, if your proxy server requires
authentication.
6. In the Proxy password field, specify your password on the proxy server, if your proxy server requires
authentication.
Note: The password is saved as unencrypted plain text.
7. Click Save.
When the proxy settings are saved in the web tool, both the SDK web tool and the command-line tools use
these settings whenever communication through the proxy server is necessary.
Getting Started

17

Include proxy server settings from the command line


During the creation of a debug token or during the signing process, your computer needs connects to the
Signing Authority Service. If your computer connects to the Internet through a proxy server, you may need to
add some additional options to your commands to allow the tools to communicate with the Signing Authority
Service. These options are appended to the blackberry-signer or blackberrydebugtokenrequest commands.
Note: If you define your proxy server settings within the SDK web tool, you won't have to add the proxy options
to your commands; once defined, the settings are appended to the CLI commands automatically.
The following table describes the proxy options available:
Options

Description

-proxyhost <host>

The network server that provides the proxy service. The value can be
an IP address or a fully qualified domain name.

-proxyport <port>

The port number on your proxy server through which blackberrysigner or blackberry-debugtokenrequest should
communicate with the Signing Authority Service.

-proxyusername

Your username on the proxy server, if your proxy server requires


authentication.

<user name>
-proxypassword
<password>

Your password on the proxy server, if your proxy server requires


authentication.

Signing an app with a proxy server


To sign your app with a proxy server:
1. From the command line, navigate to the cordova-blackberry/bin/dependencies/bb-tools/bin subfolder of
your BlackBerry 10 WebWorks SDK installation folder.
2. Run the blackberry-signer command, and append the proxy options to the standard blackberrysigner options. You would use the following syntax:
blackberry-signer -proxyhost <host> -proxyport <port> -bbidtoken
<bbid_token_file>
storepass <keystore_pw> <BAR_filename>
The following table describes the standard blackberry-signer options used above:

Getting Started

18

option

Description

-bbidtoken
<bbid_token_file>

Your BlackBerry ID token .csk file. For information on how to


request this file, see Request your BlackBerry ID token on page 14.

-storepass <keystore_pw>

The keystore password. You define this password when you request
your BlackBerry ID token.

<BAR_filename>

The file name of the signed .bar file.

For example:
blackberry-signer -proxyhost 192.168.1.1 -proxyport 80 -bbidtoken
bbidtoken.csk
storepass MySecretPassword1 MyApp.bar

Creating a debug token with a proxy server


To create a debug token with a proxy server:
1. From the command line, navigate to the cordova-blackberry/bin/dependencies/bb-tools/bin subfolder of
your BlackBerry 10 WebWorks SDK installation folder.
2. Run the blackberry-debugtokenrequest command, and append the proxy options to the standard
blackberry-debugtokenrequest options. You would use the following syntax:
blackberry-debugtokenrequest -proxyhost <host> -proxyport <port>
-storepass <keystore_pw> -devicepin <device PIN>
<debug_token_file_name.bar>
If you have multiple devices you want to test on, list their PINs in a file, and use the following command:
blackberry-debugtokenrequest -proxyhost <host> -proxyport <port>
-storepass <keystore_pw> -devicepinlist <device_PIN_list_file>
<debug_token_file_name.bar>
The following table describes the standard blackberry-debugtokenrequest options used above:

Getting Started

19

option

Description

-storepass <keystore_pw>

The keystore password. You define this password when you


request your BlackBerry ID token.

-devicepin<device PIN>

The PIN of the BlackBerry 10 device on which you want to


install this debug token.

The name of a file containing the PINs of the BlackBerry 10


devicepinlist<device_PIN_list devices on which you want to install this debug token. For
_file>
example, the contents of a file called device_PINs.txt might
appear as follows:
12G34H56 2K672HVP 221Q2958
You would specify it like using the following syntax:
-devicepinlist device_PINs.txt
<debug_token_file_name.bar>

The file name of the debug token .bar file.


The debug token file must end with .bar. If you specify the
name of an existing file, blackberrydebugtokenrequest deletes the existing file before
creating the debug token.
If you specify a path that does not include a file name,
blackberry-debugtokenrequest deletes the directory
you specify and does not create a debug token.

3. Install the debug token on a BlackBerry 10 device:


a. Determine the development IP address. You can view the development IP address on your device by
opening Settings>Security and Privacy>Development Mode.
b. From the command line, navigate to the cordova-blackberry/bin/dependencies/bb-tools/bin subfolder of
your BlackBerry 10 WebWorks SDK installation folder.
c. Run the blackberry-deploy command to install the debug token on your device:
blackberry-deploy -installDebugToken <path_to_debug_token>
-device <development_IP_Address> -password <device_pw>

Defining an alternative token or certificate location


By default, the SDK tools require that your BlackBerry ID token be located in a specific folder. This default
location varies depending on which OS you are running. However, if you store your certificate or token in a
location that is not the default (for example, if you share them across multiple developers at your organization),
you can provide an alternative location to allow the SDK tools to access them.
Getting Started

20

To define an alternative signing certificate configuration:


1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the navigation panel, click Global Settings.
3. In the Developer Certificate Location field, specify the full path to the author.p12 file. You must include the
filename. For example: \\shared_server\bb_signing\author.p12.
4. In the BBID Token Location field, specify the full path to the bbidtoken.csk file. You must include the
filename. For example: \\shared_server\bb_signing\author.p12.
5. Click Save.

Creating a WebWorks project


You can use the BlackBerry 10 WebWorks SDK web tool or command-line interface to create a project.
A new project includes all the basic resources required to function as a complete app. The folder structure of a
project includes a www folder. This folder is the working directory for your app. All project resource files should
be stored in the www folder, or in the appropriate subfolder. See Folder structure of a WebWorks project on
page 22 for the complete folder structure of a WebWorks project.
Note: By default, your app has no access to any of the Cordova or WebWorks APIs. You need to add plugins to
access the functionality you want your app to have. For more information about plugins and how to add them,
see Adding and removing plugins on page 43.

Create a WebWorks project using the SDK web tool


To create a BlackBerry WebWorks project using the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the navigation panel, click [+] beside the Projects heading.
3. In the Project Name field, enter your application's name.
4. In the Project Path field, enter a project path.
5. Click Create.

Create a WebWorks project from the command line


If you choose, you can create a WebWorks project from the command line instead of from the BlackBerry 10
WebWorks SDK web tool. If you create a project from the command line, the project is not initially available in
the web tool. However, you can import your project into the web tool at any time. For more information, see
Importing a WebWorks 2.0 project into the SDK web tool on page 23.
To create a WebWorks project:
1. On the command line, navigate to the folder where you installed the BlackBerry WebWorks SDK.

Getting Started

21

2. Run the following command to create a WebWorks project:


webworks create <path> [<app-id>] [<app-name>]
For example, the following command creates a project called My App in the c:\webworks-apps\myapp folder:
webworks create c:\webworks-apps\MyApp com.mycompany.myapp "My App"
Check the table below for parameter details:
Parameter

Description

<path>

Specifies the home folder for your project. The tool


creates this folder for you and does not overwrite an
existing folder; if you specify an existing folder, the project
is not created.

<app-id>

Specifies a unique identifier for the app. If provided, this


value is used to populate the id attribute of the
config.xml <widget> element.
Unless you are repackaging an app from another
platform, you should use a reverse DNS format for all
platforms, for example,
id="com.somedomain.HelloWorld".
This parameter is optional.

<app-name>

Specifies the name for the app. To specify a name with


spaces in it, enclose the value in quotation marks ("). If
provided, this value is used to populate the <name>
element in the config.xml file.
This parameter is optional.

Once your project is created, you may want to edit the configuration information, for example, to specify a
particular orientation or background color. For more information, see Modifying your app configuration on page
56.

Folder structure of a WebWorks project


A WebWorks 2.0 project has the following folder structure:

Getting Started

22

Folder

Description

project_root/

This folder is the root folder, which you specify when you create your project.
This folder contains the master config.xml file.

www/

This folder contains all your project resources, including the index.html file,
which is the starting page for your app. It also contains subfolders for various
resources, including CSS and JavaScript files, as well as any other resources you
might add.

merges/

This folder contains platform-specific resources. It should contain a subfolder for


each platform you are creating your app for, which contains a duplicate of
the /www folder structure.
For example, you can store a platform-specific JavaScript file in the project_root/
merges/blackberry10/www/js subfolder. When you build the app for BlackBerry
10, that JavaScript file is used in place of the JavaScript file of the same name in
the project_root/www/js folder.

platforms/

The SDK uses this folder to maintain platform-specific versions of your project.
A blackberry10 folder is automatically created in this folder, and you can add
folders for additional platforms, such as Android or iOS.
When you build your app for a specific platform, the contents of the www/ folder
are copied to the appropriate platform-specific folder.

plugins/

This folder contains any plugins you add to your project. By default, this folder is
empty.
For more information on plugins, see Adding and removing plugins on page 43.

.cordova/

This folder contains Cordova-specific configuration files.

Importing a WebWorks 2.0 project into the SDK web tool


There are instances where an existing WebWorks project is not available from within the WebWorks SDK web
tool. For example, projects that you create from the command line are not displayed in the web tool. In
additions, all WebWorks project content that appears in the tool is stored in browser cookies; deleting these
cookies removes the project data from the web tool.
You can import a WebWorks 2.0 project into the web tool at any time. To import an existing project into the web
tool:

Getting Started

23

1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click the arrow icon beside the Projects heading.
3. In the Project Path field, enter the complete path to the project.
4. Click Open.

Creating your first app


This tutorial will guide you through creating a simple "Hello World" app, and help you verify that you
successfully installed and configured the tools.

You will learn to:


Set up your project
View your app on a simulator
View your app on a device
Note: Before you start, make sure you have the necessary tools installed. For more information, see Setting up
your system on page 12.

Set up your project


To create your project:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Click [+] beside the Recent Projects heading in the navigation panel.
3. Enter Hello World in the Project Name field.
4. Enter C:\TestApps in the Project Path field.
5. Click Create.
The default app project includes all the necessary artifacts to function as a complete app.

View the app on a simulator


Verify the following on your BlackBerry 10 Device Simulator:
Device Password is enabled ( Settings > Security and Privacy > Device Password )
Development Mode is enabled ( Settings > Security and Privacy > Development Mode )
To build your app and deploy it to a simulator:
1. In the BlackBerry 10 WebWorks SDK web tool, under your project's name in the navigation panel, click
Build.
2. Select Debug Mode.
3. Select Simulator.
Getting Started

24

4. Click Build & Install.


The tool packages your app into a .bar file, installs and launches it on your simulator.
The SDK web tool also places an unsigned copy of the .bar file on your computer in the following location:
<your_app_project_directory>\platforms\blackberry10\build\device.

View the app on a device


Before you begin:
Before you can view the app on your device, you must ensure that Development Mode is enabled ( Settings >
Security and Privacy > Development Mode ).
1. In the BlackBerry 10 WebWorks SDK web tool, under your project's name in the navigation panel, click
Build.
2. Select Debug Mode.
3. Select Device.
4. Enter your device password.
5. Enter your keystore password, which you defined when you registered your BlackBerry ID token. If you have
not yet registered your BlackBerry ID token, see Set up your computer for testing and signing.
6. Click Build & Install.
When the tool finishes the build process, it attempts to install the app on the connected BlackBerry device.
Once the app successfully installs on your device and before the app starts for the first time, a dialog box
appears. Click OK on this dialog box to permit the app to access various resources on your device. A dialog box
also appears when the app is opened to inform you that Web Inspector is enabled.
Note: Before the tool installs the app, it checks to see if a debug token is already installed on the device. The
debug token is a signed app that allows you to install and run unsigned apps on a BlackBerry 10 device so you
can debug your apps. If there is no valid debug token installed, the tool creates and installs one for you using
the keystore password you supplied when you set up your app for debugging and signing.
After the build process is finished, the SDK web tool also places an unsigned copy of the .bar file on your
computer in the following location: <your_app_project_directory>\platforms\blackberry10\build\device.

Getting Started

25

Getting Started

26

Porting and Upgrading


Learn how to upgrade from previous versions of BlackBerry WebWorks, port your existing Cordova application,
and port to other platforms.
In this section, you can find out how to upgrade from previous versions of BlackBerry WebWorks, port your
existing Cordova application, and port to other platforms.

Upgrading from WebWorks 1.0


As of BlackBerry 10 OS version 10.2, the BlackBerry WebWorks platform has aligned with the Apache Cordova
project. Although BlackBerry WebWorks 1.0 apps are forward-compatible and will continue to run, there will
be no additional updates to the APIs. Moving forward, you should plan to migrate your app to BlackBerry
WebWorks 2.0.
But don't worry. Migrating your app to the new Cordova-based WebWorks world is pretty simple. Migrating your
app involves the following steps:

Step 1. Download and install the latest BlackBerry 10 WebWorks SDK


You can find the SDK here. For additional information about the tools you need and how to set them up, see
Setting up your system on page 12.
Note: The signing process has changed as of BlackBerry WebWorks 2.0. Unlike BlackBerry WebWorks 1.0,
where a separate token was required to create the developer certificate (used for code signing) and debug
token (used for testing unsigned apps on the device), now a single token is required. This token is associated
with your BlackBerry ID.
For more information on changes to the signing process, see Changes to code signing on page 33.
For more information about getting set up for testing and signing with BlackBerry WebWorks 2.0 or later,
see Setting up your computer for debugging and signing on page 14.

Step 2. Create a BlackBerry WebWorks project


Use the BlackBerry 10 WebWorks SDK web tool to create a project. Once created, the new project includes a
default app with all the basic resources required to function as a complete app. The folder structure of your
new project includes a www folder. This folder is the working directory for your application.
For more information, see Creating a WebWorks project on page 21.

Porting and Upgrading

27

Step 3. Replace the template resources in your new project with your existing resources
Delete the template project resources in your new BlackBerry WebWorks 2.0 project folders and paste your
application resources in their place. All your HTML files should be placed in the www folder; your CSS,
JavaScript, and image files can be placed in the appropriate subfolders of the www folder.
Note: You can choose to copy over your existing config.xml file, or build a new one based on the template
config.xml. However, in either case, you should be aware that the structure of the config.xml file has changed
slightly for BlackBerry WebWorks 2.0 and later. As a result, you may need to make some manual modifications
to your config.xml file. For more information on changes to the config.xml file, see Changes to the config.xml
file on page 31.

Step 4. Add plugins to your project


As of BlackBerry WebWorks 2.0, WebWorks apps use plugins to add APIs to your app. A plugin provides a set
of APIs, and includes the bindings between JavaScript and the native C/C++ layer of the BlackBerry 10 OS. You
need to add a plugin for each of the BlackBerry WebWorks APIs you use in your app. These plugins correspond
to the <feature> elements you added to your old config.xml file.
For more information about plugins, including which you should add and how to add them, see Changes to the
way you add APIs to your app on page 29.

Step 5. Update your source code


Once you have copied over your resources and added the necessary plugins to your project, there are a few
minor code changes that may be required so that your code is compatible with the new architecture:
Include cordova.js instead of webworks.js.
Listen for the deviceready event instead of the webworksready event.
To get all the details on updating your code, see Coding differences on page 32.

Step 6. Build and test


With the previous steps completed, you can begin building and testing your app to make sure that it is
functioning as expected.
Use the BlackBerry 10 WebWorks SDK web tool to build your app in debug mode.
BlackBerry WebWorks 2.0 introduced a number of improvements to the build and deploy process used in
BlackBerry WebWorks 1.0. Now, with a single command, you can create and install a debug token on a
BlackBerry 10 device, and build, install, and launch your app on the device.
See Building and Testing on page 283 to get all the details.

Differences between WebWorks 1.0 and WebWorks 2.0


To understand how to migrate your app from BlackBerry WebWorks 1.0 to BlackBerry WebWorks 2.0 or later,
you should understand the architectural differences between the platforms. The following sections describe
Porting and Upgrading

28

what the changes are and how to make your WebWorks 1.0 app compatible with the latest version of
WebWorks.

Changes to the way you add APIs to your app


As of BlackBerry WebWorks 2.0, WebWorks apps use the same plugin architecture as Apache Cordova. A
plugin provides a set of APIs, and includes the bindings between JavaScript and the native C/C++ layer of the
BlackBerry 10 OS. In Apache Cordova, all communication with the native layer is encapsulated within various
plugins. The BlackBerry 10 WebWorks SDK includes a number of plugins, each providing access to a different
feature of the platform.
In your BlackBerry WebWorks 1.0 project, you handled access to the various APIs of the BlackBerry platform
by adding <feature> tags to your config.xml file. At build time, the packager looked at the <feature>
elements in the config.xml file to determine which BlackBerry WebWorks APIs to bundle with the app.
As of BlackBerry WebWorks 2.0, however, you access an API by adding the appropriate plugin to your project.
When you add a plugin, the WebWorks tools add the plugin to the /plugins folder. You can determine which
plugins you need to add by looking at the <feature> elements in your old config.xml file; each <feature>
element maps to a corresponding BlackBerry plugin.
Plugins can be added either from the BlackBerry 10 WebWorks SDK web tool, or from the command line.
To use the BlackBerry 10 WebWorks SDK web tool, open BlackBerry WebWorks <version>, then click the
Plugins button under your project's name in the navigation panel.
To use the command line, navigate to your project folder and then run:
webworks plugin add <id>
where <id> specifies the unique identifier for the plugin.

A note about using HTML5 notifications


You should be aware that if you used HTML5 notifications in your previous app, you need to add a plugin to
access this functionality, even though it required no <feature> element previously. To access the same
functionality, add the com.blackberry.notification plugin to your app.
Mapping BlackBerry WebWorks plugins to BlackBerry features
The following table outlines how BlackBerry WebWorks plugins map to the <feature> element entries in
your existing config.xml file.
If you added this <feature> element:

You need to add this plugin:

<feature id="blackberry.app" />

com.blackberry.app

Porting and Upgrading

29

If you added this <feature> element:

You need to add this plugin:

<feature
id="blackberry.bbm.platform" />

com.blackberry.bbm.platform

<feature
id="blackberry.connection" />

com.blackberry.connection

<feature id="blackberry.identity" />

com.blackberry.identity

<feature
id="blackberry.identity.phone" />

com.blackberry.user.identity

<feature id="blackberry.invoke" />

com.blackberry.invoke

<feature
id="blackberry.invoke.card" />

com.blackberry.invoke.card

<feature id="blackberry.invoked" />

com.blackberry.invoked

<feature id="blackberry.io" />

com.blackberry.io

<feature
id="blackberry.io.filetransfer" />

The com.blackberry.io.filetransfer plugin


has been deprecated since BlackBerry WebWorks
2.2. Modify your app to use
org.apache.cordova.file-transfer
instead.

<feature id="blackberry.payment" />

com.blackberry.payment

<feature
id="blackberry.pim.calendar" />

com.blackberry.pim.calendar

<feature
id="blackberry.pim.contacts" />

com.blackberry.pim.contacts

<feature id="blackberry.push" />

com.blackberry.push

<feature id="blackberry.sensors" />

com.blackberry.sensors

<feature id="blackberry.system" />

com.blackberry.system

<feature
id="blackberry.system.event" />

No longer supported. Event listeners must now be


added to and removed from the document object.
For backwards compatibility, events added to the
sytem.event object are mapped to the document
object, so no coding changes are required.

<feature
id="blackberry.ui.contextmenu" />

com.blackberry.ui.contextmenu

Porting and Upgrading

30

If you added this <feature> element:

You need to add this plugin:

<feature id="blackberry.ui.cover" />

com.blackberry.ui.cover

<feature id="blackberry.ui.dialog" />

com.blackberry.ui.dialog

<feature id="blackberry.ui.toast" />

com.blackberry.ui.toast

Changes to the config.xml file


Although BlackBerry WebWorks 1.0 and BlackBerry WebWorks 2.0 or later both use a config.xml file to store
configuration information for your project, how they are created and used differs slightly.
As of BlackBerry WebWorks 2.0, if you need to manually edit the config.xml file, you can find it your project's
root folder.

Reduced need to manually edit the config.xml file


With BlackBerry WebWorks 2.0 or later, there is little need for you to edit the config.xml file manually. Most of
the configuration settings can be manged through the BlackBerry 10 WebWorks SDK web tool. A config.xml
file is created automatically and prepopulated with template configuration information when you create your
project.
You can use the BlackBerry 10 WebWorks SDK web tool to customize the contents of the file. Clicking
BlackBerry WebWorks <version> on the Start menu opens the BlackBerry 10 WebWorks SDK web tool. You
can click the Configuration button under your project's name in the navigation panel to view and edit most of
your app's configuration settings, including the metadata, orientation, background color, and more. The web
tool also allows you to add your plugins, and allows you to set any necessary plugin permissions.
The only instance where you need to manually edit the config.xml file is if you want to set up your app as an
invocation target. In this case, you must still manually add the <rim:invoke> element and its children to
register the app as an invocation target and to define which file types your app can handle.

No need to add <feature> elements to the config.xml file


If you intend to reuse your existing config.xml file, there is no longer any need to add <feature> elements to
the config.xml file. The BlackBerry WebWorks tools now handle adding these elements at build time, based on
which plugins you've added to your project. For best results, once you have added the required plugins to your
project, you should remove all <feature> elements from your existing config.xml.

The <preference> element replaces the <param> element


How you set the configuration parameters associated with the Application API (for example, to define the app
orientation or background color) has changed as of BlackBerry WebWorks 2.0.

Porting and Upgrading

31

In BlackBerry WebWorks 1.0, you would define these configuration parameters by adding the following
elements to your config.xml file:
<feature id="blackberry.app">
<param name="orientation" value="portrait" />
</feature>
As of BlackBerry WebWorks 2.0, you must define these parameters using <preference> elements, which
are children of the top-level <widget> element. For example, to set the orientation as in the example above,
your config.xml file should now contain the following code:
<widget>
.
.
.
<preference name="orientation" value="portrait" />
</widget>
If you choose, you can set all preferences directly in the BlackBerry 10 WebWorks SDK web tool.
For more information on how to add the <preference> element to the config.xml file manually, see
<preference> on page 84.

Coding differences
If you have previously created a BlackBerry 10 WebWorks 1.0 app, it needs only a few small coding changes to
make it compatible with BlackBerry WebWorks 2.0 or later.

Include cordova.js instead of webworks.js


In BlackBerry WebWorks 1.0 apps, you needed to include webworks.js to launch the BlackBerry WebWorks
application runtime. For example:
<script src="local:///chrome/webworks.js" type="text/javascript"></script>
In BlackBerry WebWorks 2.0 ad later, you include cordova.js instead. You should replace all instances of
webworks.js with cordova.js. For example:
<script src="local:///cordova.js" type="text/javascript" ></script>

Listen for the deviceready event instead of the webworksready event


In BlackBerry WebWorks 1.0 apps, your app needed to listen for the webworksready event, and could not
call any BlackBerry WebWorks APIs until the event had occurred. For example:
document.addEventListener('webworksready', function(e) {
.
Porting and Upgrading

32

.
.
}
In BlackBerry WebWorks 2.0 or later, your projects need to listen for the deviceready event instead. You
should replace all instances of webworksready with deviceready. For example:
document.addEventListener('deviceready', function(e) {
.
.
.
}

Changes to code signing


Signing apps has changed from BlackBerry WebWorks 1.0. The signing process has been streamlined; simply
building the app in release mode results in a signed application. More significantly, as of BlackBerry WebWorks
2.0, the WebWorks SDK uses the BlackBerry ID token for signing, which associates your keystore with your
BlackBerry ID.
As of BlackBerry WebWorks 2.0, to sign WebWorks apps, you need to create a BlackBerry ID token
(bbidtoken.csk) and use it to create a developer certificate. The resulting certificate is used to sign your
release-ready code, and also to create debug tokens that allow you to test your app on a BlackBerry device.
For more information about getting and using the BlackBerry ID token, see Setting up your computer for
debugging and signing on page 14.
If you are updating an earlier version of your app that was signed using a signing authority token, you can link
that token to your BlackBerry ID token (bbidtoken.csk). By linking these accounts, your updated BlackBerry
WebWorks app keeps continuity with the previous versions of your app and appears to end users as an update,
rather than a new app altogether.
Linking your BlackBerry ID token to a signing authority account
You can link your BlackBerry ID token to an existing signing authority account. Linking the two accounts allows
you to produce .bar files with the same Package-Author-Id, Package-Id, and Application-Id, so that you can
create upgraded versions of your existing app.

Link accounts using the SDK web tool


1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click Certificate.
3. In the Location field, enter the full path to your barsigner.csk file.
4. Click Add Signing Key. The Link Signing Keys fields appear.
5. In the BBID Signing Token Location field, enter the full path to your bbidtoken.csk file.
6. In the Barsigner Password field, enter the password associated with your barsigner.csk.
7. In the BBID Signing Token Password field, enter your BlackBerry ID token password.
Porting and Upgrading

33

8. Click Link Signing Keys. The developer certificate (the author.12 file) is created in the same location as
your signing key.

Link accounts using the command line


When using the command-line tools, you have a few options:
Link your barsigner.csk to the bbidtoken.csk, where both passwords are same:
blackberry-signer -linkcsk cskpass <Legacy CSK password or BBID Token
CSK password>
Link your barsigner.csk to the bbidtoken.csk, where bbidtoken.csk is in a custom location and both
passwords are the same:
blackberry-signer -linkcsk bbidtoken <BBID Token CSK filename>
cskpass <Legacy CSK password or BBID Token CSK password>
Link your barsigner.csk to the bbidtoken.csk, where both are in the default directory:
blackberry-signer -linkcsk oldcskpass <Legacy CSK password>
bbidcskpass <BBID Token CSK password>

Where did the Ripple emulator go?


The documentation for previous releases of BlackBerry WebWorks placed a lot of emphasis on the Ripple
emulator. If you used the Ripple emulator before, you'll probably notice that it is no longer discussed within the
BlackBerry WebWorks documentation. The reason for this is that BlackBerry has recently donated Ripple to
the Apache open source comunity. As a result, BlackBerry is no longer in control of Ripple development or
release cycles.
Work is still progressing on Ripple within the Apache community. At the moment, however, Ripple is not
compatible with Apache Cordova 3.x, upon which BlackBerry WebWorks is based, so it cannot currently be
used to test your BlackBerry WebWorks app. For future updates on Ripple, see http://
ripple.incubator.apache.org/#download.

Updating your WebWorks project


As of BlackBerry 10 WebWorks SDK 2.2, when you open a project, WebWorks will check to determine whether
that project was created using the latest version of the SDK. If the project uses an earlier version, you can use
the upgrade command to update the project to the latest version of BlackBerry WebWorks. While updating is
optional, it helps keep your projects' build support files in sync with the latest version of the WebWorks build
system.
Note: The updating process only updates the build support components. To update BlackBerry WebWorks
plugins, you must remove and re-add each plugin.
Porting and Upgrading

34

If updating your project breaks your project, submit a bug report using the Developer Issue Tracker.

Update project using the SDK web tool


To update your BlackBerry WebWorks project using the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the navigation panel, select the project and click Configuration.
3. Under the Updates field, click the update icon.

Update project from the command line


You can update your BlackBerry WebWorks project from the command line.
1. On the command line, navigate to the folder containing your BlackBerry WebWorks SDK project.
2. Run the following command to update your BlackBerry WebWorks project:
webworks upgrade

Porting from Cordova


BlackBerry WebWorks SDK 2.0 is built upon the Cordova open source project with custom BlackBerry plugins
and features. This shift increases the portability of BlackBerry WebWorks applications and makes it easy to
integrate with the BlackBerry 10 OS. Essentially, BlackBerry WebWorks SDK 2.0 consists of Cordova and
BlackBerry specific APIs as well as a custom CLI and GUI.

Porting and Upgrading

35

Use the WebWorks CLI


The BlackBerry WebWorks CLI provides custom commands for developing and testing BlackBerry
applications.
To use a BlackBerry WebWorks command, run webworks <command>, where <command> is one of the
following:
The build command builds your app in release mode or debug mode, without deploying it to a simulator
or device.
The serve command lets your preview your app in your default browser.
The emulate command builds and deploys your app to a BlackBerry 10 Device Simulator.
The run command builds and deploys your app to a BlackBerry 10 device. This command also create and
install a debug token automatically.
Both the emulate and run commands also let you specify whether you want to skip the build or launch steps.

Porting and Upgrading

36

Add BlackBerry plugins


BlackBerry 10 WebWorks SDK 2.0 contains BlackBerry specific APIs that allow applications to tightly integrate
with the BlackBerry 10 OS. You will need to use BlackBerry plugins to access core BlackBerry funtionality. For
a full list of BlackBerry plugins, see Plugins installed with BlackBerry 10 WebWorks SDK on page 8.
To add a BlackBerry plugin using the BlackBerry WebWorks CLI:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks plugin add <id> | <path> | <uri>
For example, the following example adds the BlackBerry Application API to your app.
webworks plugin add com.blackberry.app
Check the table below for parameter details:
Parameters

Description

<id>

Specifies the unique identifier for the plugin.

<path>

Specifies the path to the plugin on your local file


system.

<uri>

Specifies the remote location for the plugin.

Add BlackBerry plugins using the Cordova CLI


You can add BlackBerry plugins to your app without installing the BlackBerry WebWorks SDK by using the
Cordova CLI.
Visit http://plugins.cordova.io/ to download the plugins and learn how to add them using the Cordova command
line interface.

Porting to other platforms


Now that the BlackBerry WebWorks SDK is built on Apache Cordova, it is easier than ever to bring your apps to
multiple platforms. Using the Apache Cordova CLI, you can port your app to a number of platforms, including:
iOS
Android
Porting and Upgrading

37

Windows Phone 7 & 8


Windows 8
Firefox OS

Adding platforms to your project


To build your BlackBerry WebWorks app for other platforms, you need to download the SDKs for your targeted
platform(s) and the Apache Cordova tools. Once the SDKs and Cordova tools are installed, you add other
platforms to your project.
To add an additional platform, use the cordova platform add command. For a complete porting
walkthrough, see the Apache Cordova documentation.
Note: You can skip the Create the App step since you have already created your app using the BlackBerry
WebWorks SDK.

Add compatible features


Plugins for the BlackBerry WebWorks SDK are not compatible with other operating systems. To achieve the
same functionality across multiple platforms, you will need to find and add similar plugins for each platform
you port to. For example, to enable payment services for Android you might add the Google Play In-App Billing
plugin to achieve the same functionality as the Payment plugin for BlackBerry WebWorks.
Note: Adding plugins for other platforms may require you to make some changes to your source code.

Using PhoneGap
PhoneGap is an alternative tool for packaging and porting your app to multiple platforms. It is also based on
Apache Cordova, so your source code will not need to be changed. PhoneGap can be used either as a set of
command line tools or as a web service that packages and builds your app remotely. For a complete overview,
see the PhoneGap documentation.

Porting AIR apps to WebWorks


With the end of support for the Adobe AIR runtime on BlackBerry 10 OS version 10.3.1, one way to keep your
app available on BlackBerry 10 is to port your AIR app to HTML5, the development language of BlackBerry
WebWorks apps. With your app refactored in HTML5, you can use the BlackBerry 10 WebWorks SDK to
package the app as a .bar file.
Although the BlackBerry Runtime for Android apps continues to support AIR apps packaged as Android apps,
in some cases, converting your app to HTML5 and creating a WebWorks app may be the only migration path
available.
If your AIR app uses any AIR Native Extensions (ANEs) to extend the capabilities of the AIR runtime, then
only by converting to a WebWorks solution can you achieve the same level of functionality. The Android
runtime does not permit ANEs to connect with the BlackBerry native APIs.

Porting and Upgrading

38

If your app is deployed within the work perimeter, then a WebWorks solution is the only viable alternative,
since Android apps are not permitted within the work perimeter.
Porting your AIR app to HTML5 actually provides a couple of additional built-in benefits:
HTML5 apps offer greater cross-platform compatibility than AIR apps. Most mobile platforms support
HTML5 apps to varying degrees, while AIR apps are only supported by Android devices, and on BlackBerry
devices as Android apps.
HTML5 apps are more future-proof than AIR apps. HTML5 is quickly emerging as the future of web
development.
There are several steps involved in porting your AIR app to WebWorks. Here's a summary of the process:
1.
2.
3.
4.
5.
6.
7.

Convert your Flash content to HTML5 on page 39


Create a BlackBerry WebWorks project on page 40
Add your HTML5 resources to your WebWorks project on page 40
Rebuild your AIR Native Extensions as Cordova plugins on page 40
Add plugins to your project on page 41
Set configuration settings for your project on page 41
Build and test your app on page 41

Before you begin


If you are new to BlackBerry WebWorks, before you start to port your app, look at the Getting Started on page 5
section of the WebWorks documentation to get information on:

What a WebWorks app looks like


What you can expect to receive as part of the BlackBerry 10 WebWorks SDK
How to get the tools and how to set up your computer to use them
How to create a WebWorks project
How to create a basic HelloWorld app

Convert your Flash content to HTML5


Although BlackBerry doesn't offer tools to assist with Flash conversion, there are several third-party options
available. Some Flash-to-HTML5 conversion options include:
PixelPlant: PixelPlant is a service that converts your .swf files to HTML5 for you. You upload your Flash
content, and they return it in HTML5 format. For more information, see pixelplant.com.
CreateJS: CreateJS is a suite of JavaScript libraries that are designed to create rich content and animations
using HTML, CSS, and JavaScript. Because the CreateJS libraries are modeled after Adobe ActionScript
APIs, much of the scripting logic can be reused with only minor changes. For more information, see
createjs.com.
There may be other options that are better suited to your needs. You should thoroughly investigate all options
and determine which one works best for you. In any case, you should be prepared to make at least some
manual changes to your content to make it HTML5-ready.

Porting and Upgrading

39

Create a BlackBerry WebWorks project


If you haven't done so already, download and install the BlackBerry 10 WebWorks SDK (for additional
information about the tools you need and how to set them up, see Setting up your system on page 12).
Once it is installed and set up, use the BlackBerry 10 WebWorks SDK web tool to create a WebWorks project:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Click [+] beside the Projects heading in the navigation panel.
3. In the Project Name field, enter a name for your project. The project is identified within the web tool with
this name.
4. In the Project Path field, enter a project path. This path specifies the folder location where your project
resources are stored.
5. Click Save.
Your new project is created with a complete set of template resources that you can build into a functioning
app.

Add your HTML5 resources to your WebWorks project


Once you've converted your Flash content to HTML5 and created your WebWorks project, you need to add
your HTML5 content files to the WebWorks project folders.
To add your HTML5 content to your WebWorks project:
1. In your WebWorks project folder (which you defined in the Project Path field when you created your
project), locate the www folder.
2. Delete the template project resources in the www folder and its subfolders and paste your HTML5 content
and other app resources in their place. Make sure that files are copied to the correct locations:
HTML files should be copied to the www folder.
CSS, JavaScript, and image files should be copied to the appropriate subfolders of the www folder.

Rebuild your AIR Native Extensions as Cordova plugins


If you used AIR Native Extensions in your AIR app, there is no direct path for porting those extensions to
WebWorks. You must rebuild your ANE as a custom Cordova plugin.
WebWorks actually provides greater access to the native features of the BlackBerry 10 OS than the AIR
runtime. Before creating a custom plugin, check the existing plugins installed with the SDK to see if they
provide access to the features you need. In addition, members of the WebWorks community have also made
custom plugins available that may achieve what you need. You can see the complete list of standard and
community-created plugins in the Cordova plugins registry by searching for plugins with the com.blackberry
prefix.
If you do need to create a custom plugin, there are a few resources that can help you:
To learn the basics, check out the Creating a Cordova plugin for BlackBerry 10 on page 49 tutorial. This
tutorial walks you through the construction of the basic Echo plugin.
Porting and Upgrading

40

When you are ready to create your own custom plugin, start with the BlackBerry template for Cordova
plugins.

Add plugins to your project


If you are primarily an AIR or Flash developer, the concept of plugins may be a little foreign. In a WebWorks
app, a plugin provides a set of APIs, together with the bindings between JavaScript and the native C/C++ layer
of the BlackBerry 10 OS. In Apache Cordova, upon which BlackBerry WebWorks is built, all communication
with the native layer is encapsulated in a number of plugins. Because of this architecture, you need to add a
plugin for each of the BlackBerry WebWorks APIs you want to access within your app.
To add a plugin to your project using the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Plugins.
3. Enter the ID or URL of the plugin in the Plugin Name or URL field.
4. Click Add Plugin.

Set configuration settings for your project


You can define aspects of your app, such as its orientation or background color, by configuring your app
preferences. You can configure your app preferences using the BlackBerry 10 WebWorks SDK web tool, or you
can edit the config.xml file. For information on editing the config.xml file, see Modifying your config.xml file on
page 68.
To set your app preferences with the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Config.
3. Complete the fields for the preferences you would like to set. For a complete description of all the
configuration settings, see Configuring your app preferences on page 56.

Build and test your app


With the previous steps completed, you can begin building and testing your app to make sure that it functions
as expected. You can test your app using either a BlackBerry 10 device or the BlackBerry 10 Device Simulator.
For now, we'll test the app using the simulator.
Note: If you have a BlackBerry 10 device, you can install and run your app directly on the device by following
the steps outlined at Deploying your app to a device on page 289.
Before you begin:
Make sure the BlackBerry 10 Device Simulator is installed and running on your computer. If you haven't
already downloaded it, you can get the simulator here.

Porting and Upgrading

41

1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. Select Simulator.
5. Enter the device password used by your simulator.
6. Click Build & Install.
The tool packages your app into a .bar file, installs it on your simulator, and opens it.
When you are satisfied with the app and are ready to sign and distribute it, see Building and signing your
completed app on page 316.

Porting and Upgrading

42

Adding Features
Learn how to add plugins to your app and implement unique BlackBerry features.
In this section, you'll learn how to add plugins to your app and implement unique BlackBerry features.

Adding and removing plugins


To access Cordova and BlackBerry functionality, you need to add plugins to your project. Plugins represent the
layer that connects JavaScript to the native C/C++ layer of the BlackBerry 10 OS. They allow you to access the
native functionality of the device (for example, accessing accelerometer data, or using the camera) without the
need to code in the device's native language.
When you add a plugin to your project, it is added to your project's plugins/ subfolder and packaged with your
app. To keep the size of your app small, add only the plugins that you need.
When you install the BlackBerry 10 WebWorks SDK, the installation includes the BlackBerry and Cordova
plugins. You can find them in the plugin/ subfolder of the BlackBerry 10 WebWorks SDK installation folder.
You can create your own plugins or access plugins created by the WebWorks community to access native APIs
that are not available through the BlackBerry and Cordova plugins. For more information, see Using custom
plugins on page 48.

Adding plugins using the SDK web tool


To add a plugin to your project using the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Plugins.
3. Enter the ID or URL of the plugin in the Plugin Name or URL field.
4. Click Add Plugin.

Adding plugins from the command line


Add a plugin
You can use the plugin add command to add a plugin to your project. You can add a plugin by ID, path, or
URI.
To add a plugin to your app:
1. On the command line, navigate to your project folder.
Adding Features

43

2. Run the following command:


webworks plugin add <id> | <path> | <uri>
For example, the following command adds the BlackBerry Application API to your app.
webworks plugin add com.blackberry.app
Check the table below for parameter details:
Parameter

Description

<id>

The unique identifier for the plugin.

<path>

The path to the plugin on your local file system.

<uri>

The remote location for the plugin.

Remove a plugin
You can use the plugin rm command to remove a plugin from your project.
To remove a plugin from your project:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks plugin rm <id>
Check the table below for parameter details:
Parameters

Description

<id>

Specifies the unique identifier for the plugin.

List your installed plugins


To list the plugins you have previously added to your app:
1. On the command line, navigate to your project folder.

Adding Features

44

2. Run the following command:


webworks plugin ls

Standard WebWorks and Cordova plugins


The following plugins are installed with the BlackBerry 10 WebWorks SDK.

BlackBerry WebWorks plugins


Plugin ID

Name

Description

com.blackberry.app

Application

Provides basic app support.

com.blackberry.bbm.platfor BBM Platform


m

Lets you access the social features and


functionality of BBM.
Required permission: bbm_connect

com.blackberry.connection

Connection

Lets you access the cellular and Wi-Fi


connection information for the BlackBerry
device.

com.blackberry.display

Display

Allows you to control whether the screen dims


while the app is in the foreground.

com.blackberry.identity

Identity

Provides information about the user's identity


and accounts.
Required permission:
read_device_identitying_information

com.blackberry.ui.input

Input

Lets your app respond to user events on a


touch-enabled keyboard. This is a new input
event layer for use with touch-enabled
keyboards beginning with BlackBerry 10.3. It is
unrelated to DOM mouse events or HTML5
touch events on the screen.

com.blackberry.invoke

Invoke

Lets your app invoke and interact with other


apps on the device.

com.blackberry.invoke.card Card

Lets your app invoke a screen of another app on


the device.

Adding Features

45

Plugin ID

Name

Description

com.blackberry.invoked

Invoked

Lets your app be invoked by other apps on the


device.

com.blackberry.io

IO

Provides access to folders on the device.

com.blackberry.io.filetransfe
r

Deprecated since BlackBerry WebWorks 2.2.


Use org.apache.cordova.file-transfer instead.

com.blackberry.notification

Lets your app provide notifications to the user.

Notification

Required permission: post_notification


com.blackberry.payment

Payment

com.blackberry.pim.calenda Calendar
r

Lets you sell digital goods in your app.


Lets you access and manage entries in the
Calendar application.
Required permission:
access_pimdomain_calendars

com.blackberry.pim.contact Contacts
s

Lets you create and find contacts.

com.blackberry.push

Lets you access the BlackBerry push


architecture to receive push content in your
app.

PushPayload
PushService

Required permission:
access_pimdomain_contacts

Required permissions:
sys_use_consumer_push
run_when_backgrounded
com.blackberry.screenshot

Screenshot

Lets you capture an image of the device screen.

com.blackberry.sensors

Sensors

Lets you get access to system level sensors and


attributes of the BlackBerry device.

com.blackberry.system

System

Lets you access system level functions and


attributes of the BlackBerry device.

com.blackberry.ui.contextm Context Menu


enu

Lets you control whether context menus are


enabled, listen to events, add items to appear
based on the context, and set the theme of the
context menu.

Adding Features

46

Plugin ID

Name

Description

com.blackberry.ui.cover

Window Covers

Lets you modify the app's window cover, which


is displayed when the app is in thumbnail mode.

com.blackberry.ui.dialog

Dialog

Lets you manipulate system dialog boxes.

com.blackberry.ui.toast

Toast

Lets you display system toasts in your app.

com.blackberry.user.identity User Identity

Lets you access the user's personal information


stored in the identity provider's account system,
and provide user authentication/authorization
to access the identity provider's apps and
services.

Cordova plugins installed with BlackBerry WebWorks SDK


Plugin ID

Name

Description

org.apache.cordova.battery- Events (Battery Status)


status

Provides an implementation of an old version of


the Battery Status Events API.

org.apache.cordova.camera Camera

Provides access to the device's default camera


application.

org.apache.cordova.contact Contacts
s

Provides access to the device's contact


database.

org.apache.cordova.device

Describes the device's hardware and software.

Device

org.apache.cordova.device- Device Motion


motion
(Accelerometer)

Captures device motion along the x, y, and z


axes.

org.apache.cordova.device- Device Orientation


orientation
(Compass)

Obtains the direction that the device is pointing.

org.apache.cordova.dialogs

Notification (Dialogs)

Lets your app create visual, audible, and tactile


notifications.

org.apache.cordova.file

File System

Provides the functionality to read, write, and


navigate file system hierarchies.

org.apache.cordova.filetransfer

File Transfer

Lets you upload and download files.

Adding Features

47

Plugin ID

Name

Description

org.apache.cordova.geoloca Geolocation
tion

Provides access to location information based


on the device's GPS sensor or inferred from
network signals.

org.apache.cordova.inappbr InAppBrowser
owser

Provides a browser view that displays when


calling window.open(), or when opening a
link formed as <a target="_blank">.

org.apache.cordova.media

Media

Lets your app play back audio and video files on


a device.

org.apache.cordova.mediacapture

Media

Provides access to the device's audio, image,


and video capture capabilities.

org.apache.cordova.network Network Information


-information
(Connection)

Provides information about the device's cellular


and Wi-Fi connection.

org.apache.cordova.splashs Splashscreen
creen

Lets your app hide and show the splash screen.

org.apache.cordova.vibratio Notification (Vibration)


n

Lets your app create visual, audible, and tactile


notifications.

Using custom plugins


When it comes to accessing the native features of the device, you are not limited to the selection of plugins that
is installed with the SDK. You can use a custom plugin created by a member of the WebWorks community. Still
don't see what you need? You can create your own plugins to access native APIs that are not available through
existing plugins.

Creating custom plugins


Although a BlackBerry web app has a wide range of functionality, that functionality is limited to the resources
that the app contains and the functionality available through the existing BlackBerry and Cordova plugins. By
creating a custom plugin, you can extend the functionality of your app to include the features and functions
provided by core native APIs, like those available to native apps on the BlackBerry 10 OS.
You create a custom plugin in C/C++, the native development languages for BlackBerry 10 OS, and then you
wrap it in JavaScript. When you build and package your web app for BlackBerry, you include the plugin source
files along with other assest of your app in the package. This enables you to use JavaScript to access the
plugin's functionality from within your app at any time. Using the extended function, you can pass arguments
and handle return values, like you would in any native BlackBerry 10 app.
Adding Features

48

Creating a Cordova plugin for BlackBerry 10


An Apache Cordova plugin for BlackBerry 10 is composed of a Cordova JavaScript interface and native
implementations of a BlackBerry specific plugin interface that the JavaScript calls into.
JavaScript is the entry point for the plugin. The JavaScript interface is front-facing and is the most important
part of your Cordova plugin. In a Cordova plugin for BlackBerry 10, the native and JavaScript code
communicate with each other through a framework provided by JNEXT. Every plugin must also include a
plugin.xml file.
You can structure your plugin's JavaScript according to your preference. However, you must use the
cordova.exec function to communicate between the Cordova JavaScript and the BlackBerry native
environment. The cordova.exec function has the following signature:
exec (<successFunction>, <failFunction> , <service> , <action> , [< args
>]);
Here is an example of the cordova.exec function with an explanation of its parameters:
cordova.exec(function(winParam) {}, function(error) {}, "service",
"action", ["firstArgument", "secondArgument", 42,
false]);
Let's take a look at each of the parameters through this example:
function(winParam) {} - Success function callback. Assuming your exec call completes
successfully, this function is invoked (optionally with any parameters you pass back to it).
function(error) {} - Error function callback. If the operation does not complete successfully, this
function is invoked (optionally with an error parameter).
"service" - The service name to call into on the native side. This is mapped to a native class in the
plugin.
"action" - The action name to call into. This is picked up by the native class receiving the exec call, and
essentially maps to a class's method.
[/* arguments */] - Arguments to get passed into the native environment.
Echo Plugin example
To demonstrate how to create a Cordova plugin for BlackBerry 10, let's use a very simple plugin named Echo.
The Echo plugin demonstrates how to invoke native functionality from JavaScript. The plugin passes a string
from JavaScript and sends it into the native environment. The native code then returns the same string (that is,
echoes it) back into the callbacks inside the plugin's JavaScript.
Note: Although this Echo tutorial is useful to help you understand the steps required to create a custom plugin,
it is intentionally basic, and not intended as a template for you to follow. When you are ready to create your own
custom plugin, we recommend that you start with the BlackBerry plugin template, which you can find here.

Adding Features

49

Below is the JavaScript sample code showing the use of the cordova.exec function. We attach the plugin to
window, specifically to the echo function:
window.echo = function(str, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "Echo", "echo", [str]);
};
Let's take a detailed look at the last three arguments to the exec function. Here, the exec function is calling
the "Echo" service, requesting the "echo" action, and passing the array containing the "str" argument. The
string str represents the string that is to be echoed and is the first parameter into the window.echo
function. Note that the success callback passed into the exec function is simply a reference to the callback
function that window.echo takes (it's the second parameter).
We do a bit more for the error callback. If the native side fires off the error callback, we simply invoke the
success callback and pass into it a default string to echo back and indicate that an error has occured (using
the string 'Nothing to echo.').
For example, you can use this plugin as follows:
window.echo("echome", function(echoValue) {
alert(echoValue == "echome"); // should alert true, if there is no
error
});
We can now use what we learned about the cordova.exec function and create an Echo plugin for the
BlackBerry 10 platform.
Creating the JavaScript part of your plugin
The JavaScript portion of your plugin must contain a client.js and an index.js file:
client.js This is considered the client side and contains the API that a Cordova application can call. The
API in client.js makes calls to index.js. The API in client.js also connects callback functions to the events
that fire the callbacks.
index.js This is considered the server side. Cordova loads index.js and makes it accessible through the
cordova.exec bridge. The client.js file makes calls to the API in the index.js file, which in turn makes
calls to JNEXT to communicate with the native side.
var service = "org.apache.cordova.blackberry.echo",
exec = cordova.require("cordova/exec");
module.exports = {
echo: function (data, success, fail) {
exec(success, fail, service, "echo", { data: data });
}
};

Adding Features

50

Create the client.js file


The client and server sides (client.js and index.js) interact through the cordova.exec() function.
In client.js you invoke the exec() function and provide the necessary arguments. In the Echo plugin, we
have the following in the client.js file:
var service = "org.apache.cordova.blackberry.echo",
exec = cordova.require("cordova/exec");
module.exports = {
echo: function (data, success, fail) {
exec(success, fail, service, "echo", { data: data });
}
};
Create the index.js file
index.js interacts with the native side using JNEXT. So, you attach your constructor function to JNEXT. In our
sample Echo plugin, we attach the Echo() constructor to JNEXT. Now, we have to complete the Echo()
constructor and the echo() function.
1. In your constructor, use the init() function to perform some key operations:
a) Specify the required module exported by the native side. The name of the required module must match
the name of a shared library file (.so file).
JNEXT.require("libecho")
a) Create an object by using the acquired module and save the ID that's returned by the call.
self.m_id = JNEXT.createObject("libecho.Echo");
Here is the constructor from our sample Echo plugin:
var echo;
echo = new JNEXT.Echo();
JNEXT.Echo = function () {
var self = this,
hasInstance = false;
self.echo = function (text) {
return JNEXT.invoke(self.m_id, "echo " + text);
};
self.init = function () {
if (!JNEXT.require("libecho")) {
return false;
}
self.m_id = JNEXT.createObject("libecho.Echo");
if (self.m_id === "") {
return false;
Adding Features

51

}
};

JNEXT.registerEvents(self);

self.m_id = "";

};

self.getInstance = function () {
if (!hasInstance) {
self.init();
hasInstance = true;
}
return self;
};

2. When your application calls the echo function in client.js, that call in turn calls the echo function in
index.js, where the PluginResult object sends a response (data) back to client.js. Since the args
argument passed into the functions was converted by JSON.stringfy() and encoded as a
URIcomponent, you must decode the data before you send it with the response:
data = JSON.parse(decodeURIComponent(args.data));
Now we are ready to send the data back. Here's how it turns out when you put it all together:
module.exports = {
echo: function (success, fail, args, env) {

};

var result = new PluginResult(args, env),


data = JSON.parse(decodeURIComponent(args.data)),
response = echo.getInstance().echo(data);
result.ok(response, false);

Creating the native part of your plugin


To create the native portion of your plugin, in the BlackBerry 10 Native SDK, do the following:
1. On the File menu, click New > BlackBerry Project > Native Extension > BlackBerry WebWorks and click
Next.
2. In the Project name field, type a name for the project (for example, echo) and click Finish.
The SDK creates a native extension project and displays it in your Workbench.
System requirements
To create custom plugins to use with your web apps on BlackBerry 10 OS, you require the following:
BlackBerry 10 Native SDK 10.2 or later
Apache Cordova for BlackBerry 2.8 or later

Adding Features

52

Updating the sample code


The native extension project you create using the BlackBerry Project wizard in the IDE contains code for a
sample plugin called the memory extension plugin. Replace or modify the files in the project to add functionaly
according to your needs:
memory_js.hpp - C++ header for the JNEXT code.
memory_js.cpp - C++ code for JNEXT.
The native interface for the JNEXT extension can be viewed in the plugin header file located in the public folder
of your project. It also contains constants and utility functions that can be used in your native code. Your plugin
must be derived from JSExt, which is defined in plugin.h. That is, you must implement the following class:
class JSExt
{
public:
virtual ~JSExt() {};
virtual string InvokeMethod( const string& strCommand ) = 0;
virtual bool CanDelete( void ) = 0;
private:
std::string m_id;
};
Therefore, your extension should include the plugin.h header file. In the Echo example, you use JSExt as
follows in the echo_js.hpp file:
#include "../public/plugin.h"
#include <string>
#ifndef ECHO_JS_H_
#define ECHO_JS_H_
class Echo : public JSExt
{
public:
explicit Echo(const std::string& id);
virtual ~Echo();
virtual std::string InvokeMethod(const std::string& command);
virtual bool CanDelete();
private:
std::string m_id;
};
#endif // ECHO_JS_H_
m_id: The m_id is an attribute that contains the JNEXT ID for this object. The ID is passed to the class as
an argument to the constructor. It is needed to trigger events on the JavaScript side from native.
CanDelete(): The CanDelete() method is used by JNEXT to determine whether your native object can
be deleted.

Adding Features

53

InvokeMethod(): The InvokeMethod() function is called when JavaScript invokes a method of this
particular object. The only argument this function takes is a string passed from JavaScript that
InvokeMethod() parses in order to determine which method of the native object should be executed.
Now we implement these functions in echo_js.cpp. For the Echo example, we implement the
InvokeMethod() function as follows:
string Echo::InvokeMethod(const string& command) {
//parse command and args from string
int index = command.find_first_of(" ");
string strCommand = command.substr(0, index);
string strValue = command.substr(index + 1, command.length());

// Determine which function should be executed


if (strCommand == "echo") {
return strValue;
} else {
return "Unsupported Method";
}

Your native plugin must also implement the onGetObjList() and onCreateObject() callback
functions:
extern char* onGetObjList(void);
The onGetObjList() function returns a comma-separated list of classes supported by JNEXT. JNEXT
uses this function to determine the set of classes that it can instantiate. In our Echo plugin, we have the
following in echo_js.cpp:
char* onGetObjList() {
static char name[] = "Echo";
return name;
}
extern JSExt* onCreateObject(const string& strClassName, const string&
strObjId);
The onCreateObject() function takes two parameters. The first parameter is the name of the class
requested to be created from the JavaScript side. Valid names are those that are returned in
onGetObjList(). The second parameter is the unique object ID for the class. This method returns a
pointer to the created plugin object. In our Echo plugin, we have the following in echo_js.cpp:
JSExt* onCreateObject(const string& className, const string& id) {
if (className == "Echo") {
return new Echo(id);
}
return NULL;
}

Adding Features

54

Overall architecture of the plugin


You can place the artifacts of the plugin, which include the plugin.xml file, the source files (JavaScript, C++),
and the binary files (*.so), in any directory structure, as long as you specify the file locations in the plugin.xml
file. Below we show a typical structure:
Note: The structure below uses bold text for folder names and plain text for file names.
your_project_ folder
plugin.xml
src
blackberry10
index.js
native
device
*.so (binary files)
simulator
*.so (binary files)
www
client.js
Contents of the plugin.xml file
The plugin.xml file contains the namespace of the extension and other metadata. Define the namespace and
specify other metadata for the Echo plugin as follows:
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
id="org.apache.cordova.blackberry.echo"
version="1.0.0">
<js-module src="www/client.js">
<merges target="navigator" />
</js-module>
<platform name="blackberry10">
<source-file src="src/blackberry10/index.js" />
<lib-file src="src/blackberry10/native/device/libecho.so"
arch="device" />
<lib-file src="src/blackberry10/native/simulator/libecho.so"
arch="simulator" />
<config-file target="www/config.xml" parent="/widget">
<feature name="org.apache.cordova.blackberry.echo"
value="org.apache.cordova.blackberry.echo" />
</config-file>
</platform>
</plugin>

Adding Features

55

Community plugins
BlackBerry WebWorks is an open source project. Members of the open source community can create their
own plugins to extend the functionality of the SDK and can make those plugins available to the wider
community. These plugins provide access to native libraries that are not otherwise available through the
WebWorks or Cordova APIs, or through standard HTML5 functions.
Feel free to use any of the available community plugins in your WebWorks app, or contribute your own custom
plugin to the community.

Modifying your app configuration


When you create a WebWorks project, the tools create a default config.xml file for you, with some entries
prepopulated. The config.xml contains some entries that define meta data about your app (such as the app ID
and app description) and you (such as author name, company, and so on). The config.xml file also defines
some app features, behaviors, and device and Internet access permissions.
You can modify these configuration values at any time, either by using the BlackBerry 10 WebWorks SDK web
tool, or by manually modifying the config.xml file.

Configuring your app preferences


You can configure aspects of your app, such as its orientation or background color, by setting your app
preferences. You can configure your app preferences using the BlackBerry 10 WebWorks SDK web tool, or you
can edit the config.xml file. For information on editing the config.xml file, see Modifying your config.xml file on
page 68.
To set your app preferences with the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Config.
3. Complete the fields for the preferences you would like to set.
The following table lists the available preferences and their descriptions.
Preference

Description

App ID

The ID of your application.

App Name

The name of your application.

Adding Features

56

Preference

Description

Icon

The image that appears on a device's app grid.

Splash Screen Image

The image that's displayed when the app is opened.

Project Location

The path of your project directory.

App Description

A description of your app.

Author

Your name, or the name of your organization.

Author Email

The email address that is associated with the author.

Author URL

A web address that is associated with the author.

App Background Color

The background color for your app.

License

The end-user license agreement or a copyright statement for a


BlackBerry WebWorks app. The content is made available on the
About screen in the app.

Main URL

The start page that the BlackBerry WebWorks app displays when it
runs.

Orientation

The orientation for screens in your app. The orientation can be


default (orientation changes according to the orientation of the
device), portrait, or landscape. If no value is specified, the
orientation is set to default.

Autohide Splash Screen

Hides the splash screen for your application. When this setting is
disabled, the splash screen is displayed until
splashscreen.hide() is invoked in your code.

Hide Keyboard Form Bar

Hides the row of buttons (Previous, Next, and Submit) that is


displayed when an <input> element on the current page of the
app gets focus.

Adding Features

57

Preference

Description

Enable Child Browser

Enables your app to open child browser windows. A child window is


launched when the content attempts to open a resource in a new
window or tab (by using window.open(), or by specifying
_blank as the target of an anchor).

Enable Popup Blocker

When selected, prevents the app from displaying popups.

Enable Web Security

Enables web security. Disabling web security allows you to access


remote content from unknown sources.
This feature is intended primarily as a development convenience.
In production, URIs should generally be known and should be
whitelisted using the Access List preference.
If you disable web security, before packaging your app for
distribution, you should re-enable this setting, unless there is an
explicit reason not to do so.

Enable Disk Cache

Enables WebView caching, which prevents the app from issuing


multiple network requests for the same resource.

Enable Spatial Navigation

Enables spatial navigation on devices with a track pad or similar


input method. Spatial navigation allows the user to skip from one
focusable element (for example, a text field or button) to another,
rather than having to select each element to give it focus.
For more information about navigation modes, see Setting the
navigation mode for trackpad input on page 64.

Access List

Specifies which domains the app is permitted to access. By


default, no access to external domains is permitted.
For more information about whitelisting domains, see Accessing
external resources on page 59.

Permissions

Allows you to specify any permissions required to allow plugins to


access native functionality.
For more information about permissions, see Adding and removing
app permissions.

Adding Features

58

Accessing external resources


You can specify that your BlackBerry WebWorks app can access BlackBerry WebWorks APIs for a domain in
an executable container. An executable container allows your app to run JavaScript code within the context of
a webpage. It can be a page, a frame, or an iframe.
By default, BlackBerry WebWorks apps cannot access data from external resources. For example, a
BlackBerry WebWorks app cannot retrieve an HTML webpage, unless you configure the app to allow access.
To allow access to external resources, you must specify access permissions to define the list of domains that
your app is allowed to access.

Best Practices: Allowing access to external resources


Whenever your app retrieves content from external resources, consider the following best practices to make it
as secure as possible:
Provide JavaScript access to sensitive APIs only to trusted and secure websites.
Use the same precautions that you would use for a hosted website to protect against users with malicious
intent.
Protect your communication channel by using HTTPS when you expose sensitive APIs to the domain.
In the following example, we use the access element to specify that the site is accessed over HTTPS:
<access uri="https://somedomain.com" subdomains="true" />

Allowing requests to any website


If your app is designed to access data from an unknown or changing domain, you can use the wildcard
character (*) to ensure that your requests are not blocked. For example:
<access origin="*"/>
Note: The wildcard character (*) cannot be used for data accessed by XMLHttpRequest. To access data
using the XMLHttpRequest, you must explicitly specify each domain.
When you use the wildcard character (*), webpages that your app accesses cannot access any of the app APIs.
In the example above, all requests that do not access content via XHR and that do not require access to app
APIs are allowed.

Whitelisting file requests


If your app is designed to access the device file system, you can define the file:/// scheme as the origin domain
to ensure that your requests are not blocked.

Adding Features

59

Here's how you can ensure that your file system requests are permitted:
<access origin="file:///" subdomains="true" />

Defining external access using the SDK web tool


1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the left pane, click <your_project> > Configuration.
3. Locate the Access List section near the bottom of the list of preferences.
4. In the Origin field, enter the domain you want to allow your app to access. If your app is designed to access
data from an unknown or changing domain, you can use the wildcard character (*) to ensure that your
requests are not blocked.
5. To allow access to all subdomains within the specified domain, select Allow subdomains.
6. Click Add Access.

Adding access permissions to the config.xml file


You can specify access to a domain by adding an <access> element to the config.xml file. The config.xml file
can contain multiple <access> elements to specify access to different domains. The <access> element is a
child of the top-level <widget> element
To add an access permission to the config.xml file:
1. Open the config.xml file in the text editor of your choice.
2. Add an <access> element, specifying the domain you want to allow your app to access. If your app is
designed to access data from an unknown or changing domain, you can use the wildcard character (*) to
ensure that your requests are not blocked.
For example, to specify that a site is accessed only over HTTPS, you can add the following entry to your
config.xml file:
<access origin="https://somedomain.com" subdomains="true" />

Adding and removing app permissions


Some plugins require that specific app permissions be added to the app configuration. In most cases, when
you add a plugin that requires a permission, the tools automatically add it for you at build time.
In some cases, a permission is required only for a subset of the APIs contained by a plugin. In these cases, the
tools do not add the permission. If you intend to use the restricted APIs within the plugin, you must add the
required permission yourself. In addition, you may be required to add app permissions to use some HTML5
APIs, such as HTML5 notifications.
For example, adding the org.apache.cordova.file plugin to your project without specifying any permissions
allows you to access only those files within the application sandbox. However, to access other files on the
device file system, such as a music file, you must add the access_shared permission. In this case, adding the
Adding Features

60

plugin does not automatically add the permission. Instead, you must add the permission yourself, either using
the BlackBerry 10 WebWorks SDK web tool, or by manually adding them to the config.xml file.

Adding permissions using the SDK web tool


To add plugin permissions using the BlackBerry 10 WebWorks SDK web tool:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the left pane, click <your_project> > Configuration.
3. In the Permissions section at the bottom of the page, select the permission you want to add to the project
from the Permit drop-down list then click Add Permission. For information about the available app
permissions, see Available app permissions on page 61.

Adding permissions to the config.xml file


The project's root folder contains the config.xml file, which contains the app permissions for the project. You
can add a directly to the config.xml file by adding a <rim:permit> element. The config.xml file can contain
one or more <rim:permit> elements, all of which must be children of the <rim:permissions> element.
To add a permission to the config.xml file:
1. Open the config.xml file, in the text editor of your choice.
2. Locate the <rim:permissions> element. If no <rim:permissions> element exists, add one:
<rim:permissions>
</rim:permissions>
3. Add the app permission by inserting a <rim:permit> element in the <rim:permissions> element.
For example, if you want to access a music file on the device file system, you must add the
access_shared permission to the file, as follows:
<rim:permissions>
<rim:permit>access_shared</rim:permit>
</rim:permissions>
For information about the available app permissions, see Available app permissions on page 61.

Available app permissions


The following table identifies the available WebWorks app permissions, which are required to access specific
native functionality or capabilities. Typically the tools automatically add the required permission when the
plugin is added. However, if the plugin can function without the permission, and requires a permission only to
access certain APIs within the plugin, then the tools do not add the permission. If you intend to use the
restricted APIs, you must add the permission yourself.
Note: This list of permissions represents only those app permissions that may be required to use the
WebWorks or Cordova plugins that are installed with the BlackBerry 10 WebWorks SDK. Custom plugins that
access native functionality may require app permissions that are not listed here. For example, to use a custom
Adding Features

61

plugin that accesses the device's microphone to record audio, you must add the record_audio permission. For
a complete list of native app permissions, see App permissions in the BlackBerry 10 Native SDK
documentation.
Functionality or
capability
Camera

Device information

Location information

Shared files

Push

Run in background

Permission value

Description

use_camera

Allows the app to take pictures, record


video, and use the camera's flash.

read_device_identifying_inform Allows the app to access device


ation
identifiers such as serial number and
PIN.
access_location_services

Allows the app to access the devices


current or saved locations. This
permission replaces
read_geolocation, and includes
access to location information from
GPS, Wi-Fi, and cell ID.

access_shared

Allows the app to access pictures,


music, documents, and other files
stored on the device, at a remote
storage provider, on a media card, or
in the cloud.

_sys_use_consumer_push

Allows the app to use push


functionality.

run_when_backgrounded

Allows the app to run JavaScript and


networking in the background.
Your app can run in the background
either by including the
run_when_backgrounded
permission or by adding the
com.blackberry.push plugin to
your project.
Use this feature sparingly and only
when your application must perform

Adding Features

62

Functionality or
capability

Permission value

Description
processing in the background.
Running the app in the background
can negatively impact the battery life
of the device.

BBM Social Platform

Email and PIN


messages

Contacts

Calendar

Notifications

bbm_connect

Allows the app to connect to BBM so


that the user can chat or update their
BBM profile without leaving the app.

access_pimdomain_messages

Allows the app to access email and


PIN messages, including viewing,
creating, sending, and deleting
messages.

access_pimdomain_contacts

Allows the app to access contacts,


including viewing, creating, and
deleting contacts.

access_pimdomain_calendars

Allows the app to access the calendar,


including viewing, adding, and
deleting appointments.

post_notifications

Allows the app to post a notification to


the notification area of the screen.

Handling BlackBerry input


With the arrival of the BlackBerry Classic and BlackBerry Passport smartphones come several new ways for
users to interact with your apps:
Navigation keys: The BlackBerry Classic introduces four physical navigation keys (Send, Menu, Back, and
End keys). WebWorks allows you to customize the behavior of the Menu and Back keys. For more
information, see Handling BlackBerry Classic navigation key events on page 67.
Trackpad input: The BlackBerry Classic introduces the trackpad. The trackpad uses an infrared sensor to
detect finger movements, which it converts into directional movements on the screen. WebWorks allows
you to customize the behavior of trackpad navigation in a number of ways. For more information, see
Setting the navigation mode for trackpad input on page 64.
Touch-sensitive keyboard: The BlackBerry Passport introduces the touch-sensitive keyboard, a physical
keyboard that allows you to capture gestures such as swipes. A new plugin, com.blackberry.input, allows
you to capture events from the touch-sensitive keyboard. For more information, see Input.
Adding Features

63

Setting the navigation mode for trackpad input


The BlackBerry Classic device introduces the trackpad.
Devices with trackpads provide navigation capabilities that are not available on devices with touch-only
interfaces. You can choose one of the following navigation modes for your app to use when it's running on a
BlackBerry Classic device:
Cursor navigation mode: In cursor navigation mode, the trackpad acts as a mouse, allowing the user to
move the pointer around the screen to select focusable elements. For example, to complete a form, users
position the pointer over a field and then click the trackpad to enter input. They must repeat this set of
steps for each field they want to complete.
Spatial navigation mode: In spatial navigation mode, the trackpad allows the user to move from one
focusable element to the next. A focusable element is an element that the user can select. In web content,
certain elements, such as links and form elements, can receive focus so that the user can interact with
them (for example, to follow a link or complete a text field in a form).
You can control how users move from element to element by defining a focus order for the elements on a
page. For more information, see Defining the navigation path for spatial navigation on page 65.
Navigation mode is not user configurable. Rather, it is defined as part of your app configuration. By default,
apps use cursor navigation. To use spatial navigation, you must enable it in your app configuration.
With spatial navigation, you can customize the behavior of trackpad navigation by setting the position of the
initial focus for a screen and customizing the navigation path.
Enabling spatial navigation mode using the SDK web tool
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Configuration.
3. Select the Enable Spatial Navigation check box.
Enabling spatial navigation mode in the config.xml file
You can enable spatial navigation mode for your app by adding a <preference> element to the config.xml
file. Because this preference is specific to BlackBerry 10, you must nest this <preference> element in a
<platform> element.
To enable spatial navigation in the config.xml file:
1. Open the config.xml file in a text editor.
2. Add a <platform> element for BlackBerry 10, if one doesn't exist. For example:
<platform name="blackberry10">
</platform>

Adding Features

64

3. Within the <platform> element for BlackBerry 10, add a <preference> element. For example:
<platform name="blackberry10">
<preference name="SpatialNavigation" value="enable" />
</platform>
Defining the navigation path for spatial navigation
Spatial navigation allows the user to navigate from one focusable element to another. A focusable element is
an element that the user can select and can interact with. For example, an input field must receive focus to
allow the user to type input. When a link receives focus, the link is highlighted, and the user can follow the link
by pressing the Enter key.
Spatial navigation doesn't require that you add any plugins to your project. You can use standard HTML and
CSS to define which elements can receive focus, and how the user can navigate through those elements:
In the HTML source, you can set the tabindex attribute for an element. This attribute allows you to define
a value to an element that defines the element's position in the navigation path.
Using the CSS navigation properties, nav-left, nav-right, nav-up, and nav-down, you can define
which element receives focus based on the direction that the user swipes on the trackpad. The elements
that you specify as the targets of these properties become part of the navigation path, even if you haven't
set the tabindex attribute for those elements. These CSS navigation properties provide greater control
over the navigation path than the tabindex attribute.
If you don't set the tabindex attribute or CSS navigation properties, WebWorks provides a default navigation
path. In this case, the following elements receive focus in the order they appear:

<a>
<button>
<iframe>
<input>
<select>
<textarea>

Best practices
Define the trackpad navigation path logically. Carefully consider how the user is likely to move around your
app as you define a navigation path. Make sure that the focus doesn't jump around unexpectedly.

Defining the initial focus


You can use the tabindex attribute to define which element receives focus when a new screen is displayed
in your app. The element with the lowest tabindex value gets initial focus on the page. For example:
<a id="link1" href="http://www.my-company2.com" tabindex="2">Follow Link 1!
</a>
<a id="link2" href="http://www.my-company3.com" tabindex="3">Follow Link 2!
</a>
Adding Features

65

<a id="link3" href="http://www.my-company1.com" tabindex="1">Follow Link 3!


</a>
In the example above, Link 3 actually receives initial focus, since it has the lowest tabindex value.
In HTML5, every element supports the tabindex attribute. However, making an element focusable makes
sense only for those elements that a user typically needs to interact with, such as form elements or links.

Changing the navigation path


By default, the navigation path includes all the focusable HTML elements. The focus moves from one
focusable element to the next, either according to the direction that the user moves the trackpad, or according
to the tabindex values.
You can change the navigation path by using the following CSS properties:
Property

Description

nav-down

Defines the element that receives focus when the user


uses the touchpad to navigate down.

nav-left

Defines the element that receives focus when the user


uses the touchpad to navigate to the left.

nav-right

Defines the element that receives focus when the user


uses the touchpad to navigate to the right.

nav-up

Defines the element that receives focus when the user


uses the touchpad to navigate up.

For example, consider the following HTML:


<a id="link1" href="http://www.my-company2.com" tabindex="2">Follow Link 1!
</a>
<a id="link2" href="http://www.my-company3.com" >Follow Link 2!</a>
<a id="link3" href="http://www.my-company1.com" tabindex="1">Follow Link 3!
</a>
Now consider the following CSS rule:
a#link2 {
nav-right: #link1;
nav-left: #link3;
nav-down: #link3;
Adding Features

66

nav-up:

#link1;

In this example, the CSS navigation properties define which elements receive focus based on the direction the
user swipes the trackpad. Let's assume Link 2 has focus. When the user swipes up or to the right, Link 3
receives focus. When the user swipes down or to the left, Link 1 receives focus.

Handling BlackBerry Classic navigation key events


The BlackBerry Classic device includes four physical navigation keys. These keys provide one-touch shortcuts
to answer a call or return to a previous screen. The Send and End keys are predefined and can't be
customized. You can define the behavior of the Menu and Back keys.
Send key: Opens the Phone app or answers an incoming call.
Menu key: By default, this key performs no action. You must add code to handle Menu key events. To
capture Menu key events, you can use the menubutton event in the com.blackberry.app plugin.
Note: In most apps, the typical behavior of the Menu key is to open the app's action menu.
Back key: By default, this key minimizes the app and returns the user to the home screen. To change the
default behavior, you can use the backbutton event in the com.blackberry.app plugin.
Note: In most apps, the typical behavior of the Back key is to return to the previous screen within the app;
only when there are no other screens to close does the Back key minimize the app and return the user to
the home screen.
End key: Ends a call or minimizes the current app and returns the user to the home screen.

Best practices
Avoid unnecessary customization of the navigation keys. Although the Menu and Back keys can be
customized, be cautious about deviating from their typical behavior. Users expect the navigation keys to
work the same way in every app and context.
Handling menubutton and backbutton input events
Note: The menubutton and backbutton events are part of the com.blackberry.app plugin. To access these
events, you need to add the com.blackberry.app plugin to your project using either the SDK web tool or the
webworks plugin add command.
1. To attach an event listener that listens for the Menu or Back key to be pressed, use
document.addEventListener. You must add the listener after the deviceready event fires. For
example:
document.addEventListener("deviceready", function () {
document.addEventListener('menubutton', onMenuButton);
document.addEventListener('backbutton', onBackButton);
});

Adding Features

67

2. To specify the app behavior when each key event fires, add the callback functions. For example:
function onMenuButton() {
console.log("The Menu button was pressed");
}
function onBackButton() {
console.log("The Back button was pressed");
}

Modifying your config.xml file


The config.xml file is an XML file that is used to define the properties of your app. The config.xml file provides
general app information, such as the app name, description, start page, and home screen icon; and it specifies
the features and functionality that the app can access.
In WebWorks 2.0, there is little need to modify the config.xml file yourself. Most of the entries in the config.xml
for your app are added automatically when you use the WebWorks tools, and you can use the BlackBerry
WebWorks SDK web tool to modify many of your app's configuration settings.
However, you may need to modify the config.xml manually to add certain configuration information.
Specifically, you may need to add some <permit> elements to allow your app access to some functionality. If
you want to allow other apps to invoke your app, you also need to manually add the <invoke-target>
element and its children to define the invocation behaviour of your app.
The master config.xml file is located in the root folder of your WebWorks project. You can edit the file using any
text editor.
Note: Although multiple copies of the config.xml file may exist within your project subfolders, you should edit
only the master copy. Other versions of the file are overwritten by the tools when a project is built, so any
modifications made to those versions will be lost.
For a list of all the elements that you can use in a configuration document, see Elements in config.xml on page
69.
Note: If you edit the master config.xml file, you may notice entries that are not listed in the BlackBerry
documentation. You can ignore these entries, as they are used by other platforms. During the build process,
the SDK tools strip out any entries that are unnecessary or invalid for the BlackBerry platform before packaging
the app resources in a .bar file.
Sample config.xml for BlackBerry WebWorks 2.0
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="2.0.0.0" id="sampleapp">
<author href="http://www.example.com/"
rim:copyright="Copyright 1998-2012 My Corp">My Corp</
author>
Adding Features

68

<name>Sample application</name>
<description>
A sample application to demonstrate some features.
</description>
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>access_location_services</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
<icon src="icons/icon-150.png"/>
<rim:splash src="splash-1280x768.png"/>
<rim:splash src="splash-768x1280.png"/>
<content src="index.html"/>
<preference name="orientation" value="portrait" />
<preference name="backgroundColor" value="0xFFFF0000" />
<access uri="http://www.somedomain.com" subdomains="true" />
<license href="http://www.example.com/"/>
</widget>

Elements in config.xml
The following table describes each element that can be used in the configuration document. It also specifies
how many times you can use each element in your config.xml file for a particular platform.
Element

Description

Occurrences

<access>

Specifies that a BlackBerry WebWorks app can


access external network resources.

zero or more

<author>

Specifies the author's name.

one

<content>

Specifies the application start page.

one

<description>

Specifies a human-readable description of the


application.

zero or more

<icon>

Specifies an icon that represents the application


on the Home screen of the BlackBerry device.

zero or more

Adding Features

69

Element

Description

Occurrences

<license>

Specifies end user license and copyright


information.

one or none

<name>

Specifies a human-readable name for the


application.

one or more

<platform>

Contains platform-specific configurationn


information for your app.

<preference>

Defines a preference for the blackberry.app


plugin (for example, screen orientation).

zero or more

<rim:action>

Specifies the actions that are associated with the


invocation target.

one or more

<rim:filter>

Specifies the target filter. For each target, filters


must be declared to describe the kinds of
unbound invocation they support.

zero or more

<rim:invoke-target>

Registers your application as a handler for an


invocation event.

zero or more

<rim:mime-type>

Defines a valid MIME type for the data.

one or more

<rim:permissions>

Provides a container for <rim:permit> to


specify application permissions for device
features.

one

<rim:permit>

Defines application permissions for device


features. Must be a child of
<rim:permissions>.

one or more

<rim:property>

Defines the types of URIs or files that are used to


register an unbound invocation.

zero or more

<rim:splash>

Specifies the image to display on the screen while zero or more


your application loads.

<rim:type>

Defines the type of the invocation target.

one

<widget>

Provides a container for all other elements.

one

<access>

Syntax:
<access origin="string" subdomains=["true" | "false"] />
Adding Features

70

Description:
The <access> element specifies that a BlackBerry WebWorks app can access external network resources. By
default, if you do not specify an <access> element, an app has access to local resources only, which includes
all resources packaged in the apps .bar file.
If you specify more than one <access> element, the most specific definition is used. For example, if you use
http://somedomain.com and http://specific.somedomain.com, the <access> element that
uses the first definition (and any features defined under it) is ignored.
As a best practice, you should protect your communication channel by using HTTPS when you expose
sensitive APIs to the domain. For information about best practices on securing your app, see Accessing
external resources on page 59.

Occurrences:
Zero or more.

Parent elements:
<widget>

Child elements:
None.

Content:
None.

Attributes:
You can define the following attributes for this element:
Attribute

Description

origin

Optional. The origin attribute defines the web address for the access request.
You can specify a wildcard (*) for the origin attribute to whitelist any domain,
but only for domains that do not access content through XMLHttpRequest. If
the domain accesses data through XMLHttpRequest, you must explicitly
specify the domain for the origin attribute.

Adding Features

71

Attribute

Description

uri

Deprecated. The uri attribute defines the web address for the access request.
This attribute is only supported for backwards compatability. Going forward, you
should use the origin attribute.

subdomains

Optional. The subdomains attribute is a Boolean value that specifies whether


the host component in the access request applies to subdomains of the domain
that is specified in the origin attribute.
By default, if you do not specify the value of the subdomains attribute, the value
is set to false and no access to subdomains is requested.

Example:
The following example shows how to whitelist an external resource, in this case, the domain somedomain, as
well as any subdomains.
<access origin="https://somedomain.com" subdomains="true"/>
<author>

Syntax:
<author href="string"
rim:copyright="string"
email="string"
rim:copyright="string"
xml:lang="string">
string
</author>

Description:
The <author> element pecifies the name (typically the company or developer name) you used to register
your signing account.
You can access this element by using the blackberry.app.author property that is provided in the
BlackBerry WebWorks API.

Occurrences:
One.

Adding Features

72

Parent elements:
<widget>

Child elements:
None.

Content:
A string value representing the name of the developer or organization that you registered your signing account
with.

Attributes:
You can define the following attributes for this element:
Attribute

Description

href

Optional. The href attribute specifies a web address that is associated with the
author (for example, the web page of the author).
You can access this attribute by using the blackberry.app.authorURL
property that is provided in the BlackBerry WebWorks API.

rim:copyright

Optional. The rim:copyright attribute specifies copyright information.


On BlackBerry smartphones, this information appears on the About screen in the
application and in the copyright area in the applications list. An example of
typical copyright text is Copyright 1998-2009 My Company Inc.
You can access this attribute by using the blackberry.app.copyright
property that is provided in the BlackBerry WebWorks API.

email

Optional. The email attribute specifies the email address that is associated with
the author.
You can access this attribute by using the blackberry.app.authorEmail
property that is provided in the BlackBerry WebWorks API.

xml:lang

Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.

Adding Features

73

Attribute

Description

its:dir

Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.

Example:
<author href="http://www.example.com/"
rim:copyright="Copyright 1998-2012 My Corp">My Corp</author>
<content>

Syntax:
<content src="string"
rim:allowInvokeParams=["true" | "false"]
type="string"
charset="string" />

Description:
The <content> element specifies the start page that the BlackBerry WebWorks application displays when it
runs. The start page can contain the web address of a file that is located outside of the application archive.

Occurrences:
One.

Parent elements:
<widget>

Child elements:
None.

Content:
None.

Adding Features

74

Attributes:
You can define the following attributes for this element:
Attribute

Description

src

Required. The src attribute specifies the source HTML file in the
application archive.

rim:allowInvokeParams

Optional. The rim:allowInvokeParams attribute specifies that


parameters can be passed to your application when it is invoked from
another application.
By default, parameters cannot be passed to your application.

type

Optional. The type attribute specifies the MIME type of the file that is
specified in the src attribute.

charset

Optional. The charset attribute specifies the character set that is used
by the file that is specified in the src attribute.

Example:
The following example shows how to specify a start page called startpage.html.
<content src="startpage.html" />
<description>

Syntax:
<description>string</description>

Description:
The <description> element specifies a human-readable description for a BlackBerry WebWorks app.
You can access this element by using the blackberry.app.description property that is provided in the
BlackBerry WebWorks API.

Adding Features

75

Occurrences:
One.

Parent elements:
<widget>

Child elements:
None.

Content:
A string value representing a human-readable description of the app.

Attributes:
You can define the following attributes for this element:
Attribute

Description

xml:lang

Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.

its:dir

Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.

Example:
<description>
This application displays "Hello World" on the screen.
</description>
<icon>

Syntax:
<icon src="string" />

Adding Features

76

Description:
The <icon> element specifies a custom icon for a BlackBerry WebWorks app. The icon that you specify in the
src attribute is used to identify your app on the Home screen of the BlackBerry device.
The icon must meet the requirements for custom or default icons. Your icon image should be 24-bit PNG
format with an alpha channel. For information about designing icons for BlackBerry 10, see the UI Guidelines.
This element is optional. If you do not specify an icon for your app, the BlackBerry 10 WebWorks SDK uses the
default application icon.

Occurrences:
Zero or more.

Parent elements:
<platform>
Note: Although it is permitted to include the <icon> element as a child of <widget>, for future crossplatform compatibility, you should add all <icon> elements as children of a <platform> element.

Child elements:
None.

Content:
None.

Attributes:
You can define the following attributes for this element:
Attribute

Description

src

Specifies the path for an image file in the application archive.


This attribute is required.

rim:hover

A Boolean value that specifies whether the icon is used as a hover icon. The first
hover icon in the configuration document is used as the hover icon for the
application.

Adding Features

77

Attribute

Description
By default, if you do not specify a value for the rim:hover attribute, the value is
set to false.
This attribute is optional.

Examples:
Targeting multiple screen sizes
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. For example:
<platform name="blackberry10">
<icon src="icon-86.png" />
<icon src="icon-150.png" />
</platform>
Using localized icons
You can also use localized icons for BlackBerry 10 applications. To use localized icons, the image files must
be:
Named the same as the nonlocalized image file name that you specified in the <icon> element.
Stored in the appropriate locale subfolder that corresponds with the localized language.
When you use localized images, the files must be stored in individual locale folders (for example, "/locales/enUS", "/locales/fr") which are direct descendants of the root locales folder. The locales folder must be
located in the root of your application folder so that the BlackBerry WebWorks Packager can build your
application. The locale strings specified in the folder name must use the naming conventions that are specified
in the Internet Engineering Task Force (IEFT) Best Current Practice (BCP) 47 specification. For example, you
can use the Language-Region naming convention as in the following examples: en-US (United States English),
de-DE (German for Germany), and fr-CA (Canadian French).
The file names for the localized images must be named exactly as the nonlocalized image files that you
specified in the icon element. You can store the nonlocalized images in subfolders but the locale folder must
use the same subfolder structure for the localized images. When the BlackBerry 10 OS is set to one of the
locales (for example, German or French) and localized images are present for that locale, the BlackBerry 10
OS selects the images from the respective locale subfolder. If no localized images are available for the
specified locale, the BlackBerry 10 OS selects the nonlocalized icon image located in the root.
For example, assume that our WebWorks project includes the following files:
locales/de/icon-86.png
locales/de/icon-150.png
Adding Features

78

locales/fr/icon-86.png
icon-86.png
icon-150.png
In our config.xml file, we include the following entries:
<platform name="blackberry10">
<icon src="icon-86.png" />
<icon src="icon-150.png" />
</platform>
In this example, if the French locale is set on the device, even if the optimum icon resolution is 150x150, the
BlackBerry 10 OS uses the locales/fr/icon-86.png file because it's the only icon image available for
this locale.
<license>

Syntax:
<license>string</license>

Description:
The <license> element specifies the end-user license agreement or a copyright statement for a BlackBerry
WebWorks app. This element is optional. If you specify this element, you can implement a feature to prompt
BlackBerry device users to accept or decline the license agreement when they run the application for the first
time. After users agree to the license agreement, the prompt does not appear when they run the application
again.
The contents of the license agreement are also available on the About screen for the app.

Occurrences:
Zero or one.

Parent elements:
<widget>

Child elements:
None.

Content:
A string value representing an end-user license agreement or a copyright statement.

Adding Features

79

Attributes:
You can define the following attributes for this element:
Attribute

Description

xml:lang

Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.

its:dir

Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.

href

Optional. The href attribute specifies a web address for a web page that
contains content or license information.

Example:
<license>
Example license
Copyright 2012 My Corp.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, INSULT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</license>
<name>

Syntax:
<name>string</name>

Description:
The <name> element specifies a human-readable name for a BlackBerry WebWorks app that you can use, for
example, in an application menu.
Adding Features

80

If you do not specify a name element, the app is not valid. For BlackBerry 10 apps, the name must be 25
characters or less.
You can also specify a name by using the blackberry.app.name property that is provided in the
BlackBerry WebWorks API.

Occurrences:
One.

Parent elements:
<widget>

Child elements:
None.

Content:
A string value representing a human-readable name for the WebWorks app.

Attributes:
You can define the following attributes for this element:
Attribute

Description

xml:lang

Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.

its:dir

Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.

Example:
<name>Hello World! application</name>

Adding Features

81

<platform>

Syntax:
<platform name="blackberry10">
<rim:permissions>
<rim:permit> ...</rim:permit>
</rim:permissions>
</platform>

Description:
The <platform> element contains platform-specific application information. For example, using the
<platform> element, you can specify a platform-specific splash screen image for your cross-platform app,
and specify app permissions or preferences that are specific to the BlackBerry 10 OS. Invocation settings,
which are also specific to BlackBerry 10, must also be defined within a <platform> element.
If you are developing a cross-platform app, you should have one <platform> element for each platform you
are targeting with your app.

Occurrences:
Zero or more.

Parent elements:
<widget>

Child elements:
Name

Occurrences

<icon>

zero or more

<preference>

zero or more

<rim:invoke-target>

zero or more

<rim:permissions>

zero or more

<rim:splash>

one or none

Adding Features

82

Content:
None.

Attributes:
You can define the following attributes for this element:
Attribute

Description

name

Required. Specifies the platform name. The value for name is case insensitive.
In a BlackBerry WebWorks app, you should have an instance of <platform>
with a name value of blackberry10.
Other supported values include:

ios
android
firefoxos
tizen
wp8
windows8

Examples:
Registering bound and unbound invocations of a BlackBerry app
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</platform>
</widget>

Adding Features

83

Specifying BlackBerry specific permissions


<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
</platform>
</widget>
<preference>

Syntax:
<preference name="string" value="string" />

Description:
The <preference> element defines a preference for the blackberry.app plugin (for example, screen
orientation).

Occurrences:
Zero or more.

Parent elements:
<platform>
<widget>

Child elements:
None.

Content:
None.

Attributes:
You can define the following attributes for this element:
Adding Features

84

Attribute

Description

name

Required. Specifies the name of the preference that you are defining. For a
complete list of preferences that you can specify for name, see the Preferences
table below.

value

Required. Specifies the value of the preference that you are defining. For a
complete list of valid values for each preference, see the Preferences table below.

Preferences:
The following table lists the preferences that you can specify using the name attribute, with their associated
values. In all cases, the name value is case insensitive.
Preference

Description

Orientation

Specifies the orientation for screens in your app.


The value must specify one of the following strings:
default: Specifies that screen orientation changes according to the
orientation of the device.
portrait: Specifies that screen orientation remains in portrait orientation,
regardless of the orientation of the device.
landscape: Specifies that screen orientation remains in landscape
orientation, regardless of the orientation of the device.
By default, if you do not specify a screen orientation, the orientation is set to
default.
Example
<preference name="Orientation" value="portrait" />

AutoHideSplashScre
Hides the splash screen for your application. The value can be "true" or
en
"false", with "true" being the default. When false, the splash screen is
displayed until splashscreen.hide() is invoked.

Adding Features

85

Preference

Description
Example
<preference name="AutoHideSplashScreen"
value="false" />

BackgroundColor

Specifies the background color for your application. The value must specify a
color value in the ARGB pixel format using 8 hexadecimal digits.
Example
<preference name="BackgroundColor"
value="0xffff0000" />

ChildBrowser

Disables child browser windows. By default, when the content tries to open a
resource in a new window or tab (by using window.open(), or by specifying
_blank as the target of an anchor), the WebWorks app opens a secondary
browser window to display the resource. This feature is enabled by default.
The value must specify a value of "disable".
Example
<preference name="ChildBrowser" value="disable" />

DiskCache

Enables WebView caching, which prevents the app from issuing multiple network
requests for the same resource.
The value can be either "disable" or "enable". The default value is
"disable".
Example
<preference name="DiskCache" value="enable" />

HideKeyboardFormAc
When enabled, hides the row of buttons (Previous, Next, and Submit) that is
cessoryBar
displayed by default when an <input> element on the current page of the app
gets focus.
The value can be either "disable" or "enable". The default value is
"disable".

Adding Features

86

Preference

Description
Example
<preference name="HideKeyboardFormAccessoryBar"
value="enable" />

PopupBlocker

Enables the popup blocker, which prevents your app from displaying popups. By
default, WebWorks apps display popups in a child browser window.
The value attribute must specify a value of "enable".
Example
<preference name="PopupBlocker" value="enable" />

SpatialNavigation

Enables spatial navigation on devices with a trackpad. Spatial navigation allows


the user to skip from one focusable element to the next, rather than using the
cursor to select the element to give it focus.
For more information about navigation modes, see Setting the navigation mode
for trackpad input on page 64.
The value can be either "enable" or "disable". The default value is
"disable".
Note: This preference is specific to BlackBerry 10. You must nest this
<preference> element in a <platform> element.
Example
<platform name="blackberry10">
<preference name="SpatialNavigation"
value="enable" />
</platform>

WebSecurity

Disables web security. Disabling web security allows you to access remote
content from unknown sources. Before packaging your app for distribution, you
should remove this setting unless it is explicitly required.
This feature is intended primarily as a development convenience. In production,
all URIs should generally be known and should be whitelisted using the
<access> element.

Adding Features

87

Preference

Description
The value attribute must specify a value of "disable".
Example
<preference name="WebSecurity" value="disable" />

<rim:action>

Syntax:
<action>string</action>

Description:
The <action> element specifies the actions that are associated with the invocation target. Actions are strings
that identify the operations that your application is registered to handle. Actions can be discoverable actions or
menu actions. Menu actions always have a label and icon associated with them, while discoverable actions do
not.

Occurrences:
One or more.

Parent elements:
<filter>

Child elements:
None.

Content:
A string value representing the actions that are available to query.
The following predefined, discoverable actions are examples of actions that are available. These actions do not
have graphics or labels represented on the user interface but can be queried.
bb.action.VIEW
Describes the request to open a card or viewer based on the given MIME type, URI, or file extension. This
action should be used in cases where you register a card or viewer as a default handler.
Adding Features

88

bb.action.NOTIFY
Describes the act of notification which can be associated with different types, such as the BlackBerry
Push Service.
The following fixed menu actions are examples of actions that are available. These actions are represented in
the OS using graphics or labels and can differ based on the locale and region settings.
bb.action.OPEN
Describes the request to open associated content in a different application. You can use this action in
cases where you want a full-context switch from one application to another. Use this action in scenarios
where a full application is registering as a default handler.
bb.action.SET
Describes the request to set the associated content in a given context. For example, wallpaper, images of
contacts, BlackBerry Messenger SDK avatars, ring-tones, and so on.
bb.action.SHARE
Describes the request to share associated content. For example, you can share an image to a Bluetooth
target, which would transfer the image to another device via Bluetooth.

Attributes:
None.

Example:
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</platform>
<rim:filter>

Syntax:
<rim:filter>
<rim:action>string</rim:action>
<rim:mime-type>mime_type</rim:mime-type>

Adding Features

89

<rim:property var=["exts" | "uris"] value="string" />


</rim:filter>

Description
The <rim:filter> element specifies the target filter. For each target, filters must be declared to describe
the kinds of unbound invocation they support. Each filter defines the associated action performed for MIME
types that match the filter. Clients perform unbound invocation by sending the invocation without specifying a
target. Unbound invocations should generally provide an action, but must provide either a MIME type, URI, or
both.

Occurrences:
Zero or more.

Parent elements
<rim:invoke-target>

Child elements:
Name

Occurrences

<rim:action>

zero or more

<rim:mime-type>

one or none

<rim:property>

one

Content:
None.

Attributes:
None.

Example
Registering bound and unbound invocations
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
Adding Features

90

<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<rim:type>APPLICATION</type>
<rim:filter>
<rim:action>bb.action.OPEN</rim:action>
<rim:action>bb.action.SET</rim:action>
<rim:mime-type>text/*</rim:mime-type>
<rim:property var="exts" value="bmp,css,html,js" />
<rim:property var="uris" value="data://local,file://" />
</rim:filter>
</rim:invoke-target>
</platform>
</widget>
<rim:invoke-target>

Syntax:
<rim:invoke-target id="string">
<type>[ APPLICATION | VIEWER ]</type>
<filter>
<action>string</action>
<mime-type>mime_type</mime-type>
<property var=["exts" | "uris"] value="string" />
</filter>
</rim:invoke-target>

Description:
You can use the <rim:invoke-target> element to register your BlackBerry WebWorks application as a
handler for invocation events. In BlackBerry 10 OS, the invocation framework provides the ability by which a
client process can send a message to a target process so it can perform a certain action.
If you register your application with the invocation framework, your application can be invoked through:
Bound invocation: The target is invoked by using an identifier.
Unbound invocation: The target is invoked without specifying a target.
Bound and unbound invocation: The target is invoked by using an identifier and other attributes.
All invocations must specify an action that the target must perform as well as data to be acted upon. The data
can be specified by using a combination of MIME types, URIs, and file extensions.
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:invoke-target> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Adding Features

91

Occurrences:
Zero or more.

Parent elements:
<platform>

Child elements:
Name

Occurrences

<rim:filter>

zero or more

<rim:type>

one

Content:
None.

Attributes:
You can define the following attributes for this element:
Attribute

Description

rim:id

Required. Specifies a globally unique name. This name is verified when you sign
the application. It's recommended that you use the reverse-DNS naming
convention.
Example: com.ea.needforspeed.target

Example:
Registering bound and unbound invocations
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
Adding Features

92

<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</platform>
</widget>
Registering multiple filters against an invocation
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>application/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>audio/*</mime-type>
<mime-type>image/*</mime-type>
<mime-type>message/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
<filter>
<action>bb.action.VIEW</action>
<mime-type>text/*</mime-type>
</filter>
<filter>
<action>bb.action.SET</action>
<mime-type>image/*</mime-type>
<property var="exts" value="bmp,png,jpg,gif" />
</filter>
</rim:invoke-target>
</plaftorm>
</widget>
Registering multiple targets against an invocation type
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
Adding Features

93

<filter>
<action>bb.action.OPEN</action>
<mime-type>image/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
</rim:invoke-target>
<rim:invoke-target id="com.domain.subdomain.appname.view">
<type>VIEWER</type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>image/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
</rim:invoke-target>
</platform>
</widget>
Code sample: Parsing invoke parameters
When you set the <content> element's rim:allowInvokeParams attribute to a value of true, the start
up parameters for the application are available to the start page as a query string. You can parse the query
string using JavaScript.
function parseQueryString() {
// Create result container
var queryParamResult;
// Start at 1 to skip the leading '?'
var query = window.location.search.substring(1);
// Split the string on key-value pairs
var params = query.split('&');
// Loop through the pairs
for ( var i = 0 ; i < params.length ; i++ ) {
// Locate the '='
var position = params[i].indexOf('=');
if ( position > 0 ) {
// Text before the '=' is the key
var key = params[i].substring( 0, position );
// Text after the '=' is the value
var value = params[i].substring( position + 1 );

// Add to result container


queryParamResult[key] = value;

Adding Features

94

return queryParamResult;

<rim:mime-type>

Syntax:
<rim:mime-type>mime_type</rim:mime-type>

Description:
The <rim:mime-type> element defines a valid MIME type for the data.

Occurrences:
One or more.

Parent elements:
<rim:filter>

Child elements:
None.

Content:
A string value representing the MIME type for a file. The grammar for the MIME type must support the following
specifications:
RFC 2045 (content-types)
RFC 4288 (IANA registration)

Attributes:
None.

Example:
<rim:filter>
<rim:action>bb.action.VIEW</rim:action>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
</rim:filter>

Adding Features

95

<rim:permissions>

Syntax:
<rim:permissions>
<rim:permit>permission_string</rim:permit>
</rim:permissions>

Description:
The <rim:permissions> element is a container element for the <rim:permit> element, which specifies
the permissions for various features in a BlackBerry WebWorks application.
See the <rim:permit> element for information about permission features.
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:permissions> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">

Occurrences:
One or none.

Parent elements:
<platform>

Child elements:
<rim:permit>

Content:
None.

Attributes:
None.

Adding Features

96

Example:
The following sample demonstrates how to set the permissions for reading and writing files, reading GPS
location information, and accessing camera data.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
</platform>
<widget>
<rim:permit>

Syntax:
<rim:permissions>
<rim:permit>permission_string</rim:permit>
</rim:permissions>

Description:
The <rim:permit> element specifies permission access to various features in a BlackBerry WebWorks
application (for example, accessing the GPS location or the camera).
Note:
You must include the following namespace declaration in the top-level <widget> element to use the
<rim:permit> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">

Occurrences:
One or more.

Parent elements:
<rim:permissions>

Child elements:
None.
Adding Features

97

Content:
A string value representing a valid permission value. See the list of Permissions below for more information.

Attributes:
You can define the following attributes for this element:
Attribute

Description

system

Optional. The system attribute indicates that the specified permission is a


system permission. Set system="true" to indicate a system permission.
Currently, the only permission that must be specified as a system permission is
_sys_use_consumer_push.

Permissions:
The following table identifies the available permissions for WebWorks plugins, which are required to access
specific native functionality or capabilities.
Note: This list of permissions represents only those permissions that may be required when adding the
WebWorks or Cordova plugins that are installed with the BlackBerry 10 WebWorks SDK. Custom plugins may
require permissions that are not listed here. For example, to use a custom plugin that accesses the device's
microphone to record audio, you must add the record_audio permission. For a complete list of native app
permissions, see App permissions in the BlackBerry 10 Native SDK documentation.
Permission value

Description

Access the data lock


operational folder

access_operational_data_domain

Allows this app to access files in the


data lock operational folder. The
permission only applies to apps that
are data lock aware. For more
information about data lock, see
Creating apps that are data lock
aware.

Access the data lock


startup folder

access_startup_data_domain

Allows this app to access files in the


data lock startup folder. The
permission only applies to apps that

Functionality or
Capability

Adding Features

98

Functionality or
Capability

Permission value

Description
are data lock aware. For more
information about data lock, see
Creating apps that are data lock
aware.

BBM Social Platform

Calendar

Camera

Contacts

Device information

Email and PIN


messages

Location information

bbm_connect

Allows this app to connect to BBM so


that users can chat or update their
BBM profile without leaving the BBM
connected app.

access_pimdomain_calendars

Allows this app to access the


calendar, including viewing, adding,
and deleting appointments.

use_camera

Allows this app to take pictures,


record video, and use the camera's
flash.

access_pimdomain_contacts

Allows this app to access contacts,


including viewing, creating, and
deleting contacts.

read_device_identifying_inform
ation

Allows this app to access device


identifiers such as serial number and
PIN.

access_pimdomain_messages

Allows this app to access email and


PIN messages, including viewing,
creating, sending, and deleting
messages.

access_location_services

Allows this app to access the devices


current or saved locations. This
permission replaces
read_geolocation, and includes
access to location information from
GPS, Wi-Fi, and cell ID.

Adding Features

99

Functionality or
Capability
Notifications

Push

Run headless

Permission value

Description

post_notifications

Allows this app to post a notification to


the notification area of the screen.

_sys_use_consumer_push

Allows this app to use push


functionality.

_sys_run_headless

Allows this app to run when it is not


visible to the user.
Use this feature sparingly and only
when your application must perform
processing in the background.

Run in background

run_when_backgrounded

Allows this app to run JavaScript and


networking in the background. The
app appears as an active frame on the
device.
Your app can run in the background
either by including the
run_when_backgrounded
permission, or by adding the
com.blackberry.push plugin.
Use this feature sparingly and only
when your application must perform
processing in the background.

Shared files

access_shared

Allows this app to access pictures,


music, documents, and other files
stored on the device, at a remote
storage provider, on a media card, or
in the cloud.

Adding Features

100

Example:
The following example demonstrates how to set the permissions for reading and writing files, recording audio,
accessing camera data, and push.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>record_audio</rim:permit>
<rim:permit>use_camera</rim:permit>
<rim:permit system="true">_sys_use_consumer_push</rim:permit>
</rim:permissions>
<widget>
<rim:property>

Syntax:
<rim:property var=["exts" | "uris"] value="string" />

Description:
The <rim:property> element defines the types of URIs or files that the app supports. The URI schemes or
file extensions that you specify are used to register an unbound invocation.

Occurrences:
Zero or more.

Parent elements:
<rim:filter>

Child elements:
None.

Content:
None.

Attributes:
You can define the following attributes for this element:
Adding Features

101

Attribute

Description

var

Required. Specifies how the app is invoked. The invocation framework supports
invocation by URI or by file extensions. The value can be uris or exts.

value

Required. Specifies the property values to use when registering an unbound


invocation.
If var="uris", then value must specify one or more URI schemes (for
example, http://, https://, ftp://, or others).
If var="exts", then value must specify one or more file extensions (for
example, html, htm, php, jsp, or others).
To specify multiple URI scheme or file extension values, separate each value with
a comma. For example, value="html,htm,pdf".

Example:
<rim:filter>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
<rim:property var="uris" value="file://,pdf://" />
<rim:property var="exts" value="pdf" />
</rim:filter>
<rim:splash>

Syntax:
<rim:splash src="string" />

Description:
The <rim:splash> element specifies the image to display on the screen while the BlackBerry 10 device
loads your application. This element is optional.
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. Your splash screen image should fit
the entire screen size so that it fills the screen. For information about BlackBerry 10 screen sizes, see the
BlackBerry UI Guidelines.
The image for your splash screen can be any of the following file formats: .png, .jpg, .jpeg, .gif, or .bmp.
Note:
Adding Features

102

You must include the following namespace declaration in the parent <widget> element to use the
<rim:splash> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">

Occurrences:
Zero or more.

Parent elements:
<platform>

Child elements:
None.

Content:
None.

Attributes:
You can define the following attribute for this element:
Attribute

Description

src

Required. Specifies the path for an image file in the application archive.

Examples:
Targeting multiple screen sizes
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. For example:
<platform name="blackberry10">
<rim:splash src="splash-1024x600.png"
<rim:splash src="splash-600x1024.png"
<rim:splash src="splash-1280x768.png"
<rim:splash src="splash-768x1280.png"
</platform>

/>
/>
/>
/>

Using localized icons

Adding Features

103

You can also use localized splash screens for BlackBerry 10 applications. To use localized image files for the
splash screen, the image files must be:
Named the same as the nonlocalized image file that you specified in the <rim:splash> element.
Stored in the appropriate locale subfolder that corresponds with the localized language.
When you use localized images, the files must be stored in individual locale folders (for example, "/locales/enUS", "/locales/fr") which are direct descendants of the root locales folder. The locales folder must be
located in the root of your application folder so that the BlackBerry WebWorks Packager can build your
application. The locale strings specified in the folder name must use the naming conventions that are specified
in the Internet Engineering Task Force (IEFT) Best Current Practice (BCP) 47 specification. For example, you
can use the Language-Region naming convention as in the following examples: en-US (United States English),
de-DE (German for Germany), and fr-CA (Canadian French).
The file names for the localized images must be named exactly as the nonlocalized image files that you
specified in the <rim:splash> element. You can store the nonlocalized images in subfolders but the locale
folder must use the same subfolder structure for the localized images. When the BlackBerry 10 OS is set to one
of the locales (for example, German or French) and localized images are present for that locale, the BlackBerry
10 OS selects the images from the respective locale subfolder. If no localized images are available for the
specified locale, the BlackBerry 10 OS selects the nonlocalized icon image located in the root.
For example, assume that our WebWorks project includes the following files:
locales/de/splash-1024x600.png
locales/de/splash-600x1024.png
locales/de/splash-1280x768.png
locales/de/splash-768x1280.png
locales/fr/splash-1280x768.png
locales/fr/splash-768x1280.png
splash-1024x600.png
splash-600x1024.png
splash-1280x768.png
splash-768x1280.png
In this example, if the French locale is specified on the device, even if the optimum resolution is 1024x600, the
BlackBerry 10 OS uses the locales/fr/splash-1280x768.png file because it's the only landscape
image available for this locale.
<rim:type>

Syntax:
<rim:type>[ application | viewer ]</rim:type>

Description:
The <rim:type> element defines the type of the target.
Adding Features

104

Occurrences:
One.

Parent elements:
<rim:invoke-target>

Child elements:
None.

Content:
A string value specifying the target type. You can define the target as one of the following types:
application
The target is an application and is started only when required.
viewer
The target reference always spawns a new window and window reparenting is required.

Attributes:
None.

Example:
<rim:invoke-target id="com.mycompany.pdf.viewer">
<rim:type>viewer</rim:type>
<rim:filter>
<rim:action>bb.action.VIEW</rim:action>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
</rim:filter>
</rim:invoke-target>
<rim:invoke-target id="com.mycompany.pdf.app">
<rim:type>application</rim:type>
<rim:filter>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
<rim:property var="uris" value="file://,pdf://" />
<rim:property var="exts" value="pdf" />
</rim:filter>
<rim:filter>
<rim:action>bb.action.VIEW</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
Adding Features

105

<rim:mime-type>application/x-pdf</rim:mime-type>
</rim:filter>
</rim:invoke-target>
<widget>

Syntax:
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="string"
id="string"
xml:lang="string"
rim:header="string"
rim:userAgent="string">
</widget>

Description:
The <widget> element is the root element of the config.xml file. The config.xml file must contain a single
instance of <widget>.

Occurrences:
One.

Parent elements:
None.

Child elements:
Name

Occurrences

<access>

zero or more

<author>

one

<content>

one

<description>

zero or more

Adding Features

106

Name

Occurrences

<license>

one or none

<name>

one

<platform>

zero or more

<preference>

zero or more

Content:
None.

Attributes:
You can define the following attributes for this element:
Attribute

Description

xmlns

Required. Defines the namespace for the BlackBerry WebWorks app. The value
must be xmlns="http://www.w3.org/ns/widgets". If this namespace is
missing, the app archive is not valid.

xmlns:rim

Required. Defines the namespace for the BlackBerry WebWorks extensions (that
is, those elements with the rim: prefix). The value must be
xmlns:rim="http://www.blackberry.com/ns/widgets".

version

Required. Specifies a valid version for the app, in one of the following formats:
x.x.x
x.x.x.x
If you specify a version number that is not valid, the app archive is not valid.

rim:header

Optional. Specifies an HTTP header value that precedes every request for data
that the app sends. This attribute allows you to distinguish between requests sent
from your BlackBerry WebWorks app and requests coming from the BlackBerry
Browser. The attribute value can be any string.

Adding Features

107

Attribute

Description

rim:userAgent

Optional. Specifies the value for the user agent. The value that you specify is sent
as the value of the User-Agent header, which is included with every HTTP
request. You can use this string to identify requests coming from your app. The
attribute value can be any string.

id

Required. Specifies a unique identifier for the app.


Unless you are repackaging an app from another platform, you should use a
reverse DNS format for all platforms, for example,
id="com.somedomain.HelloWorld".
If you resubmit an app to BlackBerry World that was initially packaged using a
previous version of the BlackBerry WebWorks SDK, the value you specify for this
attribute must be the same as the value for the Package-Name in your existing
app's .bar MANIFEST file (for example,
sampleApp6d5d8d2973ab439a52d274dffa2b018). You can access the
MANIFEST file by unzipping the .bar file and viewing it in any text editor.

xml:lang

Optional. Specifies the language that is used in the element. For more
information about this attribute, visit www.w3.org/TR/html401/struct/
dirlang.html.

Example:
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="2.0.0.0"
id="sampleapp"
rim:header="RIM-Widget:rim/widget"
rim:userAgent="BlackBerry10/MyWebWorksApp">
</widget>

Creating headless WebWorks apps


As of the BlackBerry 10 WebWorks SDK version 2.1.0, you can create headless WebWorks apps. A headless
WebWorks app is comprised of two component apps that are built together into a single application package:
web app: This component includes the UI, and is just like any other WebWorks app. It is developed using
standard web technologies such as HTML, CSS, and JavaScript, and requires you to add the appropriate
Adding Features

108

plugins and modify configuration settings as necessary. Once you have created the headless WebWorks
project, the process to develop this component is the same as for any WebWorks app.
headless service: This component is a native app developed in C/C++ that is designed to run in the
background on the device. It has no UI, and the user can't invoke or interact with it in any way. Typically,
the headless service starts as a result of a defined trigger, performs some function (for example, generating
a notification), and then stops, until it is triggered again. By using the _sys_headless_nostop
permission, you can also create a headless service that runs continuously.
Although the two components are packaged together, they are designed to operate independently on the
device. That is, the headless component doesn't require the web component of the app to be running in order
to respond to a trigger.
The following diagram provides an overview of the headless app process:

For a thorough discussion of headless apps, see Headless apps in the BlackBerry 10 Native SDK
documentation.
To understand how headless apps work, let's look at the template that is provided when you create a headless
app using the BlackBerry 10 WebWorks SDK. When you create a headless app in WebWorks using the
create-headless command, you receive a fully functional app that you can immediately build and deploy
to a device or simulator. By deafult, the headless component of the app is configured with the
bb.action.system.STARTED trigger, which triggers it to run as soon as it is installed on the device. Once
triggered, the headless component immediately sends a notification to the BlackBerry Hub, which the user
can click to invoke the web component of the app. The web component provides a button that resets the
headless component of the app, causing it to send another notification.
The headless service supports various triggers; a trigger can be the receipt of pushed content or a portdirected SMS message, a change in location information, or some other event. For a full list of triggers, see
Triggers in the BlackBerry 10 Native SDK documentation. The behavior of the headless component upon being
triggered similarly depends on the requirements of your app.

Additional system requirements


The headless component that's provided when you create your WebWorks project is a native C/C++
application. It includes both the binary and the complete source code for the headless portion of the app.
The source code provides the complete project, which can be imported into the Momentics IDE for
BlackBerry.
To modify and recompile the code, download and install the BlackBerry 10 Native SDK.
Adding Features

109

Creating a headless WebWorks project


You create headless apps from the command line using the create-headless command. You can't create
a headless app using the SDK web tool.
When you create a headless app, the SDK creates a project containing the following:
All the basic web resources required for the web component
The compiled binary of the headless component (located in the www/assets folder)
The C/C++ project for the headless component (located in the HeadlessService folder), which you can
import into the Momentics IDE
Note: When importing the project into the IDE, we recommend that you don't select the Copy into
workspace option. The MakeFile included in the project automatically places the newly built binary into the
www/assets folder of the WebWorks project. Copying the project into the workspace prevents the binary
from being placed in the correct folder.
To create a WebWorks project with a headless service:
1. On the command line, run the following command to create a WebWorks project with a headless service:
webworks create-headless <path>
For example, the following command creates a headless project in the c:\webworks-apps\myapp folder:
webworks create-headless c:\webworks-apps\MyApp
Check the table below for parameter details:
Parameter

Description

<path>

The home folder for your project. The tool creates this
folder for you and does not overwrite an existing folder; if
you specify an existing folder, the project is not created.

Differences in a headless WebWorks app


A headless app project has two major differences from a regular WebWorks project:
There are some additional folders added to the project folder structure.
The config.xml file includes some nonstandard entries.

Folder structure
A WebWorks 2.0 project with a headless service has the following differences in the project folder structure:

Adding Features

110

Folder

Description

www/assets

The www folder includes an assets subfolder. The assets folder contains the
compiled binary of the headless service component of your app.

HeadlessService

The HeadlessService folder contains the complete C/C++ project for the
headless portion of the app. You can import the project into the Momentics IDE
for BlackBerry to modify the default headless app and add custom functionality.
For information on how to import the headless project, see Import your headless
project into the Momentics IDE on page 112.

Changes to the config.xml file for headless apps


The config.xml file provided for a headless WebWorks app contains a <config-file> element. This element
contains entries that are injected into the the bar-descriptor.xml file for the headless service component.
In a native app, the bar-descriptor.xml file specifies the parameters for identifying, installing, and launching
the app on BlackBerry 10 OS. More importantly, the bar-descriptor.xml file defines the triggers that launch the
headless service, and defines the elements required to launch and run both the WebWorks and headless
components.
If you need to change bar-descriptor.xml values for your headless WebWorks app, you must edit those same
values within the <config-file> element of config.xml file.

Modifying the template components


Once you've created the headless WebWorks project, you can modify the template web and headless
components of the app.
Modifying the web component of a headless app is no different than creating and modifying a regular
WebWorks app. You add plugins, modify configuration settings, set permissions, and so on.
To modify the headless component, you need some information about triggers, coding in C/C++, and the
Momentics IDE. If you modify the source code, you also need to recompile the source code. As long as you
import the project without copying it into your workspace, the MakeFile compiles and replaces the default
binary in the www/assets folder with the newly built binary. You can find helpful information in the BlackBerry
10 Native SDK documentation. Before you start exploring, however, there is some information unique to
headless WebWorks apps that you should know.

Defining triggers
For information on defining triggers for your headless service, see the Triggers section in the BlackBerry 10
Native SDK documentation.
While the syntax and structure are identical, remember that in a headless WebWorks app, the triggers are
specified within the <config-file> element of the config.xml file, not in a bar-descriptor.xml file.
Adding Features

111

Modifying the headless component source code


The Creating a headless app section of the BlackBerry 10 Native SDK documentation provides a complete
tutorial describing how to create a native headless app. You might find this information helpful as you modify
your app.
In the template app, the service.cpp and service.hpp files correspond to the application.cpp and
application.hpp files, respectively, that are described in the tutorial. Also, this tutorial describes how to create
the UI component of the app; your headless WebWorks template already provides the UI portion, so you can
disregard this information.
Import your headless project into the Momentics IDE
To customize the template headless app that was provided when you created your headless WebWorks
project, you must first import the project into the Momentics IDE for BlackBerry.
Note: When you import the project, do not copy it into your workspace. By not copying it, you make sure that
the source for both the headless portion and the web portion are kept together. More importantly, when you
compile the source code, the project's MakeFile automatically places the compiled binary into the www/assets
folder. The binary file must be placed in this folder so that both the web and headless portions of the app are
built together.
Once the project has been imported, you can modify the code and recompile it to generate the binary file for
the headless service.
To import your headless project:
1. Open the Momentics IDE for BlackBerry.
2. Select File > Import . The IDE opens the Import wizard and displays the Select panel.
3. In the Select panel, expand General, select Existing Projects into Workspace, and then click Next. The IDE
displays the Import Projects panel.

Adding Features

112

4. In the Import Projects panel, next to the Select root directory field, click the Browse button and
navigate to your project's HeadlessService folder.
5. In the Projects list, make sure that the HeadlessService project is selected.
6. Make sure that the Copy projects into workspace check box is not selected.
7. Click Finish to import the selected project into the IDE.

Adding Features

113

App integration
The BlackBerry 10 OS provides the invocation framework to bring powerful cross-app integration to the
platform. You can use the invocation framework and cards to greatly enhance the user experience and
functionality of your app.
The invocation framework facilitates inter-app communication. The framework allows your app to start other
apps from within its UI, preserving user focus and ensuring optimal multitasking and app flow. You can also
integrate your app with apps that are included in the BlackBerry 10 OS (also known as core apps). For
example, you can integrate with apps such as File Manager, Pictures, Music, and BBM, and you can invoke
these apps when you need them.
Cards enhance the invocation framework's capabilities. Cards allow you to open a particular screen of another
app as a card, instead of opening the full app. Cards use fewer system resources and offer a great user
experience.
The invocation framework also includes other features that make your app easier to use and more tightly
integrated with other apps on the device. You can add your app as an entry to different menus (such as the
context menu and target selection menu), allow your app to be invoked using active text, and enable your app
to be the default app for certain types of content.

Invocation framework
The invocation framework in the BlackBerry 10 OS allows one app to invoke another by sending it a message.
When an app calls for an invocation on some content, the invocation framework responds with appropriate
apps that can carry out a requested action on that particular content. For example, using the invocation
framework, your app can allow the user to perform a set of actions on a piece of content such as a .doc file.
These actions allow the user to share, open, or send the .doc file in an email using another app from within the
UI of your app. In this example, your app is the client app in the invocation framework and the app that shares,
opens, or sends the .doc file as an email is the target app.
Depending on your app's functionality, the invocation framework can allow your app to become more
discoverable if you register your app as a target. Registering allows other apps to invoke your app and use its
features.
An invocation request is the message structure that is passed between a client app and a target app. An
invocation message represents either a request for the target to perform a task or a notification about an event
that has occurred. An invocation request is passed to a target app when the target is invoked. The framework
takes care of opening the target app if it is not already running.
An invocation request contains the following information:
The unique ID of the target app
The action that should be performed
The data that should be acted upon
Adding Features

114

Invocation target
An app that is registered with the invocation framework is called a target app. Other apps can invoke a target
app by using the invocation framework. Upon invocation, the user's context switches to the target app. The
client app (the app from which the invocation request is sent) moves to the background while the user works in
the target app.
The target ID in an invocation message tells the invocation framework where to send the invocation message. A
target ID is assigned by the target app developer and is guaranteed to be unique when the app is signed. To
help select a unique value, the target ID uses a reverse DNS style structure (for example, com.acme.myapp).

Invocation action
The action attribute in an invocation request describes the task that can be performed on the content. Every
action is uniquely identified by a name. Action names end with a verb in uppercase letters. To help identify the
ownership and uniqueness of each action, the action attributes in an invocation request use a reverse DNS
style structure (for example, com.acme.action.VIEW).
The invocation framework supports a set of actions that your app can request the platform to perform (for
example, viewing an image). You can also use actions to register your app as a target in the core apps of the
BlackBerry 10 OS (for example, registering your app as a target could allow an image in the Pictures app to be
shared with your app).
All of the actions available on the BlackBerry 10 OS begin with bb.action and are appended by a verb in
uppercase letters. Before you add a custom action, check to see if there is already a suitable action provided
by the platform. For a complete list of available platform actions, see Invoking core applications.

Invocation data
The data in an invocation message is provided as a URI and a MIME type. The URI identifies the location of the
data resource and the MIME type describes the data. For common MIME types, the platform can deduce the
MIME type from the URI, even if you do not specify the MIME type when you specify a URI. For example, it can
deduce the MIME type from a file extension in the URI.
For small amounts of data, you can include the data directly in the invocation message using the data
attribute. The URI is assumed to be data://local and can therefore be left out of the message. When you
send data directly in the invocation message, you must provide a MIME type because the platform can only
deduce the MIME type if a URI is present in the message. The total size of the message cannot exceed 16 KB.
A custom MIME type that describes data should begin with the application/vnd. prefix. It should be
followed by sufficient context so that the MIME type is properly distinguished from other types. If the data has
multiple encodings represented in the MIME type, make sure that the data is the last element defined in the
type (for example, application/vnd.mycompany.mydata).
You can also specify additional, optional data by using the metadata attribute in an invocation message. Data
is sent in JSON format.

Adding Features

115

Sending invocation
An invocation message contains a target, an action, and data. To learn more about these parameters, see
Invocation framework. You can configure your app to invoke target apps by using bound or unbound
invocations.
Bound invocation
Bound invocation occurs when a client app explicitly identifies the target app to handle the invocation. The
following image shows how a client app can use bound invocation to invoke a specific target app. In this case,
Target app opens the document contained in the client app.

Before you can send an invocation request, you must add the com.blackberry.invoke plugin to your app.
To add the plugin, on the command line, navigate to your project folder and run the following command:
webworks plugin add com.blackberry.invoke
Here's an example that shows how to send an invocation request:
blackberry.invoke.invoke({
target: "com.example.image.view",
action: "bb.action.OPEN",
type: "image/png",
uri: "file:///path/to/image.png"
}, onSuccess, onError);
Once the invocation request is sent, the invocation response is handled by the invocation framework itself.
However, you must create JavaScript functions to handle the success or error events. Here's a sample that
shows you how to do that:
function onSuccess() {
console.log("<p>Invocation successful</p>");
}
function onError(error) {
console.log("<p>Invocation error: " + error + "</p>");
}
Target discovery
You can hard code the target app that you want to send an invocation message to, or you can query the
invocation framework to find out what targets are installed on the BlackBerry device. The invocation framework
uses a target filter to allow the target apps to declare the types of invocation they support. When a client app
queries the invocation framework, the framework uses the target app's filter to describe the kind of target it is
and the data it can accept.
Adding Features

116

The quality of the results depends on how specific the target query request is. A target query request should
consist of the URI and MIME type. If the MIME type is omitted, the framework tries to determine the type using
the URI.
A client app can include the action to be performed on the data in its target query request. If the action is not
specified in the target query request, the query result will contain a list of all the actions that can be performed
on the specified data by the available targets.
The invocation framework returns a query result that includes the targets grouped by the action that these
targets support. For each target, the query result provides the target ID, the target type (an app or a card), and
other information about the target, such as icons and labels, that can be used to display the target in the client
app's screen.
To determine what targets are suitable candidates, the invocation framework applies a set of brokering rules.
For more information, see Target selection and brokering.
The following code sample demonstrates a target query request in which a client app searches for targets that
support the bb.action.OPEN action on image/png images, which are sent as a file:// URI:
var request = {
"action": "bb.action.OPEN",
"type": "image/png",
"uri": "file://path/to/image.png",
"target_type": ["APPLICATION", "VIEWER"],
"action_type": "ALL"
};
blackberry.invoke.query(request, onSuccess, onError);
Here's how you can handle the results:
function onSuccess(response) {
console.log("<p>Invocation query response: " + response + "</p>");
var data = JSON.stringify(response);
//can now parse the data variable for invocation targets
// that matched the query criteria
}
function onError(error) {
console.log("<p>Invocation query error: " + error + "</p>");
}
Unbound invocation
The invocation framework can make invoking a target app easy by removing the need to query. Instead of
sending a target query request to determine the available targets, the client app can simply send an invocation
request to the framework without specifying a target. This kind of invocation is called unbound invocation. If
you send an unbound invocation request, the framework searches for and invokes a suitable target app for
you.
Adding Features

117

The following image shows how a client app lets the invocation framework return the most suitable target app
for a particular action. In this case, Target app is the most suitable app to open the document contained in the
client app.

To find the best target app, the framework first uses a brokering process. It applies a set of rules to determine
which target apps support the client app's invocation request. If there is more than one suitable target
available, the framework applies a set of selection rules to choose the most appropriate target. For more
information, see Target selection and brokering.
You can also send an invocation request without specifying an action. In this type of request, only the data is
sent. The framework determines the type of target and the action to be performed.
If you don't specify an action, the invocation framework tries to find an appropriate target app for the
bb.action.VIEW action. If no suitable target app is found for bb.action.VIEW, the invocation framework
falls back to determine an appropriate target app that supports bb.action.OPEN. If still no suitable target
app is available for bb.action.OPEN, the invoke request is unsuccessful.
The following code sample shows how you can create an unbound invocation request. The code invokes the
most suitable target app to handle the image.png file, which is specified by the URI.
blackberry.invoke.invoke({
uri: "file:///path/to/image.png"
}, onSuccess, onError);
Data transfer
This section explains how the invocation framework sends data, to help you understand how to optimize your
invocation requests and send multiple files between client and target apps. Although apps can use many
different URI schemes to transfer data, the invocation framework provides support for in-band transfer and file
transfer.
In-band transfer
Most often, an invocation request carries only a small amount of data (less than 16 KB). In some cases, this
small amount of data can be encoded directly into a URI. It is also possible to send it as part of the invocation
request. When data is sent as part of the invocation message, it is placed in the data attribute. This type of
transfer is called an in-band transfer.
During an in-band transfer, the URI value should be set to data://local, which points to the data attribute.
When the data is sent in-band, the MIME type must describe the type of the data, to allow both the invocation
framework and the target app to handle the message.
blackberry.invoke.invoke({
target: "com.example.image.view ",
action: "bb.action.OPEN",
Adding Features

118

type: "text/plain",
data: "Hello World!",
}, onSuccess, onError);
File transfer
This section contains information on how the invocation framework handles file transfers and the types of files
that are supported.

File extensions
The invocation framework supports file handling based on the file extension. The file extensions can be defined
as file:// in the scheme attribute when the data is referenced by the URI. The invocation framework also
supports the declaration of an extensions attribute in the target filters. In an invocation request, if the URI is
suffixed with a file extension that matches any of the file extensions declared in the extensions attribute, then a
given target filter will match with that invocation request. When the extensions attribute is defined, the target
filter implicitly supports the file:// URI for those declared extension cases.
The extensions attribute is applied only if the accompanying URIs contain a file://-based URI. Also,
combining the extensions attribute and specific MIME types in a target filter means that both must be specified
by a client app for the target filter to successfully match with an invocation request. The best practice in most
cases is to define the extensions-related target filters as a separate declaration, where the URI attribute is
file:// and the MIME type is a wildcard character (*).

File transfer modes


Sending an invocation request with a file:// URI to pass files succeeds only if the target app can access the
file. BlackBerry 10 supports the use of a shared area in the file system to share data between the client and
target apps. However, to send sensitive data to a target app, a client app can use the file transfer feature of the
invocation framework.
When the framework receives an invocation request with a file:// URI, it inspects the URI to determine if
the request refers to a shared area. If the file is already shared, the invocation request passes the URI to the file
in the shared area, as specified by the sender. However, if the invocation framework detects that the file is not
shared, then it creates a read/write copy of the file in a private inbox for the target app. The client app can
specify the file transfer mode attribute to override this behavior.
Invocation requests support the following file transfer modes:
File transfer mode

Description

Preserve

Skip file transfer handling and deliver the file as-is.

Adding Features

119

File transfer mode

Description

CopyReadOnly

Create a read-only copy of the file in the target app's


private inbox.

CopyReadWrite

Create a read/write copy of the file in the target app's


private inbox. This is the default behavior.

Link

Create a hard link to the file in the target app's private


inbox. When Link is specified, the file must have
read/write permissions and the sender must be the
owner of the file.

Sending multiple files


For certain invocation requests, you might want to send multiple files in a single request. The invocation
framework supports a special set of MIME types (type/subtype). Each type is a combination of supported
file types, as explained below:
Type

Supported file types

filelist/audio

audio/mp4, audio/mpeg

filelist/video

video/mpeg, video/mp4

filelist/image

image/gif, image/jpeg, image/png

filelist/media

Any of the files supported for filelist/audio,


filelist/video, or filelist/image

filelist/document

application/pdf, application/vnd.msexcel, application/msword, application/


vnd.ms-powerpoint

filelist/mixed

Any

Adding Features

120

When sending multiple files, you can set the URI attribute to describe the common file path that is associated
with each file. Usually, this file path is the common root directory, if one exists. If no common root directory
exists, set the URI attribute to list://. After you set the type and URI, you can assign the list of individual file
URIs to the data attribute using the following JSON format:
[

'uri':<file-uri>,
'type':<mime-type>,
'data':<metadata>

Attribute

Format

Description

Mandatory?

Example

uri

File URI

The URI of the file


being listed; the
URI prefix must
match the
invoke.uri
attribute value

Yes

file://path/to/
file

type

MIME

The MIME type of


the specified file

No

image/jpeg

data

JSON

Additional
metadata in JSON
format

No

test metadata

Receiving invocation
You can configure your app to receive invocation requests from other apps. To receive an invocation request,
your app must support invocation targets. To support invocation targets, you must declare your targets in the
config.xml file and handle invocation messages.
Target declaration
To be invoked, an application identifies itself by declaring itself as a target in its config.xml file. To declare a
target, add the following elements to the config.xml file for each target that the application exposes.
<invoke-target id="com.example.image.view">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>My App Name</invoke-target-name>
<icon>
<image>icon.png</image>
Adding Features

121

</icon>
</invoke-target>
Attribute

Element

Description

ID

<invokeThis attribute
target id> uniquely
identifies the
app as a
target. This
attribute can
also be used
by the client
apps to
perform
bound
invocation.

Type

<invoketargettype>

This attribute
specifies the
type of the
target. Apps
and cards are
supported as
types of the
target.

Name

<invoketargetname>

This attribute
specifies the
name of the
target app.

Icon

<icon>

This attribute
specifies the
icon for the
target app.

Receiving invocations

Adding Features

122

Declaring your application as a target is essential for receiving an invocation request, but to be invoked you
need to add code in your application to receive invocation messages. Before you can receive invocation
messages, you must specify your app in the config.xml file as shown below:
<rim:invoke-target id="com.bb.test.invokable">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>text/plain</mime-type>
</filter>
</rim:invoke-target>
The following code describes how to configure your application to listen for invocation messages:
// Add an event listener for when
// the application gets invoked:
document.addEventListener('invoked',onInvoked);
// The following function parses the incoming data
function onInvoked(invokeRequest) {
}
Handling launch through invocation
An important thing to consider when you write an application target is how an app is launched. Usually an app
launches when the BlackBerry device user taps the app icon on the home screen. However, with the
invocation framework the app can also be invoked. So how does an app know whether it was invoked or
launched? Here's how your app can listen for the invocation events:
function onInvoked(info) {
if(info.source) {
console.log("Source: " + info.source);
}
if(info.target) {
console.log("Target(me): " + info.target);
}
if(info.action) {
console.log("Action: " + info.action);
}
if(info.data) {
console.log("Data: " + info.data);
//the data comes in as a base64 string you can convert it using
atob(...)
//note that atob will fail if you are being passed unicode strings
console.log("Data: " + atob(info.data));
}
}
document.addEventListener('invoked',onInvoked);

Adding Features

123

You can also specify any particular behavior that you'd like your app to exhibit when it is invoked (for example,
screen orientation) by setting app preferences. For more information, see Configuring your app preferences.
Target filters
One of the key features of the invocation framework is the ability to discover target applications or cards on a
BlackBerry device. Targets are discovered based on the filters they declare in their config.xml file, which
describe the kinds of invocation request that a target supports. Target filters allow your app to be queried for by
other apps and make your app a candidate for unbound invocation requests.
Target filters are declared as part of the <invoke-target> element in the config.xml file and consist of the
following attributes:
Attribute

Description

filter

Describes the
criteria for this
app to be
considered for
unbound
invocations or
invocation
queries. This
attribute is the
containing
element for the
other attributes
that are listed
here.

action

Describes the
actions that can
be performed on
the content. This
attribute
represents the
action that the
target supports
for the types
specified in the
mime-type
attribute.
Include one
<action>

Adding Features

124

Attribute

Description
element for each
supported
action.

mime-type

Describes the
type of content.
This attribute
represents the
different types
for which the
specified actions
are supported.
You can specify
both the type
and subtype by
using wildcards
in a target filter.
For example, a
filter can specify
image/png,
image/*, or *.
Include one
<mime-type>
element for each
supported MIME
type.

uris

Describes the
supported URI
pattern that
must prefix the
URI that is
provided in the
invocation
request. This
attribute
represents the
URI prefixes that
describe how
the target

Adding Features

125

Attribute

Description
supports the
delivery of the
data. The URI
value may
contain the
single wildcard
character * to
indicate that the
filter
supports any del
ivery
mechanism.
If the target app
or a card
supports the
delivery of the
data as part of
the message
body, then it
should include
the data://
local URI.

exts

Represents the
list of file
extensions
supported by the
target. The
values specified
in this attribute
apply only to
file:// URIs.
When
extensions are
specified in a
target filter, they
are generally
specified in
conjunction with
a MIME type of
*.

Adding Features

126

Attribute

Description
A best practice
is to be as
specific as
possible when
specifying the
filter criteria, to
increase the
chances of
being selected
to handle the
invocation
request.
Wildcard
characters (*)
are considered a
relatively weak
match when
performing
selection, so if
your target
supports a
specific set of
types, you must
specify each of
the types in the
filter. In cases
where your app
supports both
specific MIME
types and
extensions, you
should split the
registration into
two separate
filters. One filter
registers for the
specific types
and one filter
registers for the
extensions
against the
MIME type of *.

Adding Features

127

When you declare a target filter, make sure that your filter description follows these rules:
The URI value cannot be set as a wildcard character (*). That is, you cannot declare <property var=
"uris" value="*"/> in your config.xml file.
If the target filter contains actions such as bb.action.VIEW or bb.action.OPEN, has MIME types set
as a wildcard character (*), and has the URI attribute set as data:// or file:// or left unstated, then
your app cannot be deployed or installed on the device.
For a target filter that uses the URI file:// and a MIME type wildcard character (*), to successfully
register with the invocation framework, you must also specify a file extension value that is not a wildcard
character (*).
If you declare a file extension value in the target filter, the file extension value is considered during the
brokering and selection process if it is used with a file:// URI.
If your app uses a target filter declaration that is invalid, then when your app is deployed, you will receive the
result::failure 884 Restricted Invoke Filter detected error.
Here are some examples of target filters that register successfully with the invocation framework:
actions=bb.action.OPEN;types=*;uris=http://;
actions=bb.action.OPEN,bb.action.VIEW;types=*;uris=file://;exts=jpg,gif,tif
;
actions=bb.action.VIEW;types=*;uris=data://;exts=jpg,gif,tif;
The following target filters do not follow the rules specified above and will not allow the app to be deployed or
installed on the device:

actions=bb.action.OPEN,bb.action.VIEW,bb.action.SET;types=*;uris=file://;
actions=bb.action.OPEN;types=*;uris=data://;
actions=bb.action.VIEW;types=*;uris=*;
actions=bb.action.VIEW;types=*;
actions=bb.action.OPEN,bb.action.VIEW;types=*;uris=file://;exts=*;

The following example describes an invoke target that has two filters. The first filter describes the support for
bb.action.OPEN and bb.action.VIEW actions on .png and .jpeg image files that are delivered in a file or
in the message body. The second filter describes the support for bb.action.OPEN and bb.action.VIEW
actions on any URI file with .jpg or .png extensions.
<invoke-target id="com.example.image.view">
<entry-point-id></entry-point-id>
<invoke-target-type>application</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.OPEN</action>
<mime-type>image/png</mime-type>
<mime-type>image/jpeg</mime-type>
<property var="uris" value="file://,data://local"/>
</filter>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.OPEN</action>
Adding Features

128

<mime-type>*</mime-type>
<property var="uris" value="file://"/>
<property var="exts" value="jpg,png"/>
</filter>
</invoke-target>
Target selection and brokering
When a client app queries the invocation framework for a suitable target or when it sends an unbound
invocation request, the invocation framework determines the set of suitable targets by comparing the
invocation request to all of the installed target filters defined for the apps on the BlackBerry device. This
process is called invocation brokering. Brokering uses a set of rules to determine how to match the invocation
request to each filter. Specifically, a filter is considered a match only if both the action rules and the data rules
are satisfied.

Rules for matching actions


A target filter is considered an action match in either of these two cases:
The action specified in the invocation request matches one of the actions that are specified in the target
filter.
If the invocation request does not specify an action, all filters are considered to be an action match.
If the target filter doesn't contain declaration of any actions, then it doesn't match any invocation requests.

Rules for matching data


The URI and MIME type are considered when the invocation data is matched. URI matching involves
comparing of the uris and exts attributes of the target filter with the uri attribute of the invocation request.
The composition of a URI looks like this:
<scheme>://<host>:<port>/<path> = <scheme>://<authority>/<path>
The host and port values are equal to the authority value. The scheme comparison is not case-sensitive
but the authority and path comparisons are case-sensitive. The uri is considered a match only if any of
the values specified in the target filters uris attribute is a prefix of the uri specified in the invocation
request.
Similarly, if the target filter specifies exts values, then that app is considered a match only if one of the exts
values is the suffix of the uri path that is provided in the invocation request.
Note: The invocation framework adds a dot separator between the specified exts value and the rest of the
path automatically when it performs the comparison.
A MIME type comparison is performed between the MIME type provided in the invocation request and the
MIME type that is provided in the target filter. Both the invocation request and the target filter may use a
wildcard character (*) in the subtype of the MIME type. Here are some factors that determine whether a target
filter is considered a MIME type match:
Adding Features

129

The URI and MIME type specified in the invocation request match with the target filter's uri and exts.
The wildcard character (*) is considered and is used for MIME type matching.
If the MIME type is specified, then the type is not inferred from the uri.
If the target filter doesn't specify any exts values, then the filter matches any extension.
The absence of the uri in either the invocation request or the target filter implies that the data attribute is
data://local.
If the invocation request does not specify a MIME type and a target filter declaration has matching URIs and
file extensions, then the invocation framework considers that target filter a MIME type match.
If the invocation request does not specify a uri and the target filter declares a matching MIME type but
either does not declare a uri, which implies that the data attribute is data://local, or explicitly
declares the uri as data://local, then the target filter is considered a MIME type match.
Unbound selection
When an unbound invocation has multiple targets that are suitable, the invocation framework chooses
a best fit target to invoke by using the brokering rules. Here are the rules that the selection process follows:
The filter that has the strongest URI match based on its length is selected.
When target filters are compared, only the scheme attribute is used for the URIs that are declared in the
config.xml file.
If more than one target filter has the longest matching URI, then the target filter with the strongest MIME
type match is selected. The type with the wildcard character (*) is considered the weakest match, the
subtype with the wildcard character type/* is considered weak, and a match without wildcard characters
is considered the strongest match.
If more than one target filter has the strongest MIME type match, then the target filter with an exts match
is selected if the uri attribute is defined in file:// format.
If more than one target filter has a matching ext, then the filter that the invocation framework marks as
default for that set of target filter criteria is selected.
If no target filter is identified as default, then the oldest target filter is selected as the best possible match.

Cards
A card allows an app to export a screen to another app. Unlike an app that may offer a full and rich set of
features, a card typically provides the ability to perform specific tasks such as picking a contact, composing an
email, or previewing an image. To a user, a card appears as part of the client app and does not appear as a
separate Active Frame.
Your app can export (or expose) a card, which makes it available for other apps to use. Your app can also
import cards that other apps expose, which lets your app use the feature or functionality of those cards.
An app can expose only one card at a time. However, one card can expose another card, which allows the app
to create a stack of cards that appear as part of the client app. Although the card appears as part of the client
app, it maintains its own process and security context. In the following sections, you will learn how to create
and use cards in your app, as well as how to expose them to other apps.

Adding Features

130

Card styles
When an app imports a card, the BlackBerry 10 OS controls the visual transition on and off the screen, but it
also controls the peek behavior that allows the user to look at the card under the card that's currently
displayed. The BlackBerry 10 OS manages the transition and the peek behavior based on the card's style.
Composers, pickers, and previewers
You can use three different styles of card in your app: composers for creating and editing content, pickers for
choosing existing content, and previewers for viewing existing content. The style of card you use determines
how the BlackBerry 10 OS transitions between the app and the card, how peeking is handled, and the general
task that a card performs. Each card style has associated visual style guidelines.
The following image shows picker, composer, and previewer cards:

Card transitions
A card transitions on or off the screen in a beautiful animation. The cards appears on the screen as sliding in
either from the bottom or from the right side. Previewers slide in from the right side, while composers and
pickers slide in from the bottom of the screen.
The following image shows the transition style of composers and pickers:

Adding Features

131

The following image shows the transition style of previewers:

Adding Features

132

Peeking
Peeking is the ability for a user to see under a card by using a gesture. There are two ways in which a user can
peek under the card:
Parent peek: The user slides a finger right to reveal the screen that lies immediately under the card.
Root peek: The user slides a finger right on the action bar to reveal the app at the bottom of the stack of
cards.
The following image shows the parent and root peek:

Not all card styles support both peek types. Composer and picker cards support only parent peek, and
previewer cards support both types.
UI consideration for cards
For a great user experience, here are some guidelines to consider if you want to use cards in your app:

Adding Features

133

Description

Composers

Previewers

Pickers

Button(s) in the title bar


of the screen

Yes

No

Yes

Action bar at the bottom


of the screen

No

Yes

Yes

Supports context menu

Yes

Yes

No

To learn what the action bar, context menu, and buttons are, see The basics in the UI Guidelines for
BlackBerry 10.
Note: When you create a card, you must add support for both landscape and portrait orientation so that the
card follows the orientation of your app.

Invoking cards
Cards enhance the invocation framework's capabilities by allowing apps to share the UI and the app logic with
other apps. You send a request to invoke a card in the same way as an invocation request for an app, which
means that everything that you learned about sending an invocation request, applies to cards as well. Before
your app can invoke cards, you must add the invocation plugins to your app. To add the plugins, on the
command line, navigate to your project folder and run the following commands:
webworks plugin add com.blackberry.invoke
webworks plugin add com.blackberry.invoke.card
Here's how you can use the invocation framework to import a card from another app:
blackberry.invoke.invoke({
target: "com.acme.myapp",
action: "bb.action.VIEW",
type: "image/png",
uri : "file://path/to/image.png"
}, onInvokeSuccess, onInvokeError);
Before a new card is invoked and allowed to be stacked, the BlackBerry 10 OS verifies that the client app is not
already parenting a card. Unlike an app, a card may continue to exist in multiple instances, but a parent app
(or card) can parent only one card at a time. This is important because multiple instances of a card may be
running at the same time.
Cards support a "fire and forget" import model. However, for apps that require notifications and additional
feedback, cards also provide peek notifications and response data.

Adding Features

134

Listen for peek events


Cards offer a parent card or an app the ability to receive notifications when a user peeks at another card. This
is important if you want your app to display content differently during a peek event.
Here is how you can enable your app to listen for peek events:
function onChildCardStartPeekHandler(peekType) {
console.log("The card started peeking.");
if (peekType == "root") {
updateContent(true);
}
}
function onChildCardEndPeekHandler() {
console.log("I am no longer being peeked at.");
}
document.addEventListener("onChildCardStartPeek",
onChildCardStartPeekHandler);
document.addEventListener("onChildCardEndPeek", onChildCardEndPeekHandler);

Listen for a card response message


A card can send a response message to the parent app when a card completes its task. For example, a picker
card can return the data that a user selects to the client app.
Here's how you can listen for card response messages:
function onCardClosedHandler(info) {
console.log("Card was closed: " + info);
}
document.addEventListener('onChildCardClosed',onCardClosedHandler);
If you're using previewer or composer cards, you don't usually need to handle a response. You should design
your previewer and composer cards so that any response is optional.

Close a card
An app can request to close a card that it imported. As a result, the card is transitioned off of the screen. When
a user closes the card, both the app and the card are notified. However, if the card is closed by the app itself,
the card cannot provide a response. Also, when an app closes a card, it closes the entire stack of cards
(including children of the card) above it.
Here's how your app can request to close a child card:
blackberry.invoke.closeChildCard();
Adding Features

135

To learn more about APIs that support card invocation and read code samples, see card.

Creating your own cards


A great way to get your app noticed is to export your app's cards, so other apps can import them. Creating
cards is similar to creating a small, focused app. One of the key differences, however, is that unlike an app, a
card can have multiple instances running at the same time. The BlackBerry 10 OS creates a new instance for
each client app. In many cases, the BlackBerry 10 OS will pool your card (pooling is discussed a bit later). This
section can help you understand how you can use cards to expose your app's functionality to other apps.
A card shares an execution context across multiple instances of itself. For example, all instances of a card run
in the same workspace directory and use the same permissions. This feature of cards is important when you
consider how you use your resources. If you read and write files, make sure you coordinate access across
different instances of your card. Any cards that your app exports are packaged in the same .bar file as the app.

Registering a card target


Because a card is used through an invocation request, the first step in exporting a card is to register an
invocation target for it. Registering card targets is the same as declaring your app as a target except for a minor
difference. The <invoke-target-type> tag must specify one of the card styles supported by the
BlackBerry 10 OS. The valid values for <invoke-target-type> are card.previewer,
card.composer, and card.picker. Registering in this way informs the BlackBerry 10 OS that you are
exporting a card and describes the style of the card, so the BlackBerry 10 OS can handle it appropriately.
Just like apps, cards are packaged and identified as invocation targets in the config.xml file. Here's an example
that shows you how to declare a card:
<invoke-target id="com.acme.myapp">
<invoke-target-type>card.previewer</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.SHARE</action>
<mime-type>image/png</mime-type>
<mime-type>image/jpeg</mime-type>
<property var="uris" value="file://"/>
</filter>
</invoke-target>

Requesting your card to be closed


After a card finishes its task, it can request to be closed. When this request is processed, the card is
transitioned off the screen and its parent app is notified. While the card closes itself, it can also send a
response message to the parent application.

Preparing your card for pooling


You can create your cards so they can be pooled when a user closes the card. Pooling helps to keep frequently
used cards ready for reuse, which reduces loading and transition time when cards are stacked. For example, if
Adding Features

136

the user is viewing one email after another, instead of exporting a new card for every email, the BlackBerry 10
OS may pool the existing email previewer card and use it again.
When you're creating a card, you must consider several things before you handle pooling events, such as
which resources your cards should clean up or keep when they're pooled.
First, consider adding support for purging the state of the card. While pooled cards are not terminated, they
may be suspended to keep them from processing while pooled. When your card is pooled, it should release
resources such as files or database connections until it is resumed again. When a card receives a
cardPooled() signal, it should clear its current state and listen for future invocations. In addition, cards
must be written to support multiple instances which run simultaneously in the same sandbox.
Second, if an app with cards defines several card targets, then when it's retrieved from the pool, the card may
be invoked to service any of the declared targets. In other words, if a .bar file bundles a composer, previewer,
and picker under a single entry point, then when it's retrieved from the pool, the app or card may be invoked as
any of these targets.

Preparing your cards for resizing and rotation


Note: When you create cards, you must add support for both landscape and portrait orientation so that the
card follows the orientation of your app.

Card security
Cards have their own identity and sandbox environment that is shared with all instances of the card. Like apps,
cards are processed in their own context and with their own permissions. It is important to pay attention to the
capabilities and the data that you want to expose using your card.
To learn more about APIs that support card invocation and read code samples, see card.

Invoking core apps


You can use the invocation framework to integrate your app with core apps in the BlackBerry 10 OS. For
example, you can enable your app to register with the invocation framework and invoke the BlackBerry
Browser app to open and display any URLs that appear in your app. Here's a list of frequently used core apps
with their respective invocation attributes and the values that are required to invoke them:

Adobe Reader

Maps

Adding Features

137

BBM
Media Player
BlackBerry Browser
Miracast card
BlackBerry World
NFC
Phone
Bluetooth
Calendar

Pictures

Camera
Picture editor
Remember
Clock
Contacts

Search

Adding Features

138

Settings
Device Monitor
Docs to Go

Text Messages
Twitter

Email

Facebook

Video editor

Foursquare

Voice note

LinkedIn

YouTube

Adobe Reader
Opening a .pdf file
Here are the invocation attributes you use to open a .pdf file in the Adobe Reader app:

Adding Features

139

Attribute
Target ID
Action
URI
MIME type
File extensions

Value
com.rim.bb.app.adobeReader
bb.action.OPEN
file:///path/to/my/content.pdf
application/pdf
.pdf

Here are the invocation attributes you use to open a .pdf file in a previewer card:
Attribute
Target ID
Action
URI
MIME type
File extensions

Value
com.rim.bb.app.adobeReader.viewer
bb.action.VIEW
file:///path/to/my/content.pdf
application/pdf
.pdf

BBM
Sharing a file with BBM
Here are the invocation attributes you use to share a file with BBM:

Adding Features

140

Attribute
Target ID
Action
URI

Value
sys.bbm.sharehandler
bb.action.SHARE
file:///path/to/my/content.doc

Opening the BBM app


Here are the invocation attributes you use to open the BBM app:
Attribute
Target ID
Action

Value
sys.bbm
bb.action.OPEN

Setting a BBM display picture


Here are the invocation attributes you use to set a picture as a BBM display picture:
Attribute
Target ID
Action
URI

Value
sys.bbm.imagehandler
bb.action.SET
file:///path/to/my/content.jpg

Sharing text with BBM


Here are the invocation attributes you use to share text with BBM:
Adding Features

141

Attribute
Target ID
Action
MIME type
Data

Value
sys.bbm.sharehandler
bb.action.SHARE
text/plain
Text string to be shared

Sharing text or an image with BBM Groups


Here are the invocation attributes you use to share text or an image with BBM Groups:
Attribute
Target ID
Action
URI

Value
sys.bbgroups.sharehandler
bb.action.SHARE
file:///path/to/my/content.txt or
file:///path/to/my/image.png

Inviting a user to BBM or starting a BBM chat


Here are the invocation attributes you use to invite a user to BBM or to start a BBM chat:
Attribute
Target ID
Action

Value
sys.bbm.sharehandler
bb.action.BBMCHAT

Adding Features

142

Attribute
URI

Value
pin:<pin>

Note: This invocation action displays either an Invite to BBM screen or the BBM chat composer screen
depending on whether the specified PIN is already a BBM contact.

Inviting a user to BBM


Here are the invocation attributes you use to invite a user to BBM:
Attribute
Target ID
Action
URI

Value
sys.bbm.sharehandler
bb.action.INVITEBBM
pin:<pin>

Starting a BBM audio or video chat


Here are the invocation attributes you use to start a BBM audio or video chat with a contact:
Attribute
Target ID
Action
Data

Value
sys.service.videochat
bb.action.OPEN
dest=<BlackBerry ID or PIN of
contact>&video=<0 or 1>
The value 0 is specified for an audio call and 1 is
specified for a video call (for example,
dest=user01@example.com&video=1).

Adding Features

143

Invoking your BBM Channel


Here are the invocation attributes you use to invoke your BBM Channel from within your app:
Attribute
Target ID
Action
URI

Value
sys.bbm.channels.card.previewer
bb.action.OPENBBMCHANNEL
bbmc:<my BBM channel PIN>

Sharing text or an image with BBM Channels


Here are the invocation attributes you use to share a text or an image with BBM Channels:
Attribute
Target ID
Action
URI

Value
sys.bbm.channels.sharehandler
bb.action.SHARE
file:///path/to/my/content.doc,
file:///path/to/my/image.jpg

Starting a multi-person chat


Here are the invocation attributes you use to start a multi-person chat in BBM:
Attribute
Target ID
Action

Value
sys.bbm.sharehandler
bb.action.BBMCONF

Adding Features

144

Attribute
MIME type

Value
vnd.bb.bbm/contactlist

Data must be sent in JSON format, as follows:


"conference": {
"contacts" : [
{ "pin" : "1234ABCD" },
{ "pin" : "1234567A" },
]
}
When sending data, you must specify the contact's PIN in the pin field.
Note: API support for starting a group chat in BBM is available in API level 10.1 and later of the BlackBerry 10
Native SDK.

BlackBerry Browser
Opening a URL
Here are the invocation attributes you use to open a URL:
Attribute

Value

Target ID

sys.browser

Action

bb.action.OPEN

MIME type

Any valid MIME type value

URI

http://
https://
ftp://

Opening local content


Here are the invocation attributes you use to open local content:

Adding Features

145

Attribute

Value

Target ID

sys.browser

MIME type

text/html
application/xhtml+xml
image/svg+xml

Action

bb.action.OPEN

File extensions

URI

file://

htm
html
xhtml
svg

BlackBerry World
Opening a specific page in BlackBerry World
Here are the invocation attributes that you use to open a specific page in the BlackBerry World storefront:
Attribute
Target ID
Action

Value
sys.appworld
bb.action.OPEN

Here's a list of URIs that you use to open various other pages in BlackBerry World:
Page

URI

Home page

appworld://

Content details for an ID (for example, for games,


apps, albums, tracks, movies, TV show series, or TV
show season or episode)

appworld://content/<contentid>

Adding Features

146

Page

URI

Category listing for an ID

appworld://category/<categoryid>

Editorialized Merchandising Unit (EMU) for an ID

appworld://emu/<emuid>

Search results for a search term

appworld://search/<searchterm>

Vendor page for an ID

appworld://vendor/<vendorid>

My World

appworld://myworld

My World subscriptions

appworld://myworld/subscriptions

Content control

appworld://parentalcontrol

Games

appworld://games

Apps

appworld://apps

Music

appworld://music

Video

appworld://video

Any unknown command opens the home page of


BlackBerry World

appworld://<???>

Opening a specific page in BlackBerry World for Work


Here are the invocation attributes that you use to open a specific page in BlackBerry World for Work:
Attribute
Target ID
Action

Value
sys.enterpriseappworld
bb.action.OPEN

Here's a list of URIs that you use to open various other pages in BlackBerry World for Work:
Page

URI

Home page

entappworld://

My World

entappworld://myworld

Adding Features

147

Page

URI

App details

entappworld://package/<packageid>

Any unknown command opens the home page of


BlackBerry World for Work

entappworld://<???>

Bluetooth
Sharing a local file
Here are the invocation attributes you use to invoke a Bluetooth card to share a local file:
Attribute
Target ID
Action

Value
sys.btviewer
bb.action.SHARE

URI

Any valid URI value that is preceded by file:// for


a single file

MIME type

Any valid MIME type value, such as audio/mp3,


image/jpg, or application/myfiletype

Data must be sent in JSON format, as follows:


[

"uri": "file:///path/to/file"

},
...

Note: For sharing multiple files, the URI is preceded by list://.

Calendar
Creating an event
Here are the invocation attributes that you use to open a calendar card to create an event:
Adding Features

148

Attribute
Target ID
Action
MIME type

Value
sys.pim.calendar.viewer.eventcreate
bb.action.CREATE
text/calendar

Description

Data

Account ID of the event

unsigned int accountId

Folder ID of the event

unsigned int folderId

List of participant email addresses

"participants":
["email1@xyz.com","email2@xyz.com"]

Subject of the event

"subject":"<text>"

Body of the event

"body":"<text>"

Start time of the event

String startTime

Location of the event

QString location

Duration of the event

int duration

Picking an existing event


Here are the invocation attributes that you use to open a calendar card to pick an existing event:
Attribute
Target ID
Action
MIME type

Value
sys.pim.calendar.viewer.nav
bb.calendar.PICK
text/calendar

Adding Features

149

Here's the card response that you receive:


Reason

Data

Description

Done

Event data in VCS format

This response is returned when the


user picks an event, after which
the card closes.

Editing an existing event


Here are the invocation attributes that you use to open a calendar card to edit an existing event:
Attribute
Target ID
Action
MIME type

Value
sys.pim.calendar.viewer.eventcreate
bb.calendar.EDIT
text/calendar

Description

Data

Account ID of the existing event

unsigned int accountId

Folder ID of the event (optional)

unsigned int folderId

Event ID

unsigned int eventID

Start time of the event (optional)

QString startTime

Note: The start time lets you differentiate between any two or more recurring events that have the same
eventID.

Viewing an .ics file


Here are the invocation attributes that you use to launch a calendar card to view an .ics file:

Adding Features

150

Attribute
Target ID
Action
MIME type
URI

Value
sys.pim.calendar.viewer.ics
bb.action.OPEN
text/calendar
file:///path/to/my/file/filename.ics

If you want to open the .ics file for a specific account, you can set an account ID in the data attribute of the
invocation request.
Description

Data

Account ID of the existing event

unsigned int accountId

Opening the calendar app


Here are the invocation attributes that you use to open the calendar app:
Attribute

Value

Action

bb.calendar.OPEN

MIME type

text/calendar

Data

"data":"file:///path/to/file.txt"

Adding Features

151

Query name

Query value

Description

view

Opens a specific view of the


calendar app (for example,
monthly view).

calendars

<account-id><folderId>
<account-id>-<syncId>

Opens the calendar app with only


the specified calendars visible. You
can enable multiple calendars by
providing a comma-separated list
of <account-id>-<folderId>
and <account-id>-<syncId>.

date

Date must be in the following


format: Wed Jun 13 2012

Opens the calendar view for the


specified date.

monthly
agenda
people
schedule
weekly

Viewing an existing event


Here are the invocation attributes that you use to launch a calendar card to view an existing event:
Attribute
Target ID
Action
MIME type

Value
sys.pim.calendar.viewer.ics
bb.calendar.OPEN
text/calendar

Description

Data

Account ID of the existing event

unsigned int accountId

Event ID of the existing event

unsigned int eventId

Adding Features

152

Description

Data

Start time of the existing event. You can use this


attribute to distinguish between any recurring events
that have the same event ID.

The start time string should be in the following format:


"yyyy-MM-dd HH:mm:ss"

Type

"event"

Here are the invocation attributes that you use to open the calendar app to view an existing event:
Attribute

Value

Action

bb.calendar.VIEW

MIME type

text/calendar

Data

"data":"file:///path/to/file.txt"

Query name

Query value

Description

accountId

<account-id>

Account ID of the event.

eventId

<event-id>

Event ID of the event.

date

The start time must be in the


following format: 2012-06-13
09:39:56

The start time of the event. This


attribute is required only for
recurring events to identify which
of the events in a recurring event
should be opened.

Type

"event"

The type of the event. This


attribute is required for opening an
existing event with the calendar
app.

To learn more about invoking calendar cards and read code samples, see the API documentation on calendar
event composer and calendar event picker cards.

Adding Features

153

Camera
Opening the Camera card
Here are the invocation attributes you use for opening the camera card:
Attribute

Value

Target ID

sys.camera.card

Action

bb.action.CAPTURE

Data

photo, video, or full (where full is the default


value, in case a value is not specified)

Here are the responses of the Camera cards:


Reason

Data

Description

done

Not applicable

This response is returned if a card


is closed when a user presses the
back button without initiating a
capture.

close

Includes an error message in the


data attribute, if applicable.

This response is returned when the


card closes due to an error. Here
are the possible errors for the
card's closure that are returned in
the data field of the invocation
response:
Too many files open,
picture save failed.
Insufficient space to
save the picture.
Picture save failed.

save

Includes a full path to the saved


file.

This response is returned if a card


is closed after a user takes a

Adding Features

154

Reason

Data

Description
picture or records a video. The
captured file is returned in the data
field of the message.

Opening the Camera app


Here are the invocation attributes you use for invoking the Camera app:
Attribute
Target ID
MIME type
Action
Data

Value
sys.camera.app
image/jpeg or video/mp4
bb.action.CAPTURE
photo, video, or full (full is the default if
nothing is specified)

When the Camera app is opened, it is not locked to any particular mode, regardless of the data parameter's
description. The user can change the mode of the Camera app at any time. For example, a user can choose
between the photo capture mode, video capture mode, and the timeshift mode. Also, if an instance of the
Camera app is already running, it is displayed instead of a new instance being started. Similarly, the instances
that are running don't change the mode specified in the data parameter.

Clock
Opening the clock application
Here are the invocation attributes you use to open the clock app:

Adding Features

155

Attribute
Target ID
Action

Value
bb.clock.launcher
bb.action.VIEW

MIME type

text/plain

Data

Description

alarmClockPane

Launches the alarm clock view

worldClockTab

Launches the world clock view

stopwatchTab

Launches the stopwatch view

timerTab

Launches the timer view

Contacts
Viewing a contact
Here are the invocation attributes you use to launch the contacts app to view a contact:
Attribute
Target ID
Action
MIME type
Data

Value
sys.pim.contacts.app
bb.action.OPEN
application/vnd.blackberry.contact.id
Contact ID integer.

Adding a new contact


Here are the invocation attributes you use to launch the contacts app to add a new contact:
Adding Features

156

Attribute
Target ID
Action
MIME type

Data

Value
sys.pim.contacts.app
bb.action.ADDTOCONTACT
application/
vnd.blackberry.string.phone,
application/
vnd.blackberry.string.email,
application/vnd.blackberry.string.pin
Depending on the MIME type, you could use the
phone number string, email address string, or the PIN
string.

Opening a vCard contact attachment


Here are the invocation attributes you use to open a vCard contact attachment (.vcf file) using a contact
previewer card:
Attribute
Target ID
Action
URI

Value
sys.pim.contacts.card.viewer
bb.action.VIEW
file:// (for example, file:///
path/to/file.vcf)

Here are the invocation attributes you use to launch the contacts app to open a vCard contact attachment (.vcf
file):

Adding Features

157

Attribute
Target ID
Action
URI

Value
sys.pim.contacts.app
bb.action.OPEN
file:// (for example, file:///
path/to/file.vcf)

Creating a new contact


Here are the invocation attributes you use to create a new contact using a contact composer card:
Attribute
Target ID
Action

Value
sys.pim.contacts.card.composer
bb.action.CREATE

Editing an existing contact


Here are the invocation attributes you use to edit an existing contact using a contact composer card:
Attribute
Target ID
Action
MIME type

Value
sys.pim.contacts.card.composer
bb.action.EDIT
application/
vnd.blackberry.string.contact,
application/contact

Adding Features

158

Attribute

Value

Data

Contact ID integer

Here are the invocation attributes you use to view a contact using a contact previewer card:
Attribute
Target ID
Action
MIME type

Data

Value
sys.pim.contacts.card.viewer
bb.action.VIEW
application/contact, application/
vnd.blackberry.string.contact,
application/vnd.blackberry.contact.id
Contact ID integer.

Setting a picture of an existing contact


Here are the invocation attributes you use to set a picture of an existing contact:
Attribute
Target ID
Action
URI

Value
sys.pim.contacts.setcontactpicture
bb.action.SET
file:// (e.g. file:///path/to/
photo.jpg)

Adding Features

159

Device Monitor
Opening the Device Monitor
Here are the invocation attributes you use for the Device Monitor app:
Attribute
Target ID
Action
MIME type

Value
sys.SysMon.app
bb.action.OPEN
You should specify a wildcard character *

Here are the invocation attributes you use for the Device Monitor card:
Attribute
Target ID
Action
MIME type

Value
sys.SysMon.card
bb.action.VIEW
You should specify a wildcard character *

Here's a list of URIs you can use to invoke the Device Monitor card or the app:
Setting
CPU
Battery
Storage
Memory

URIs
devicemonitor://cpu
devicemonitor://battery
devicemonitor://storage
devicemonitor://memory

Adding Features

160

Here's an example to show how you can invoke the Device Monitor app:
<invoke-target id="sys.SysMon.app">
<entry-point-id>sysmon_app</entry-point-id>
<invoke-target-type>APPLICATION</invoke-target-type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>*</mime-type>
<property var="uris" value="devicemonitor://"/>
</filter>
</invoke-target>
Here's an example to show how you can invoke the Device Monitor card:
<invoke-target id="sys.SysMon.card">
<entry-point-id>sysmon_app</entry-point-id>
<invoke-target-type>card.previewer</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>*</mime-type>
<property var="uris" value="devicemonitor://"/>
</filter>
</invoke-target>

Docs to Go
Opening a spreadsheet
Here are the invocation attributes you use to open a spreadsheet in a previewer card:
Attribute
Target ID
Action
URI
MIME type

Value
sys.sheettogo.previewer
bb.action.VIEW
file:///path/to/my/content.xls
application/vnd.ms-excel,
application/vnd.openxmlformats-

Adding Features

161

Attribute

Value
officedocument.spreadsheetml.sheet,
application/vnd.openxmlformatsofficedocument.spreadsheetml.template
, application/vnd.msexcel.sheet.macroEnabled.12,
application/vnd.msexcel.template.macroEnabled.12

File extensions

.xls, .xlt, .xlsx, .xltx, .xlsm, .xlt


m

Here are the invocation attributes you use to open a spreadsheet file in the Docs to Go app:
Attribute
Target ID
Action
URI
MIME type

File extensions

Value
sys.dxtg.stg
bb.action.OPEN
file:///path/to/my/content.xls
application/vnd.ms-excel,
application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet,
application/vnd.openxmlformatsofficedocument.spreadsheetml.template
, application/vnd.msexcel.sheet.macroEnabled.12,
application/vnd.msexcel.template.macroEnabled.12
.xls, .xlt, .xlsx, .xltx, .xlsm, .xlt
m

Adding Features

162

Opening a presentation
Here are the invocation attributes you use to open a presentation in a previewer card:
Attribute
Target ID
Action
URI
MIME type

File extensions

Value
sys.slideshowtogo.previewer
bb.action.VIEW
file:///path/to/my/content.ppt
application/vnd.ms-powerpoint,
application/vnd.openxmlformatsofficedocument.presentationml.present
ation, application/
vnd.openxmlformatsofficedocument.presentationml.templat
e, application/vnd.openxmlformatsofficedocument.presentationml.slidesh
ow, application/vnd.mspowerpoint.presentation.macroEnabled.
12, application/vnd.mspowerpoint.template.macroEnabled.12,
application/vnd.mspowerpoint.slideshow.macroEnabled.12
.ppt, .pot, .pps, .pptx, .potx, .ppsx
, .pptm, .potm, .ppsm

Here are the invocation attributes you use to open a presentation file in the Docs to Go app:
Attribute
Target ID
Action

Value
sys.dxtg.stg
bb.action.OPEN

Adding Features

163

Attribute
URI
MIME type

File extensions

Value
file:///path/to/my/content.ppt
application/vnd.ms-powerpoint,
application/vnd.openxmlformatsofficedocument.presentationml.present
ation, application/
vnd.openxmlformatsofficedocument.presentationml.templat
e, application/vnd.openxmlformatsofficedocument.presentationml.slidesh
ow, application/vnd.mspowerpoint.presentation.macroEnabled.
12, application/vnd.mspowerpoint.template.macroEnabled.12,
application/vnd.mspowerpoint.slideshow.macroEnabled.12
.ppt, .pot, .pps, .pptx, .potx, .ppsx
, .pptm, .potm, .ppsm

Opening a document
Here are the invocation attributes you use to open a document in a previewer card:
Attribute
Target ID
Action
URI
MIME type

Value
sys.wordtogo.previewer
bb.action.VIEW
file:///path/to/my/content.doc
application/msword, text/plain,
application/vnd.openxmlformatsofficedocument.wordprocessingml.docum

Adding Features

164

Attribute

Value
ent, application/vnd.openxmlformatsofficedocument.wordprocessingml.templ
ate, application/vnd.msword.document.macroEnabled.12,
application/vnd.msword.template.macroEnabled.12

File extensions

.doc, .dot, .txt, .docx, .dotx, .docm


, .dotm

Here are the invocation attributes you use to open a document file in the Docs to Go app:
Attribute
Target ID
Action
URI
MIME type

File extensions

Value
sys.dxtg.stg
bb.action.OPEN
file:///path/to/my/content.doc
application/msword, text/plain,
application/vnd.openxmlformatsofficedocument.wordprocessingml.docum
ent, application/vnd.openxmlformatsofficedocument.wordprocessingml.templ
ate, application/vnd.msword.document.macroEnabled.12,
application/vnd.msword.template.macroEnabled.12
.doc, .dot, .txt, .docx, .dotx, .docm
, .dotm

Adding Features

165

Email
Sharing a file
Here are the invocation attributes you use to share a file:
Attribute
Target ID
Action
URI
MIME type

Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE
file:///path/to/file
Any valid MIME type value

Sharing an .ics file


Here are the invocation attributes you use to share an .ics file:
Attribute
Target ID
Action
URI
MIME type

Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE
file:///path/to/event.ics
text/calendar

Sharing text
Here are the invocation attributes you use to share text through an email composer:

Adding Features

166

Attribute
Target ID
Action

Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE

MIME type
Data

text/plain
Text to share as a QByteArray

Sharing multiple files


Here are the invocation attributes you use to share multiple files through an email composer:
Attribute
Target ID
Action

Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE

URI

list://

MIME type

filelist/[subtype]

Data must be sent in JSON format, as follows:


[

"uri": "file:///path/to/file"

},
...

Composing an email with prepopulated fields


Here are the invocation attributes you use to compose an email with prepopulated fields using a mailto:
URI:
Adding Features

167

Attribute
Target ID
Action

Value
sys.pim.uib.email.hybridcomposer
bb.action.OPEN, bb.action.SENDEMAIL

For the URI attribute:


For the URI attribute, use a standard mailto: URI and make sure that the entire URI is percent-encoded.
If you want to prepopulate the recipient field with more than one entry, use the following format:
mailto:address1@domain.com?to=address2@domain.com
If you want to prepopulate the CC, BCC, subject, and the message body fields, use the following format:
mailto:address@domain.com?cc=address2@domain.com&bcc=
address3@domain.com&subject=A%20Subject&body=That%20body
Here are the invocation attributes you use to compose an email with prepopulated fields using data in JSON
format:
Attribute
Target ID
Action
MIME type

Value
sys.pim.uib.email.hybridcomposer
bb.action.COMPOSE
message/rfc822

Data should be sent in JSON format, as shown below:


{

"to" : ["a@a.com", "b@b.net"],


"accountid" : 1234,
"cc" : ["foo@bar.com", "stuff@place.com"],
"bcc" : ["foo@bar.com", "stuff@place.com"],
"subject" : "Some punctuation. Symbol in the $ubject!!",
"body" : "HI! Here is some more stuff.\n\n14% of emails have #1 newline

or

Adding Features

168

stuff* @ home.\n",
"attachment" : ["file:///path/to/my/item.txt"]
}
The accountid field in the code above represents the account ID that is used as a default value for the
composer card.

Replying to or forwarding an existing message


Here are the invocation attributes you use to reply to, reply to all, and forward an existing message:
Attribute
Target ID
Action

MIME type

Value
sys.pim.uib.email.hybridcomposer
bb.action.REPLY, bb.action.REPLYALL,
bb.action.FORWARD
message/rfc822

The URI points to the message that is being replied to or being forwarded and is sent in the following format:
pim:message/rfc822:[accountID]:[messageID]

Viewing an existing message


Here are the invocation attributes you use to view an existing message:
Attribute
Target ID
Action
MIME type

Value
sys.pim.uib.email.previewer
bb.action.VIEW
message/rfc822

The URI points to the message that is viewed and is sent in the following format:
pim:message/rfc822:[accountID]:[messageID]
Adding Features

169

Facebook
All the invocation attributes related to the Facebook app require a Facebook account to be set up on the
device.

Sharing text with Facebook


Here are the invocation attributes you use to share text with Facebook:
Attribute
Target ID
Action

Value
Facebook
bb.action.SHARE

MIME type

text/plain

URI

data://

Data

Text string to be shared

Sharing media with Facebook


Here are the invocation attributes you use to share media (pictures and video) with Facebook:
Attribute
Target ID
Action

Value
Facebook
bb.action.SHARE

URI

file:///path/to/content.png

File extensions

.gif, .jpeg, .jpg, .png, .psd, .tiff,


.tif, .3g2, .3gp, .
3gpp, .asf, .avi, .dat, .flv, .m4v, .
mkv, .mod, .mov, .mp4, .mpe, .mpeg4,
.mpg, .nsv, .ogm, .ogv, .qt, .tod, .v
ob, .wmv

Adding Features

170

Attribute

Value

MIME type

MIME type can specified in the following format:


image/gif, image/jpeg, video/mov, video/
mpeg4, and so on

Sharing a URL with Facebook


Here are the invocation attributes you use to share a URL with Facebook:
Attribute
Target ID
Action

Value
Facebook
bb.action.SHARE

URI

http://, https://

Entry

Description

object_type

Specifies the type of the profile (for example, page


for a business profile or user for a personal profile.

object_id

Specifies the numeric ID of the Facebook profile


page. The numeric ID can be found within the URL of
the Facebook profile page (for example,
www.facebook.com/profile.php?
id=328506290597521).
Here's a useful link to identify the profile ID of a
Facebook profile.

Here's an example that shows how you can open a business profile page:
blackberry.invoke.invoke( {
target: "com.rim.bb.app.facebook",
action: "bb.action.OPEN",
Adding Features

171

metadata: JSON.stringify
({object_type : 'page' , object_id : '328506290597521'})
}, onSuccess, onError );

Foursquare
Opening a single sign-on card
Here are the invocation attributes you use to open a single sign-on card:
Attribute
Target ID
Action
MIME type
Data

Value
com.foursquare.blackberry.sso.card
bb.action.VIEW
sso/foursquare
Client ID (for example,
JDHEN48FRJ47FJFRI4FJFRJ4843JRF8484JFK
DOEWYU37RUJ)

Searching for a venue


Here are the invocation attributes you use to search for a venue:
Attribute
Target ID

Action
MIME type
URI

Value
com.foursquare.blackberry.venuesearch
.card
bb.action.VIEW
venuesearch/foursquare
"foursquare://venues/search?
oauth_token=" + accessToken

Adding Features

172

Exploring a venue
Here are the invocation attributes you use to explore a venue:
Attribute
Target ID
Action
URI

Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://venues/explore

Opening a venue card


Here are the invocation attributes you use to open a venue card:
Attribute
Target ID
Action
URI

Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://venues/<VENUE ID> (for
example, foursquare://venues/
4ef0e7cf7beb5932d5bdeb4e)

Opening a check-in card


Here are the invocation attributes you use to open a check-in card:
Attribute
Target ID

Value
com.foursquare.blackberry.uri

Adding Features

173

Attribute
Action
URI

Value
bb.action.OPEN
foursquare://checkins/<check-in ID> (for
example, foursquare://checkins/
50a08609e4b04c46ea54446d)

Opening the user profile


Here are the invocation attributes you use to open a user profile:
Attribute
Target ID
Action
URI

Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/self/update

Opening friend requests


Here are the invocation attributes you use to open friend requests:
Attribute
Target ID
Action
URI

Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/requests

Adding Features

174

Opening friend suggestions


Here are the invocation attributes you use to open friend suggestions:
Attribute
Target ID
Action
URI

Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/suggest?
type=friend

Opening page suggestions


Here are the invocation attributes you use to open page suggestions:
Attribute
Target ID
Action
URI

Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/suggest?type=page

Adding friends
Here are the invocation attributes you use to add friends from Contacts, Twitter, Facebook, or Search:
Attribute
Target ID
Action

Value
com.foursquare.blackberry.uri
bb.action.OPEN

Adding Features

175

Attribute
URI

Value
foursquare://users/addfriends?
from=phonebook

LinkedIn
All the invocation attributes related to the LinkedIn app require a LinkedIn account to be set up on the device.

Sharing text with LinkedIn


Here are the invocation attributes you use to share text with LinkedIn:
Attribute
Target ID
Action

Value
LinkedIn
bb.action.SHARE

MIME type

text/plain

URI

data://

Data

Text string to be shared

Opening a LinkedIn profile


Here are the invocation attributes you use to open a LinkedIn profile:
Attribute

Value

Target ID

com.linkedin.urihandler

Action

bb.action.VIEW

Adding Features

176

Attribute

Value

URI

linkedin:contact:<public_URL_of_the_L
inkedIn_profile_page>
The public URL can be in the following format:
ca.linkedin.com/...

Maps
You can invoke BlackBerry Maps by using the Invoke API with the following invocation attributes:
Attribute

Value

Action

bb.action.OPEN

MIME type

application/vnd.rim.map.action-v1

The MIME type above defines all the actions that BlackBerry Maps handles. For example, setting the map
center or starting navigation mode. The data passed in the invocation request is in JSON format.

Displaying a single location on the map


In addition to the action and MIME type attributes mentioned above, you can use the following data attributes
to invoke the BlackBerry Maps app to display a single location on the map.
Attribute

Values

Description

center

JSON object

Defines the latitude, longitude,


heading, and altitude of the map
center. The default value depends
on the location being displayed.

center.latitude

[-90.0,90.0]

Latitude in decimal degrees. This


value is required.

center.longitude

[-180.0,180.0]

Longitude in decimal degrees. This


value is required.

Adding Features

177

Attribute

Values

Description

center.heading

[0,359]

Heading in degrees from true


North

center.altitude

An integer value greater than or


equal to 0

Altitude in meters from ground.


The default value is 0.

placemark

JSON object

Defines a location to add to the


map as a pin and center the map
on it

placemark.latitude

[-90.0,90.0]

Latitude in decimal degrees

placemark.longitude

[-180.0,180.0]

Longitude in decimal degrees

placemark.name

String

Location name

placemark.description

String

Location description

placemark.geocode

true or false

Defines whether to geocode or


reverse geocode the location. The
default value is false.
If the value is true, geocode the
placemark when a name is
provided and latitude/longitude is
not provided.
Also, if the value is true, reverse
geocode the placemark when the
name is not provided and latitude/
longitude is provided.

geolocation

true or false

Find the current location of the


device when the app launches.
The default value is false.

Launching the Maps app


blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1"
}
);
Adding Features

178

Launching the Maps app and getting the current device location
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"geolocation": true
}
)
}
);

Launching the Maps app and centering the map at a particular location
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"center": {
"latitude": 43.4667,
"longitude": -80.5167,
"altitude": 2000
}
}
)
}
);

Launching the Maps app and adding a pin to the map


blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"placemark": {
"latitude": 43.4667,
"longitude": -80.5167,
"name": "Waterloo",
"description": "Waterloo, Ontario, Canada"
}
}
)
}
);
Adding Features

179

Invoking the Maps app for navigation


You can use the following data attributes to invoke the BlackBerry Maps app in navigation mode.
Attribute

Values

Description

view_mode

nav

Invokes the Maps app and displays


it in view_mode. By default, the
view_mode opens the map
screen but it can also open the
navigation screen if provided with a
nav value.

nav_start or nav_end

JSON object

Defines where navigation should


begin or end. If the parameter is
not provided, the navigation starts
or ends at the current location.

nav_start.properties or
nav_end.properties

JSON object

Defines properties of the start or


end location.
If the parameter is not provided,
the nav_start.latitude,
nav_end.latitude or
nav_start.longitude,
nav_end.longitude
coordinates should be geocoded or
reverse geocoded.

nav_start.properties.nam
e or
nav_end.properties.name

String

The name of the start or end


location. The default value is "".
This attribute is required.

nav_start.properties.des
cription or
nav_end.properties.descr
iption

String

Description of the start or end


location

nav_start.latitude or
nav_end.latitude

[-90.0,90.0]

Latitude of the start or end location


If the parameter is not provided,
the BlackBerry Maps app attempts
to geocode or reverse geocode
using the values in

Adding Features

180

Attribute

Values

Description
nav_start.properties or
nav_end.properties.

nav_start.longitude or
nav_end.longitude

[-180.0,180.0]

Longitude of the start or end


location.
If the parameter is not provided,
the BlackBerry Maps app attempts
to geocode or reverse geocode
using the values in
nav_start.properties or
nav_end.properties.

nav_options

JSON object

Defines the navigation options that


can be used.

nav_options.nav_mode

fastest or shortest

Type of navigation to use:


fastest for fastest route and
shortest for shortest route. This
attribute is required.

nav_options.avoid_highwa
ys

true or false

Defines whether to avoid highways


or not.

nav_options.avoid_tolls

true or false

Defines whether to avoid tolls or


not.

Navigating from the current location to a given location


blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"view_mode": "nav",
"nav_end":
{
"properties":
{
"name": "Toronto",
"description": "City of Toronto",
"address": "Toronto, Ontario, Canada"
},
Adding Features

181

}
);

"latitude": 43.7,
"longitude": -79.4

Navigating from one location to another


blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"view_mode": "nav",
"nav_start":
{
"properties":
{
"name": "Work"
},
"latitude": 45.342533,
"longitude": -75.930417
},
"nav_end":
{
"properties":
{
"name": "Toronto",
"description": "City of Toronto",
"address": "Toronto, Ontario, Canada"
},
"latitude": 43.7,
"longitude": -79.4
},
"nav_options":
{
"nav_mode": "shortest",
"avoid_highways": true,
"avoid_tolls": true
}
}
)
}
);

Adding Features

182

Displaying uncompressed KML data on the map


To display uncompressed KML data on the map, you can use application/vnd.google-earth.kml
+xml as the MIME type. Here's an example:
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.google-earth.kml+xml",
data: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<kml xmlns=\"http://www.opengis.net/kml/2.2\"><Placemark>
<name>Title</name>
<description>Description</description><Point>
<coordinates>-75.930417,45.342533,0</coordinates>
</Point></Placemark></kml>"
}
);

Media Player
Opening audio or video files
Here are the invocation attributes you use to open audio or video files:
Attribute

Value

Target ID

sys.mediaplayer.previewer

MIME type

All supported audio and video files

Action

bb.action.VIEW

URI

file://
http://

Here are the data attributes to open audio or video files:


Data

Description

contentTitle

The title that's displayed in the viewer title field.

imageUri

The URL of the image source that replaces the


default background image. This attribute is useful for
audio content.

Adding Features

183

The invocation attributes you use to open audio or video files with the Media Player application require the
same set of attributes as the ones you use for the Media Player cards, except for the target ID:
Attribute

Value

Target ID

sys.mediaplayer.previewer.app

Miracast card
You can invoke a Miracast card to discover and establish a connection to a nearby Miracast device. You can
invoke the Miracast card in two modes: play on and show on.

Showing content on a Miracast device


In ShowOn mode, the application is not aware of the streaming. The content is streamed to a Miracast device
in the native resolution of the BlackBerry device. Here are the invocation attributes you use to invoke the
Miracast card to show your content on a Miracast device:
Attribute
Target ID
Action
MIME type

Value
sys.miracastviewer
bb.action.VIEW
application/vnd.rim.miracast.showon

Playing content on a Miracast device


In PlayOn mode, your app renders content to a Miracast device at a resolution that can be different from the
native resolution of the BlackBerry device. Here are the invocation attributes you use to invoke the Miracast
card to play your content on a Miracast device:
Attribute
Target ID
Action

Value
sys.miracastviewer
bb.action.VIEW

Adding Features

184

Attribute

Value

MIME type

application/vnd.rim.miracast.playon

NFC
Sharing a single local file or a URI
Here are the invocation attributes you use to invoke an NFC card to share a single local file or a URI:
Attribute
Target ID
Action

Value
sys.NFCViewer
bb.action.SHARE

URI

Any valid URI value that is preceded by file:// (for


example, file://, http://, or https://)

MIME type

Any valid MIME type value, such as audio/mp3,


image/jpg, and application/myfiletype

Sharing a set of files or URIs


Here are the invocation attributes you use to invoke an NFC card to share a set of files or URIs:
Attribute
Target ID
Action
URI

Value
sys.NFCViewer
bb.action.SHARE
list://

Adding Features

185

Attribute

Value

MIME type

Any valid MIME type value preceded by filelist/,


such as filelist/audio/mp3, filelist/
image/jpg, and filelist/application/
myfiletype

Data

Data can be sent in JSON format as a list of metadata


in the following format:
[{

}]

"uri":<file-uri>,
"type":<mime-type>,
"data":<metadata>

In the above code, the uri is the local path to the file,
type is the MIME type for the specified file, and
data is the associated metadata for the specified file
(for example, thumbnail).

Sharing text
Here are the invocation attributes you use to invoke an NFC card to share text:
Attribute
Target ID
Action
MIME type
Data

Value
sys.NFCViewer
bb.action.SHARE
text/plain
Text is sent as a byte array. UTF-8 encoding is
supported.

Adding Features

186

Sharing NDEF messages


Here are the invocation attributes you use to invoke an NFC card to share NFC Data Exchange Format (NDEF)
messages:
Attribute
Target ID
Action
MIME type
Data

Value
sys.NFCViewer
bb.action.SHARE
application/vnd.rim.nfc.ndef
An NDEF message is sent in the form of a byte array.
The nfc_get_ndef_message_bytes() function
is used to create the byte array message.

Sharing URLs
Here are the invocation attributes you use to invoke an NFC card to share URLs, including remote files (for
example, http://aa.mp3):
Attribute
Target ID
Action
MIME type
Data

Value
sys.NFCViewer
bb.action.SHARE
text/URI-list
Data is sent as a URI to the remote file or link and
must be URI encoded (for example, http://
somesite/multi%20word%name.doc).

Adding Features

187

Sharing data as a URL


Here are the invocation attributes you use to invoke an NFC card to share your app's custom data or share an
image or a document as a URL:
Attribute
Target ID
Action

Value
sys.NFCViewer
bb.action.SHARE

MIME type

The MIME type can be specified in application/


myapp, text/vCard format. Make sure that the
values specified are different from the MIME type
values used to share text, NDEF messages, and
URLs.

Data

Custom data is sent in byte array form, specific to the


app and MIME types mentioned above.

Phone
Opening call logs
Here are the invocation attributes that you use to open the call log. If you don't specify the call log in the MIME
type, the full call log list is displayed.
Attribute

Value

Data

Optional integer of a call log ID

Action
MIME type

bb.action.OPEN
application/vnd.blackberry.calllog.id

Showing the dial pad


Here are the invocation attributes that you use to show the dial pad:
Adding Features

188

Attribute
Action
MIME type

Value
bb.action.DIAL
application/
vnd.blackberry.phone.dialpad

Here are the data attributes that you use to populate the dial pad with a number before showing it:
Data

Description

String number (required)

The phone number to show

int line_id (optional)

Line ID to use

int contact_id

Contact ID of the party being called. If you don't


specify this field, the contact information is looked up
based on the phone number.

Dialing a number
Here are the invocation attributes that you use to dial a number:
Attribute
Action
MIME type

Value
bb.action.DIAL
application/
vnd.blackberry.phone.startcall

Here are the data attributes that you use to dial a number:
Data

Description

String number (required)

The phone number to call

Adding Features

189

Data

Description

int line_id (optional)

Line ID to use

int contact_id

Contact ID of the party being called. If you don't


specify this field, the contact information is looked up
based on the phone number.

Boolean apply_smart_dialing

Whether to apply smart dialing (default value is true)

Dialing an emergency number


Here are the invocation attributes that you use to dial an emergency number:
Attribute
Action
MIME type

Value
bb.action.EMERGENCY_CALL
application/
vnd.blackberry.phone.startcall

Pictures
Opening images
Here are the invocation attributes you use to open images with the picture previewer:
Attribute
Target ID
Action

Value
sys.pictures.card.previewer
bb.action.VIEW

MIME type

All supported image files

URI

file:///

Adding Features

190

Picture editor
Invoking the picture editor card
Here are the invocation attributes you use to invoke the picture editor card:
Attribute

Value

Target ID

sys.pictureeditor.cardeditor

Action

bb.action.EDIT

URI

file:///path/to/content.jpg

Configuring the size of the output image


Parameter

Value

Example

size

WIDTHxHEIGHT

800x600

upScale

true or false

QString upScale=
"false";

You can configure the size of the output image by using the size and upScale parameters. The size
parameter allows you to specify the dimensions of the output image in pixels and the upScale parameter
identifies whether the output image is scaled to that specified size or not. The upScale parameter is valid only
if you define a size for your output image. In addition, true is the default value for the upScale parameter.
Depending on how you use these two parameters, you will have one of the three outcomes mentioned below.

Omitting the output image size


In this case, the size and upScale parameters are not used. This approach allows the user to crop the
image to any size or aspect ratio. On opening, the picture editor's Filter tab opens by default for this case. This
use case is demonstrated in the Pictures app of the BlackBerry 10 OS.

Specifying an exact output image size


To specify an exact size for the output image, you must specify a value for the size parameter and set the
upScale parameter to true. The value for the upScale parameter can also be omitted because true is the
default value.
Adding Features

191

In this case, the size of the output image is exactly the same as specified by the size parameter. On opening,
the picture editor's Transform tab opens by default for this case. The output image is cropped to the same
aspect ratio as the size. The user can't change the aspect ratio of the output image because the buttons to
change the aspect ratios are disabled in the picture editor.
When saving the output image, if the size of the edited image is different from the specified size, the output
image is scaled automatically to the specified size. This use case is demonstrated in the Contacts app of the
BlackBerry 10 OS.

Specifying a maximum limit for the output image size


To specify a maximum limit for the size of the output image, you must specify a value for the size parameter
and set the upScale parameter to false.
In this case, the size of the output image can be smaller than, but never exceed, the size specified in the size
parameter. On opening, the picture editor's transform tab opens by default for this case. The output image is
cropped to the same aspect ratio as the size. This also means that the user will not be able to change the
aspect ratio of the output image because the buttons to change the aspect ratios are disabled in the picture
editor.
When saving the output image, if the size of the edited image is larger than the size parameter specification,
it is downscaled automatically to the specified size. However, if the size of the edited image is smaller than
the size parameter specification, the output image size remains the same. This use case is demonstrated in
the BBM app of the BlackBerry 10 OS.

Remember
Creating a new entry
Here are the invocation attributes that you use to open a Remember card to create a new entry:
Attribute
Target ID
Action
URI

Value
sys.pim.remember.composer
bb.action.ADD
remember://notebookentry
You can also add the following key-value pairs by
adding a question mark (?) after the URI:
title=<ENTRY TITLE>

Adding Features

192

Attribute

Value
description=<ENTRY DESCRIPTION>
duedate=<# SECONDS SINCE EPOCH>
status=NotActionable, Completed,
NotCompleted
notebookid=<ACCOUNT KEY>:<NOTEBOOK
KEY>
tags=<COMMA-SEPARATED TAG LIST>

For the URI attribute, make sure that the entire URI is percent-encoded.

Adding a file or URI to a new entry


Here are the invocation attributes that you use to open a Remember card to add a file or URI to a new entry:
Attribute
Target ID
Action
URI

Value
sys.pim.remember.composer
bb.action.SHARE
file://
list://
http://
https://

Metadata

For file:// URIs, you must provide a JSON map


containing a key-value pair for the title of the entry.
For example:
{

"title": "Title to be set on


the entry"
}

Adding Features

193

Attribute

Value
For http:// and https:// URIs, you can provide
a JSON map containing key-value pairs for the
subject and description of the URI. For example:
{

"subject": "Webpage subject",

"description": "Webpage
description"
}
Data

For list:// URIs only, provide a JSON list of maps


(one per file), where each map contains a single keyvalue pair specifying the file's URI. For example:
[
{ "uri": "file:///path/to/
video.mp4" },
{ "uri": "file:///path/to/
picture.jpg" }
]

MIME type

For list:// URIs only, the MIME type must be


filelist/<TYPE>.

Editing an entry
Here are the invocation attributes that you use to open a Remember card to edit an entry:
Attribute
Target ID
Action

Value
sys.pim.remember.composer
bb.action.EDIT

Adding Features

194

Attribute
URI

Value
pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>

Viewing an entry
Here are the invocation attributes that you use to open a Remember card to view an entry:
Attribute
Target ID
Action
URI

Value
sys.pim.remember.previewer
bb.action.VIEW
pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>

Opening an entry
Here are the invocation attributes that you use to open a Remember card to open an entry:
Attribute
Target ID
Action
URI

Value
sys.pim.remember
bb.action.OPEN
pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>

Adding Features

195

Search
Searching using keywords
Here are the invocation attributes that you use to search with keywords:
Attribute

Value

Target ID

sys.search

Action

bb.action.OPEN

MIME type

All supported files

URI

search://?term=<keywords>, where
keywords are free-form text

Integrating your app with the Search app


If your app includes data that users can search for, you can integrate it with the Search app on a device. There
are two ways that your app can appear in the Search app:
Extended search
When a user types a search term in the Search app, the user can extend the search to other apps on the
device (for example, Help, Maps, BlackBerry World, and so on). The Search app invokes the app that the
user chooses (the target app) and passes the search term to the app in the invocation request. The
target app is responsible for displaying the search results. The list of target apps appears in the Extend
Search section at the bottom of the Search app, and you can register your app to be part of this list.
Active search
As a user types a search term in the Search app, search results are displayed dynamically. When the
user taps a result, a card is displayed or an app is started based on the result that the user tapped. These
active search results are categorized in sections that describe the type of result, such as Browser,
Messages, and Places. You can register your app to be part of the list of active search results.
Note: In later releases of the BlackBerry 10 OS, the Search app is also known as BlackBerry Assistant.
Registering for extended search
To register your app as an invocation target for extended search, here's how you can specify your app in the
config.xml file:
<invoke-target id="com.blackberry.search.extended.test1">
<invoke-target-type>APPLICATION</invoke-target-type>
Adding Features

196

<filter>
<action>bb.action.SEARCH.EXTENDED</action>
<mime-type>application/vnd.bb.search.criteria</mime-type>
</filter>
</invoke-target>
When your app is registered, the Search app displays your app in the Extend Search section using your apps
name and icon. Your app receives any search requests as invocation requests. The search string is delivered in
the data attribute of the request as an in-band transfer.
Registering for active search
To register your app as an invocation target for active search, here's how you can specify your app in the
config.xml file:
<invoke-target id="com.blackberry.search.asyoutype.test1">
<invoke-target-type>APPLICATION</invoke-target-type>
<filter>
<action>bb.action.SEARCH.SOURCE</action>
<mime-type>application/vnd.bb.search.db.criteria</mime-type>
</filter>
</invoke-target>
When your app is registered, the Search app displays your app in one of the active search categories using
your apps name and icon. The Search app discovers and displays your app dynamically as a data source or
category (for example, alongside the Messages or Calendar apps). When the user types a search term, the
Search app queries a database in your app for results and displays the results in the appropriate category.
When the user taps a search result, an invocation request is sent to your app so that it can display the details of
that result.
When you register your app for active search, your app must provide searchable data for the Search app to
access. The BlackBerry 10 OS includes the /sharewith/search/ folder for an app to share its search data (for
example, /accounts/1000/appdata/myapp/sharewith/search/). The Search app has read-only access to this
folder, and your app must provide a searchable database in this folder to let the Search app perform queries.
Note: For more information about folders in the BlackBerry 10 OS, see File system access.
Requirements for the search database
There are a few rules that you must follow when you create the search database:
The database must be an SQLite3 database and the database file name must be search.db (for example, /
accounts/1000/appdata/myapp/sharewith/search/search.db).
The search.db database file must include two tables:
search: This table is a full-text search (FTS) table that contains the search data.
search_info: This table contains information that isn't searchable but is required by the Search app to
render, view, or sort the search results. For example, this table might provide a timestamp, an icon, and
an invocation URI for each result.
Adding Features

197

You can include other tables in the search.db file, but they are optional and depend on the features of your
app.
The search table must meet the following criteria:
It must be an FTS table, which provides the Search app with behavior and search results that are
consistent with other data sources.
It must include the title and description columns to store searchable data. The Search app uses the
data in these columns to display the search results. You should keep the data in these columns small
enough to be displayed correctly, but large enough to provide useful information to users.
It must use TOKENIZE=icu instead of the default simple tokenizer. This tokenizer provides
consistency across data sources and helps to improve the quality of search results in certain languages,
such as Chinese.
It can have as many other columns as are required to support the features in your app.
Here's an example of an SQL creation script that you can use to create the search table:
CREATE VIRTUAL TABLE search USING fts4 (
title, description,
<optional app-specific columns>,
TOKENIZE=icu);
The search_info table can optionally include the following columns:
icon_path
This column contains a relative path to an image in the app sandbox folder. If this value is empty, then
the Search app displays an image of the app in the search result. Icons must be configured as public
assets in the bar-descriptor.xml file so that they're stored in the /app/public/ folder on the device. For
example, a valid icon path is /app/public/search_icon.png.
uri
This column contains an unbound URI that can be used to invoke a specific result. If no URI is
provided, the app is invoked with a result ID as the in-band data, which is discussed in Handling an
invocation request from active search on page 199 below.
timestamp
This column contains a timestamp in Epoch format. This timestamp is localized and displayed in a
common format, depending on the locale of the device. This column can be empty if it's not
applicable in your app.
group_id
This column allows your app to control how search results are grouped and displayed in the Search
app.
Here's an example of an SQL creation script that you can use to create the search_info table:
CREATE TABLE search_info (
icon_path VARCHAR(128),
Adding Features

198

uri VARCHAR(128),
timestamp INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0);
The search and search_info tables should be organized so that the docid column in the search table has a
1:1 relationship with the rowid column in the search_info table. For more information about how to
structure these tables for your apps, see Examples on page 199.
The search.db database file that you share with the Search app can include other tables that your app uses.
The Search app reads only the search and search_info tables, and the Search app is the only part of the
BlackBerry 10 OS that has read-only access to the /sharewith/search/ folder. Your app is the only component
that has read-write access to the data that it provides.
Handling an invocation request from active search
When your app is invoked from an active search result, the data attribute contains a result ID as an in-band
transfer. Your app can use the result ID to check the search.db database file and find the corresponding
record. The result ID is one of the rowid values in the search_info table.
Note: Your app can handle the invocation as an application or a card.
Examples
The following examples show you how you can structure the search and search_info tables to provide active
search results from your app.
Searching by title and description
This example shows how you can provide titles and descriptions that are searchable and displayed in active
search results. It also demonstrates how your app can have additional custom columns that are also
searchable. The example includes the address, phone_number, and mobile_number columns, as well as the
required title and description columns.
DROP TABLE IF EXISTS search_info;
DROP TABLE IF EXISTS search;
CREATE TABLE search_info (icon_path VARCHAR(128),
uri VARCHAR(128),
timestamp INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0);
CREATE INDEX search_info_timestamp_index ON search_info(timestamp);
CREATE INDEX search_info_groupid_index ON search_info(group_id);
CREATE VIRTUAL TABLE search USING fts4 (title, description, address,
phone_number, mobile_number,
TOKENIZE=icu);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(1, "", "http://www.example.com", 0, 1);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(2, "app/public/test1.jpg", "", 0, 2);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(3, "", "", 0, 3);
Adding Features

199

INSERT INTO search(docid, title, description, address, phone_number,


mobile_number)
VALUES(1, "Westlee Barichak", "BlackBerry", "4701 Tahoe Blvd.",
"519-555-0100", "519-555-0167");
INSERT INTO search(docid, title, description, address, phone_number,
mobile_number)
VALUES(2, "Karla Tetzel", "BlackBerry", "619 Kumpf Dr.",
"519-555-0123", "519-555-0184");
INSERT INTO search(docid, title, description, address, phone_number,
mobile_number)
VALUES(3, "Denise Marshall", "BlackBerry", "1001 Farrar Road",
"519-555-0128", "519-555-0189");
Here's an example of active search results for this data:
rowid

title

description

Denise
Marshall

Westlee
Barichak

icon_path

uri

timestamp

group_id

BlackBerry

BlackBerry

http://
0
www.example
.com

Grouping search results


This example shows how you can group active search results from your app. Grouping is usually required for
instant messaging searches. For example, BBM uses this type of grouping; you can search for content inside
any message in a conversation, but the active search results display only the last message of the conversation.
You can control this logic in your own app by using the same group_id value for each entry in the search_info
table.
DROP TABLE IF EXISTS search_info;
DROP TABLE IF EXISTS search;
CREATE TABLE search_info (icon_path VARCHAR(128),
uri VARCHAR(128),
timestamp INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0);
CREATE INDEX search_info_timestamp_index ON search_info(timestamp);
CREATE INDEX search_info_groupid_index ON search_info(group_id);
CREATE VIRTUAL TABLE search USING fts4 (title, description,
TOKENIZE=icu);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(1, "app/public/con1.jpg", "", 1365403000, 1);
Adding Features

200

INSERT INTO search_info(rowid, icon_path, uri, timestamp,


VALUES(2, "app/public/con1.jpg", "", 1365303001, 1);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(3, "app/public/con2.jpg", "", 1365203002, 2);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(4, "app/public/con2.jpg", "", 1365103003, 2);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(5, "app/public/con2.jpg", "", 1365003004, 2);
INSERT INTO search(docid, title, description)
VALUES(1, "IM conversation 1", "Test message
INSERT INTO search(docid, title, description)
VALUES(2, "IM conversation 1", "Test message
INSERT INTO search(docid, title, description)
VALUES(3, "IM conversation 2", "Test message
INSERT INTO search(docid, title, description)
VALUES(4, "IM conversation 2", "Test message
INSERT INTO search(docid, title, description)
VALUES(5, "IM conversation 2", "Test message

group_id)
group_id)
group_id)
group_id)

1, conversation 1");
2, conversation 1");
1, conversation 2");
2, conversation 2");
3, conversation 2");

Here's an example of active search results for this data:


rowid

title

description

IM
conversation
1

IM
conversation
2

icon_path

uri

timestamp

group_id

Test message app/public/


2,
con1.jpg
conversation
1

1365303001

Test message app/public/


3,
con2.jpg
conversation
2

1365003004

Controlling grouping manually


This example illustrates how the Search app doesn't force apps to group their active search results. If you use
the same data from the Grouping search results on page 200 example above but use unique values for each
group_id, then the Search app displays multiple results even if they are in the same conversation. This
behavior allows you to control how search results are grouped and displayed.
DROP TABLE IF EXISTS search_info;
DROP TABLE IF EXISTS search;
CREATE TABLE search_info (icon_path VARCHAR(128),
uri VARCHAR(128),
timestamp INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0);
CREATE INDEX search_info_timestamp_index ON search_info(timestamp);
Adding Features

201

CREATE INDEX search_info_groupid_index ON search_info(group_id);


CREATE VIRTUAL TABLE search USING fts4 (title, description,
TOKENIZE=icu);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(1, "app/public/msg1.jpg", "", 1365403000, 1);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(2, "app/public/msg2.jpg", "", 1365403001, 2);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(3, "app/public/msg3.jpg", "", 1365403002, 3);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(4, "app/public/msg4.jpg", "", 1365403003, 4);
INSERT INTO search_info(rowid, icon_path, uri, timestamp,
VALUES(5, "app/public/msg5.jpg", "", 1365403004, 5);
INSERT INTO search(docid, title, description)
VALUES(1, "IM conversation 1", "Test message
INSERT INTO search(docid, title, description)
VALUES(2, "IM conversation 1", "Test message
INSERT INTO search(docid, title, description)
VALUES(3, "IM conversation 2", "Test message
INSERT INTO search(docid, title, description)
VALUES(4, "IM conversation 2", "Test message
INSERT INTO search(docid, title, description)
VALUES(5, "IM conversation 2", "Test message

group_id)
group_id)
group_id)
group_id)
group_id)

1, conversation 1");
2, conversation 1");
1, conversation 2");
2, conversation 2");
3, conversation 2");

Here's an example of active search results for this data:


rowid

title

description

IM
conversation
2

icon_path

uri

timestamp

group_id

Test message app/public/


3,
msg5.jpg
conversation
2

1365403004

IM
conversation
2

Test message app/public/


2,
msg4.jpg
conversation
2

1365403003

IM
conversation
2

Test message app/public/


1,
msg3.jpg
conversation
2

1365403002

IM
conversation
1

Test message app/public/


2,
msg2.jpg

1365403001

Adding Features

202

rowid

title

description

icon_path

uri

timestamp

group_id

1365403000

conversation
1
1

IM
conversation
1

Test message app/public/


1,
msg1.jpg
conversation
1

Settings
Opening the notification settings of an app
Here are the invocation attributes you use to open the notification settings card of an app:
Attribute
Target ID
Action
MIME type
URI

Value
sys.settings.card
bb.action.OPEN
settings/view
settings://notification/application?
id= + packageInfo.name() (for example,
settings://notification/application?
id=com.foo.bar)
To open the notification settings of a core app, you
can use the following app ID: phone, bbm,
bbmvideo, text, reminders, facebook,
twitter, linkedin, foursquare.

Opening the Settings card


Here are the invocation attributes you use to open the Settings card:

Adding Features

203

Attribute
Target ID
Action
MIME type

Value
sys.settings.card
bb.action.OPEN
settings/view

Here's a list of URIs you can use to invoke different Settings cards:
Setting
About screens

URIs
settings://about
settings://about/general
settings://about/hardware
settings://about/os
settings://about/network
settings://about/legal
settings://about/workspace

Accessibility
Accounts

settings://accessibility
settings://pim
settings://pim/defaultAccounts
settings://pim/createAccount
settings://pim/listAccounts
settings://pim/createAccountType?
type=<type> where type can be facebook,
twitter, linkedin, evernote, or
mail_contacts_calendar
settings://pim/showAccount?id=<id>

Adding Features

204

Setting

URIs
settings://pim/deleteAccount?id=<id>
settings://pim/EnrollmentProgress

Application Manager

settings://appmgr

Application Permissions

settings://permissions

BlackBerry Balance

settings://balance

BlackBerry ID

settings://bbid

BlackBerry Link

settings://link

BlackBerry Protect

settings://protect

Bluetooth

settings://bluetooth

Certificates

settings://certificates

Child Protection

settings://childprotection

Date and Time

settings://datetime

Default Applications

settings://defaultapps

Development Mode

settings://devmode

Device Monitor

settings://sysmon

Diagnostics

settings://diagnostics

Display

settings://display

Display (Advanced screen)

settings://display/advanced

Language and Input

settings://language
settings://language/input
settings://language/keyboard
settings://language/spellcheck
settings://language/assistance

Location

settings://location

Mobile Hotspot

settings://mhs

Adding Features

205

Setting

URIs

Mobile Network

settings://radio

Network Connections

settings://networkconnections

NFC

settings://nfc

Notification

settings://notification

Password

settings://password

Payment Options

settings://payment

Screen Reader

settings://screenreader

Search

settings://search

Security

settings://security

Sharing

settings://sharing

SIM Card

settings://sim

Software Updates

settings://softwareupdate

Sound

settings://sound

Storage and Access

settings://storage

Tethering

settings://tethering

USB

settings://usb

Video Chat

settings://videochat

Voice Control

settings://voice

VPN

settings://vpn

Wi-Fi

settings://wifi

Wipe

settings://wipe

Text Messages
Composing a text message
Here are the invocation attributes that you use to open the composer card for the Text Messages app with
specific body text and recipients:

Adding Features

206

Attribute
Target ID
Action
MIME type

Value
sys.pim.text_messaging.composer
bb.action.COMPOSE
application/text_messaging

The following examples show PPS-encoded data fields:


// Example 1
body::Hello world!
to:json:["2125551212","9785551234"]
// Example 2
body::Hello world!
send:b:true
to:json:["2125551212"]
Here are the invocation attributes that you use to open the composer card for the Text Messages app with a
recipient field set to a specified phone number:
Attribute
Target ID
MIME type

Data

Value
sys.pim.text_messaging.smsuri
application/
vnd.blackberry.string.phone
Recipients phone number

You can perform the same invocation by using the following invocation attributes in your invocation request:

Adding Features

207

Attribute
Target ID
Action
URI

Value
sys.pim.text_messaging.smsuri
bb.action.SENDTEXT
tel:5198887465

Sharing an attachment with a recipient


Here are the invocation attributes you use to share an attachment with a recipient, using the Text Messages
app:
Attribute
Target ID
Action
URI
MIME type

Value
sys.pim.text_messaging.sharemedia
bb.action.SHARE
list://
filelist/media

You can perform the same invocation by using the following invocation attributes in your invocation request:
Attribute
Target ID
Action
URI

Value
sys.pim.text_messaging.smsuri
bb.action.SENDTEXT
tel:5198887465

Adding Features

208

Data should be sent in JSON format, as follows:


[

"uri": "file:///path/to/file"

},
{

"uri": "file:///path/to/another_file"

},
...

Twitter
All of the invocation attributes related to the Twitter app require a Twitter account to be set up on the device.

Sharing text with Twitter


Here are the invocation attributes you use to share text with Twitter:
Attribute

Value

Target ID

Twitter

Action

bb.action.SHARE

MIME type

text/plain

URI

data://

Data

Text string to be shared

Sharing a photo with Twitter


Here are the invocation attributes you use to share a photo with Twitter:
Attribute

Value

Target ID

Twitter

Adding Features

209

Attribute

Value

Action

bb.action.SHARE

URI

file:///path/to/content.png

File extensions

.gif, .jpeg, .jpg, .png

MIME type

image/gif, image/jpeg, image/png

Sharing a URL with Twitter


Here are the invocation attributes you use to share a URL with Twitter:
Attribute

Value

Target ID

Twitter

Action

bb.action.SHARE

URI

http://, https://

Opening a Twitter profile


Here are the invocation attributes you use to open a Twitter profile:
Attribute

Value

Target ID

com.twitter.urihandler

Action

bb.action.VIEW

Adding Features

210

Attribute

Value

URI

twitter:connect:<twitter_profile_name
>
The profile name must not contain the at sign (@)
prefix. For example, here's the correct format:
twitter:connect:blackberry.

Searching Twitter
Here are the invocation attributes you use to search Twitter for relevant tweets containing a search term:
Attribute

Value

Target ID

com.twitter.urihandler

Action

bb.action.VIEW

URI

twitter:search:<search_term>
Using a hashtag symbol as a prefix in your search
results is optional (for example,
twitter:search:#BB10Believe).

Video editor
The video editor allows the user to change the saturation, brightness, contrast, and audio volume of a video
clip. The video editor can also trim, crop, and rotate the video clip.

Editing a video
Here are the invocation attributes you use to invoke the video editor card:

Adding Features

211

Attribute
Target ID
Action

Value
sys.video_editor.card
bb.action.EDIT

URI

videoeditor:///path/to/content.mp4

MIME type

video/mp4

Voice note
The voice note card allows the user to record a voice note and save it.

Opening the voice note card


Here are the invocation attributes you use to invoke the voice note card:
Attribute
Target ID
Action
MIME type
URI
File extensions

Value
sys.apps.audiorecorder
bb.action.CAPTURE
Any valid MIME type value
file://
.wav, .m4a, .3gp, .amr, .awb, .qcp

The metadata of the voice note is specified by size and format attributes. The format attribute can be
specified in any of the file extensions listed above.

YouTube
Sharing a video with YouTube
Here are the invocation attributes you use to share a video with YouTube:

Adding Features

212

Attribute
Target ID
Action

Value
Youtube
bb.action.SHARE

URI

file:///path/to/content.mp4

File extensions

.3gp, .
3gpp, .avi, .flv, .m2v, .mp4, .mov, .
webm, .wmv

Invoking apps using active text


You can add custom active text elements that invoke your app by registering string patterns and app targets. A
custom active text element for your app is specified using a URI in your app's config.xml file. You must also
specify your app as the invocation target. The pattern and target parameters in the invocation request are
registered with the BlackBerry 10 OS when the app is installed on the device.
On devices that use BlackBerry Balance, the app with the active text and the app being invoked must be in
the same space (personal or work).
To use a URI pattern, you specify the start of a URI. You can specify the scheme portion alone (for example,
myuri:) or you can specify a longer form (for example, myuri:createid). Strings in native UI controls
become active text elements if they start with this pattern, conform to the syntax of a URI, and an invocation
filter is specified, as described below. In BlackBerry WebWorks applications, you must specify text patterns
within an anchor element.
Patterns are specified in the config.xml file using the <invoke-target> element. Here's an example that
shows an invocation request that contains a URI pattern:
<invoke-target id="com.mycompany.myapplication">
<type>APPLICATION</type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>*</mime-type>
<property var="uris" value="activetext:"/>
</filter>
<invoke-target-pattern>
<pattern-value type="uri">activetext:</pattern-value>
</invoke-target-pattern>

Adding Features

213

</invoke-target>
Attribute

Description

<invoketarget>

The invocation parameters of


your app. For more
information about <invoketarget>, see Target
declaration on page 121.

<type>

Can be APPLICATION or
CARD.

<filter>

Describes the criteria for this


app to be considered for
unbound invocations or
invocation queries. Must be
specified for URI pattern types
only. For the URI pattern type,
apps must be invokable with
bb.action.OPEN or
bb.action.VIEW. For more
information about <filter>,
see Target filters on page 124.

<invoketargetpattern>
and
<patternvalue>

The string pattern to match.


Use type="uri" for URI
matching.

To link to an active text target from a WebWorks app, add an anchor tag to your HTML source.
<a href="activetext://test">Active Text Link</a>
To get the value of an active text invocation, check the uri property in the invoked callback.
document.addEventListener('invoked', function (args) {
console.log(args.uri);
});
Adding Features

214

Invoking apps using keyboard shortcuts 10.3.1


On BlackBerry 10 devices that have physical keyboards (such as the BlackBerry Q10 smartphone and
BlackBerry Passport smartphone), users can start apps by using keyboard shortcuts from the home screen or
BlackBerry Hub. A keyboard shortcut lets a user press and hold a key to start an app. Several apps are already
assigned to keys by default, such as the Settings app (assigned to the O key) and the Phone app (assigned to
the P key). If an app isn't assigned to the key that's pressed, the user can choose an app to assign to that key
from a list of apps.
There are four types of available shortcuts:

App Launch Shortcut


Quick Compose Shortcut
Speed Dial
Other Shortcut

For the App Launch Shortcut type, you don't need to do anything special in your app for it to appear in this list;
your app is included automatically. The user can select the App Launch Shortcut menu option and assign your
app to the key. When the user presses and holds the shortcut key, your app starts.

Instead of just starting your app, you might want users to be able to create a shortcut to a specific task in your
app. For example, if your app allows users to create a new item or entry, you could create a shortcut directly to
the creation screen in your app. To do this, you define an invocation target with an action of
bb.action.SHORTCUT and a MIME type of application/vnd.blackberry.shortcut. These values
let your custom shortcut appear in the Other Shortcut category for the user to select and assign to a key. You
can define as many custom shortcuts as you want, each performing a specific task in your app. Don't forget to
provide an appropriate label and icon for your shortcut!

Adding Features

215

For some shortcut tasks, it doesn't make sense to invoke an app UI to perform the task. For example, for a
shortcut that mutes the notification sounds on a device, it isn't necessary to open an app UI when the shortcut
key is pressed. To support this behavior, you can use a headless invocation target as a shortcut. If you choose
to use this approach, make sure to provide the user with feedback when your headless app finishes the task.
You could flash the LED or vibrate the device, or you could consider other notification options such as
notification dialog boxes or instant previews.
To learn more about headless apps, including how to create one from scratch, see Headless apps.
You define your invocation target in the bar-descriptor.xml file for your app. Here's an example of a target that
defines the "Quick Respond" shortcut for an app:
<invoke-target id= "com.example.EmergencyResponder">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>Quick Respond</invoke-target-name>
<icon>
<image>quick_respond_icon.png</image>
</icon>
<filter>
<action>bb.action.SHORTCUT</action>
<mime-type>application/vnd.blackberry.shortcut</mime-type>
</filter>
</invoke-target>
Note: When you create filters for shortcuts in your app, it's a good idea to always give the target a meaningful
icon and name that describes the task that it performs.
For more information about defining invocation targets, see Target declaration on page 121.

Becoming a default app


You can enable your app to become the default app for certain types of content, such as files (for
example, .pdf, .doc, or .cal files) and data (for example, an HTTP link, text, or a phone number). When the user
opens the specified content for the first time, your app is listed as an option to be the default app for that type
of content.

Adding Features

216

Registering your app


To register your app as a default app, you must specify bb.action.OPEN as the action and specify either a
MIME type and URI or a MIME type and file extension in the config.xml file.
For example, to register your app as the default app to open a specific URL (http://www.example.com), your
app must specify bb.action.OPEN as the action, http://www.example.com as the URI, and text/
html as the MIME type in the target filter section of the config.xml file.
Note: If you are registering for a URI or file extension and do not have a specific MIME type to declare, you
should specify a wildcard character (*) for the MIME type.

Setting a default app


After you register your app as a default app, the user
still needs to set it as the default app for that type of
content. The user can set the default app by selecting
the Use as default check box in either the Open in
sheet of the context menu or in the Open in system
dialog box.
The user can configure the default apps in the
Settings app by selecting App Manager > View
Default Apps.

Adding Features

217

Menu integration
The BlackBerry 10 OS offers a well-integrated menu system that enables you to make highly contextual apps.
There are two types of menus available on the UI of a BlackBerry 10 device: action menu and context menu.
This section shows you how to add menus to your app and how to use the invocation framework to display your
app in the context menu of other apps. This section also shows you how to configure your app to allow the
BlackBerry 10 OS to automatically populate any related actions into the context menu of your app.
It's a good practice to add invocation-related actions to the context menu. However, if an action applies to the
whole page, you can add the action to the action bar.
To learn more about the action and app menus, see Menus.

Context menu
The context menu is a vital part of building an intuitive experience and is a key feature in BlackBerry 10. When
the user presses and holds a particular area of the app UI, the context menu is presented. The context menu is
divided into two sections that offer actions related to the content selected by the user.
The upper section of the context menu is the app section, which contains all of the actions that the app adds.
For example, in the following image on the right, Add as friend, Call, Email, and Text actions are all app
actions.
The lower section of the context menu is the platform section, which contains all of the actions that the
BlackBerry 10 OS adds automatically. In the following image on the right, Delete is a platform action.

Adding Features

218

Customizing the context menu


To learn about enabling and customizing the context menu, see the API documentation on context menu.

Add your application to the platform section


You can add a specific feature of your app to the platform section of the context menu of other apps. Enabling
your app to appear in the platform section gives it greater visibility among other apps and is good for the
publicity of your app. You can add a specific feature of your app to the platform section by declaring support
for the invocation of a core action for a given context. The following core actions are available in the BlackBerry
10 OS:
bb.action.OPEN
bb.action.SHARE
bb.action.SET
It is important to choose the action that suits your app's needs. For example, if your app manages images, then
supporting bb.action.OPEN action in your app is a good idea. If your app uploads images to an online
catalog, then you probably want to support bb.action.SHARE. If your app assigns images as avatars, then
you probably want to use bb.action.SET as the core action.
Here's how you can declare these actions in the target filter section of the config.xml file of your app:
<invoke-target id="com.example.image.view">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>My Sample Application</invoke-target-name>
<icon>
<image public="true"> icon_small.png</image>
<image public="true"> icon_big.png</image>
</icon>
<filter>
<action>bb.action.SHARE</action>
<mime-type>*</mime-type>
<property var="uris" value="file://,list://"/>
<property var="exts" value="jpg,png,jpeg,bmp"/>
</filter>
</invoke-target>
For more information about invocation and how you can make your app an invocation target, see Receiving
invocation.

Adding Features

219

Target selection menu


The target selection menu is displayed when the user
selects the Share action on the context menu. The
target selection menu contains two sections:
Suggestions and a Share With list displaying all of the
available targets for sharing.

Adding icons to the target selection menu


If your app is declaring itself as a target for core menu actions (OPEN, SHARE, and SET), you must package
your app with two images of size 81 x 81 pixels and 358 x 358 pixels. These images should typically show your
app's icon. The image of size 81 x 81 pixels is used in the list that displays all of the available targets while the
image of size 358 x 358 pixels is used in the suggestions section of the target selection menu.
Here's how the images for the BBM and Text Messages apps look in the list section:

Adding Features

220

Here's how the images for the Email and Text Messages apps look in the suggestions section:

Note: As a best practice, remember to fill any transparent pixels in your image with color. This approach
prevents the background color of the suggestions grid from appearing through the transparent pixels.
You should specify the images in the config.xml file of your app, as follows:
...
<icon>
<image public="true"> icon_small.png</image>
<image public="true"> icon_big.png</image>
</icon>
...

Invoking third-party apps


If you're using C++, you can now make your app more discoverable and bring more users to your app by
communicating the invocation target attributes of your app to other developers, allowing them to invoke your
app from their apps. For a user, this approach means better multitasking and a smooth app flow. To have your
app's invocation attributes published on this page, use your BlackBerry ID to sign in to the BlackBerry Jam
Zone for invocation.
You can also integrate your app with other third-party apps. Here's a list of apps with their respective
invocation attributes and the values that are required to invoke them.
Note: The descriptions below are provided by the app vendor, not BlackBerry.
Adding Features

221

Finance

Cashalyst
Import and View Quicken (qfx) and ofx bank files
Use this invocation target to import and view Quicken (qfx) and ofx bank transaction files. QFX/OFX files can be
downloaded from your online bank website.
Attribute
Target type
Target ID
Action
MIME type
File extensions
Data description

Value
application
com.digicasa.cashalyst.import
bb.action.OPEN, bb.action.VIEW
application/*, text/*
qfx, ofx
Invocation requires either a file:// with the full path to
the qfx/ofx file or a data://local with the complete
contents of the qfx/ofx file.

Games

Anagrammatist EN
Search for the anagrams
Adding Features

222

Invocation calls Anagrammatist EN app. This application provides some functions for the word games - like
checking if the provided word exists, seraching for anagrams, searching for all the possible words from the
given letters etc.
Attribute
Target type
Target ID

Action
MIME type
Data description

Value
application
AnagrammatistEN591c82ab559936cc457d58
1de4df064
bb.action.SEARCH.EXTENDED
application/vnd.bb.search.criteria
In general, the string (set of letters) is accepted.

Music & Radio

Ambience
Ambient Sounds for BlackBerry
Create some ambience with images and sounds.
Attribute
Target type
Target ID

Value
application
ambience

Adding Features

223

Attribute
Action
MIME type

Value
bb.action.OPEN
text/plain

Photo & Video

Photo Effect
PhotoEffect
Create beautiful photo effects.
Attribute
Target type
Target ID
Action
MIME type
URIs
File extensions
Data description

Value
application
com.umang.PhotoEffect
bb.action.OPEN
image/*, image/png, image/jpg, image/jpeg
file://
png, jpg, jpeg
Invocation requires either a file:// with the full path to
the qfx/ofx file or a data://local with the complete
contents of the qfx/ofx file.

Adding Features

224

Productivity

ekkes Express Charts


Import Chart Images
Integrate 'ekkes Express Charts' as a Composer Card to define Charts on-the-go. There's a sample app at
Github HowTo do this: https://github.com/ekke/ekkesChartInvoker You can select from existing Charts or
define a new one. The image is a full-screen JPEG.
Attribute
Target type
Target ID
Action
MIME type
Data description

Value
card.composer
org.ekkescorner.charts.chartimages
bb.action.SHARE
image/jpeg
CardDone Message sends you 'Done' if all is ok and
'Cancel' if user canceled.If result is 'Done' you'll get
the path to the image from data. See the sample app
how to construct the filename right.

BBM Social Platform


The BlackBerry Messenger social platform provides APIs that allow you to leverage the social features and
functionality of BBM in your app.
BBM is an instant messaging program designed to allow BlackBerry device users to communicate with each
other. Since its introduction to the suite of core BlackBerry applications, BBM has quickly become one of the
most widely used applications on BlackBerry smartphones. Users do not need to sign into or out of BBM. As
Adding Features

225

long as their BlackBerry devices are connected to a wireless network, BBM can keep users connected to their
BBM contacts and groups.
The BBM SDK, used in conjunction with the BlackBerry WebWorks SDK, lets you use the same infrastructure
upon which BBM is built to communicate between instances of your app on multiple BlackBerry devices. For
example, in a chess game app, a BlackBerry device user could invite a BBM contact to play a game of chess,
and the moves could be communicated back and forth using the BBM platform.
Leverage the features of the BBM platform
You can access the same infrastructure that BBM, one of the most successful and widely used mobile social
platforms, is built upon. With the BBM SDK, you can develop apps that incorporate social features such as
peer-to-peer connections between BlackBerry devices, or integrated chats. There is no need to develop these
social features yourself, and no server-side development is required to support them.
The BBM platform provides support for the social aspects of your app, such as tracking which BlackBerry
devices your app is installed on, managing the connections between instances of your app, and proactively
discovering the contacts who have already installed the app.
Increase the stickiness of your app
A sticky application is one that users find useful, engaging, and use frequently. When you integrate BBM into
your app you can create a community where BlackBerry device users can get together, socialize, and
communicate. Adding this social aspect can help your app maintain its presence on BlackBerry devices and
help attract users.
Increase the discoverability of your app
When people like something, they want to share it with others. Because BlackBerry device users can
communicate with any or all of their BBM contacts from within an app, when you create a BBM connected
app, you have a built-in advertising system.
Users can not only encourage their contacts to download your app, they can actively invite them to do so by
sending an invitation that links directly to the application details page in the BlackBerry World storefront.

Designing the UI for BBM connected applications


As you design the UI for your BBM connected app, be aware of the impact that the layout of the screens and
the flow of interactions have on the user's experience with your application. Provide meaningful, streamlined
interactions between your application and BBM. The following best practices can help you create the best
possible experience for your users.

Best practices for look and feel


Create a succinct name for your application. Long names detract from readability. Avoid including the
version of your application in the name. For example, use "Word Mole" instead of "Word Mole version 2.0."
Mention that your app is BBM connected when you write a description of your application for the
BlackBerry World storefront. Because BlackBerry Messenger is one of the most widely used applications on
Adding Features

226

BlackBerry devices, users might be encouraged to try your application. You can use the following sample
text in your description: "By connecting this application to BBM, you and your contacts can get together,
socialize, and communicate by <insert a phrase that describes what users can do (for example, playing
games against each other)>."
Create an application icon that is 114 x 114 pixels.
Design an icon that is visually interesting. Make sure that users can distinguish the icon from the
background of the screen and that they can distinguish your application from other applications. Avoid
using BlackBerry Messenger icons or BBM branding in your application.

Best practices for app start-up


Register your app with the BBM Social Platform when users open your app for the first time. Users are
more likely to expect setup activities the first time that they open an application.
Avoid unnecessary exposure to BBM functionality. If users tap a dimmed item (for example, in menus or
on buttons on the screen), display a toast to notify that the application is not connected to BBM and explain
how they can connect to BBM.

Best practices for sending invitations and messages


Make sure that users are the ones who initiate requests to engage other users. Your application should
not initiate requests on a user's behalf. For example, users should initiate requests to send a file, download
an application, or invite others to join games, forums, or chats.
Allow users to enter their own text or provide default text in the message or invitation. If you provide
default text, do not include advertisements or spam. Users might be annoyed if they have to delete
unnecessary text.
If users send a file, voice note, or image, send only what the user intends to send. Avoid sending
advertisements or spam along with the file, voice note, or image.
Include a contextual link in messages where possible. For example, if a user sends a picture of a
landmark, you can include a link to a map that shows where it is located. Otherwise, link to the main screen
of the application.

Best practices for choosing contacts


Provide filter options for contacts, if possible and if meaningful to the task. For example, in a game, allow
users to filter the contacts by skill level such as beginner, intermediate, and expert. This approach makes it
easier for users to find relevant contacts, especially if they have a lot of BBM contacts.
Allow users to filter contacts by the contact categories that they create in BBM.

Adding Features

227

Best practices for chats


Make sure that users have the ability to choose the contacts that they want to chat with.
When a chat begins, expose the chat interface so that users know that a chat has started.
Make sure that you design your screens so that users can access key features when the chat interface is
open. If users chat using a virtual keyboard, be aware that the portion of the screen reserved for the
application is reduced in landscape orientation.
Make the chat interface available on multiple screens in your application so that users don't have to open
a specific screen to open and reply to chats.
If your application supports multiple chats, make sure that users have a way to switch between chats.

Best practices for BBM user profiles and profile boxes


Always ask permission before updating a personal message or status in a user's BBM profile. Do not
prompt users to update their display picture because they won't be able to see the picture before it is
updated.
If users allow your application to update their personal message, use the personal message field to
describe a quality that is attributed to the user (for example, "I am a fan of Word Mole"). To describe a
current activity, create a personalized status for the user (for example, "I am playing Word Mole").
Include only new accomplishments or specific activities that are meaningful milestones, in a profile box.
For example, include notifications such as "Kevin has achieved level 4." Do not use the profile box to
promote a feature or a new version of your application.
Provide a succinct description for each update in the profile box (for example, "Catharina has posted a
new playlist. Take a look."). If possible, allow users to click a description to get more information. For
example, users could click a description to see a playlist. If a link cannot open a specific location in the
application, link to the main screen of the application.
Include a unique and meaningful icon for the activity or event in the profile box. For example, use a
trophy icon to mark noteworthy accomplishments in a game. Avoid shrinking a large picture and using it as
an icon. If you do not create icons for each activity or event, then your application icon appears instead.
Create icons that are 119 x 119 pixels. Test the icons on each screen to make sure that the icons, when
scaled, still convey the intended meaning.

Configuring the BBM server simulator


If you plan to use the BlackBerry 10 Device Simulator to test your BlackBerry Messenger connected app, you
need to configure your development environment to support BBM.

Adding Features

228

Install Java
The first thing you need to do is download and install the Java SE 6 update 37 or later (JDK or JRE, 32-bit or 64bit).
Note: The BBM server simulator does not support Java 7.
Next, you set up Java environment variables and unlimited strength encryption.

Set up Java environment variables


1. In Windows, open the Environment Variables dialog box.
2. Set the JAVA_HOME system variable to the directory where you installed Java (for example, in the 32-bit
version of Windows, C:\Program Files\Java\jre6.
(In the 64-bit version of Windows, the default path for 32-bit Java is C:\Program Files (x86)\Java\jre6\).
3. In the Path environment variable, add %JAVA_HOME%bin; to the beginning of the string.
4. Click OK to save and close the Environment Variables dialog box.
5. Verify that your environment variables are set correctly.
a) Open a command prompt.
b) Type java -version and verify that the Java version is the same as the version that you set in the
environment variable:
java version "1.6.0_38"
Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
Java HotSpot(TM) Client VM (build 20.13-b02, mixed mode, sharing)

Set up unlimited strength encryption


The Java Cryptography Extension (JCE) enables encryption by using a key size of greater than 128 bits.
Note: You must live in an eligible country to enable this functionality. You can find more information in the
readme.txt file contained in the following .zip file.
1. Download the jce_policy-6.zip file from the Oracle website.
2. Extract the contents of the jce_policy-6.zip file to your computer.
3. In the security directory of the system JRE (for example, C:\Program Files (x86)\Java\jre6\lib\security\),
replace the local_policy.jar and US_export_policy.jar files with the files you extracted.

Get the tools


Before you can test your BBM connected app in the device simulator you need to install some software.
If you don't have a BlackBerry 10 device, you can download and install the BlackBerry 10 Device Simulator to
test your applications. The BBM server simulator is bundled with the BlackBerry 10 Device Simulator.

Adding Features

229

Testing BBM connected apps


To test your BBM connected app in the BlackBerry 10 Device Simulator, you need to install at least two
instances of the device simulator in different locations on your hard disk, one for each instance of BBM. Learn
more about how to Run multiple device simulators with BBM on page 230.
After you install the device simulator and a virtual machine, you're ready to get started. The first thing you need
to do is start the BBM server simulator. The BBM server simulator enables communication between instances
of BBM.
Note: You need to run only one instance of the BBM server simulator.
1. In the directory where you installed the simulator, open the BlackBerry 10 Simulator - <version> BBM
directory.
2. Double-click the Run BBM Server Simulator shortcut to open the console and start the server.
Next, start the device simulator: in the BlackBerry 10 Simulator - <version> directory, double-click the
BlackBerry 10 Simulator shortcut.
Then, connect the device simulator to the controller. The controller allows the device simulator to connect to
the BBM server simulator.
Now, connect the device simulator to the BBM server simulator.
1. On the Controller menu, click BBIO.
2. In the IP address field, specify the IP of the computer that hosts the BBM server simulator. In the Port field,
port 3101 is automatically specified.
Note: The IP address cannot be 127.0.0.1 or localhost, even if the BBM server simulator is running on the
same computer that hosts the device simulator.
3. Click Connect. You can see activity in the BBM server simulator console when the connection is successful.
4. To shut down the BBM server simulator when you finish testing, in the BBM Server Simulator directory,
double-click the Shutdown BBM Server Simulator shortcut. After the simulator stops, type exit at the
command prompt to close the command window.

Run multiple device simulators with BBM


If you want to run more than one BlackBerry 10 Device Simulator at a time, you need to install each simulator
in a separate location on your hard disk, one for each instance of BBM.
Note: You need to run only one instance of the BBM server simulator.
1. Start VMware.
2. Navigate to the directory where you installed the simulator and open the BlackBerry 10 Simulator <version> directory.
3. Select BlackBerry10Simulator.vmx and click Open to start the simulator.
4. Open the controllers directory and run controller.exe.
5. Change the default PIN of the simulator by following the instructions in Configuring the simulator.
Note: After you change the PIN, restart the simulator.
Adding Features

230

6.
7.
8.
9.

On the Controller menu, click Connection > Connect.


In the Auto Discover section, select the entry for the device simulator instance that you want to connect.
In the IP Address drop-down list, select the IP Address of the corresponding simulator.
Click Connect. "Connected to <IP Address>" appears on the status bar at the bottom of the controller
window.
10.On the Controller menu, click Device > BBIO > Connect to BBM Server.
11.In the IP address field, specify the IP of the computer that is running the BBM server simulator. In the Port
field, port 3101 is automatically specified..
Note: The IP address cannot be 127.0.0.1 or localhost, even if the BBM server simulator is running on the
same computer as the device simulator.
12.Click Connect.
When the connection is successful, you see activity in the BBM server simulator console.
13.In the device simulator, click the app that you want to run.
14.Repeat steps 1 to 13 for each additional instance of the simulator that you want to run.
For more information, see Testing BBM connected apps on page 230.

Beta testing and releasing your BBM connected app


The BBM pre-production environment
The BlackBerry Messenger pre-production environment is a dedicated cluster of BBM services that provides
all of the functionality of the BBM Social Platform. The pre-production environment is ideal for building
internal, alpha, and beta versions of your BBM connected app. It provides you with an opportunity to test your
app's features and functionality on activated BlackBerry smartphones with a small beta community before you
release it through the BlackBerry World storefront.
If your app, or app version, does not already exist in BlackBerry World, it is automatically placed in the preproduction environment. The UUID that you provide acts as a unique identifier for your app that facilitates
monitoring for any adverse or unintended events (such as burstiness) in the traffic that is associated with your
app. Since the pre-production environment is intended for testing, while restricting traffic from your app in the
production environment, the following limitations apply:
Each app is limited to 100 active instances.
An app expires after 180 days. Once expired, your app no longer has access to the BBM platform services
in the pre-production environment.
An app in pre-production can communicate (for example, share content or send join invitations) only with
other users who are running the same app or app version. This means that users who are testing the app
cannot communicate with users who are running any version of that app if it has been submitted to or is
available in BlackBerry World.

Communication limitations
To prevent an application from using too much of the available bandwidth, the BlackBerry Messenger platform
limits the total volume of data that is transferred by a BBM connected application as follows:
Adding Features

231

All messages and application data transferred over channel and session connections for all BBM
connected applications that are running on a BlackBerry device are collectively limited to a maximum data
transfer rate that is configured by the BBM server. If the total volume of data attributed to an application
threatens to exceed the maximum transfer rate, the BBM platform throttles data traffic for that application
to reduce the transfer rate to an acceptable level. File transfers sent from a BBM connected application are
not considered to be application data, and are therefore exempt from this limitation on the data transfer
rate.
Data sent from a BBM connected application over a channel/session connection is limited to a maximum of
60 KB per transfer.
File transfers from a BBM connected application are limited to a maximum of 6 MB per file.
The maximum number of users in a connection is limited to 24.

UUID Guidelines
A Universally Unique Identifier (UUID), also known as a Globally Unique Identifier (GUID), is a unique, 128-bit,
36-character identifier that you generate for your app using a UUID/GUID generator. Your app must provide a
UUID when it registers with the BBM social platform to access the social platform APIs. The UUID string must
conform to the Microsoft 8-4-4-4-12 format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). Valid characters consist of
hexadecimal values in the ranges 0 to 9 and a to f.
The UUID is also used to identify your app (along with the vendor name and the app name) in the preproduction test environment, before the app is made available in BlackBerry World. If the app is installed from
BlackBerry World, the UUID is not used to identify it. You should use the same UUID when testing future
releases of the same app. If the UUID changes across versions, different versions of the same app will not be
able to communicate with each other in the pre-production environment.

Releasing BBM connected apps through BlackBerry World


If you have separate, optimized versions of your app for BlackBerry smartphones running BlackBerry 7 (or
earlier) and BlackBerry 10, there are some things you need to consider when adding BBM connected apps to
the vendor portal. Typically, you assign a separate SKU to each app that you add to the vendor portal.
However, if you want your app to be able to communicate across platforms, you must assign the same SKU to
each variant of your app. To have a BBM connected app that is running on a BlackBerry 7 smartphone
communicate with the same app running on a BlackBerry 10 smartphone, they must both have the same SKU
in BlackBerry World. You can still submit different screen shots, icons, feature image, descriptions, and
keywords for each variant of your app when using the same SKU. You can learn more about Adding and
managing apps on the BlackBerry World vendor portal website.

Payment Service
After you create an awesome app, you might want to offer in-app purchases. The Payment Service lets you do
just that. To get started, you need to include the Payment Service classes into your app. Then you can add your
app on the vendor portal for the BlackBerry World storefront. You can add digital goods to your app, offer
subscriptions, and charge for additional features. Learn more about getting your app up for sale on BlackBerry
World.
Adding Features

232

You can use your imagination to decide what digital goods to create, and how best to offer them for sale from
within your app. For example, you can:

Sell guides to help users learn about levels, back doors, and bonus points.
Offer additional levels or new characters in your game.
Upgrade your users to the advanced version of your app.
Sell extra services, such as music or video streaming in your app.
Offer items such as eBooks, personalized greeting cards, photos, and maps.
Sell subscriptions to renewable goods, such as magazines and newsletters.

What can the Payment Service offer?


A simple payment solution

You can incorporate the Payment Service in your app and then upload the app and its digital goods, along with
pricing and a description to the BlackBerry World vendor portal. The Payment Service manages all the
technical and financial details for you. You don't have to waste time managing relationships or business terms
with payment providers and coding for integration into each provider's solution.
A fast and familiar payment solution for end users
The Payment Service provides a fast and familiar purchase experience for your users. Using their BlackBerry
ID, users can apply various payment methods, including credit card, PayPal, and carrier billing, toward the
purchase of digital goods you defineall without leaving your app.
An easy way for you to keep track of your earnings
Digital goods in your app are described and priced according to the pricing tiers presented in the BlackBerry
World vendor portal. In the vendor portal, you can manage and track sales of your app and its digital goods so
you can keep track of how much you're earning.

How does it work?


All the Payment Service functions are designed to make the user experience consistent for each type of
payment and for every BlackBerry device. When a user wants to use your app to purchase digital goods, this is
what happens:

Adding Features

233

Component

Description

Content server

The content server is an optional component that you


can set up to send digital goods to your users. If you
include your digital goods in the source code for your
app, and programmatically unlock the digital goods
for users after a purchase, then you don't need this
component.
If you set up a content server, you can provide the
URL for the content server in the BlackBerry World
vendor portal. The Payment Service server can use
the URL to send notifications about successful
purchases to your content server.
For more information about the content server, see
Distributing digital goods.

Payment providers

The payment providers are the organizations that


offer payment types that device users can use to
purchase digital goods (for example, credit card,
PayPal, carrier billing). The Payment Service server
handles communications with the payment providers
so that you don't have to implement support for each
payment method in your app.

Payment Service server

The Payment Service server is the part of BlackBerry


World that facilitates interactions between your app,

Adding Features

234

the payment providers, the vendor portal, and your


content server.
When a user wants to purchase your app, this is what
happens:
1. A user makes a request to purchase digital goods
in your app.
2. Your app builds the Payment Service information
that it needs to make a purchase and then your
app initiates a purchase request.
3. If the user isn't logged in with a BlackBerry ID
account, the Payment Service prompts the user to
log in without leaving the app.
4. The Payment Service prompts the user to confirm
the purchase. The user can change the payment
method or set up a new payment method.
5. The Payment Service verifies that the digital goods
are registered and completes the purchase
through the payment provider that the user
selects.
6. The Payment Service provides a receipt for the
purchase and your app displays the receipt in your
UI.
7. If there is a problem with the transaction, Payment
Service provides the error code and your app
handles the exception.

What's next?
Let's get started earning some money! Register your digital goods, learn about what the Payment Service has
to offer, and use the code samples to create an app that includes some in-app purchasing.

Registering with BlackBerry World


When you submit an application in the BlackBerry World vendor portal, you can also add digital goods to your
application. When you add digital goods, you need to provide details, including the following information that
may become data in payment service transactions.

Adding Features

235

SKU

The SKU is an identifier that you can use to manage


your digital goods. When a user initiates the purchase
of digital goods in your application, the Payment
Service server can use the SKU to identify the digital
goods.

License type

You can select one of the following license types for


your digital good:
Consumable: A consumable license is temporary, like
a movie rental. Users can purchase this type of digital
good more than once.
Non-consumable: A non-consumable license is for
permanent enhancements, like extra levels of a
game. If you use this license type, you must make
sure that the digital good is available for a minimum
time period as defined in the BlackBerry SDK Licence
Agreement. You must also make sure that digital
goods are still available if the user reinstalls the
application or switches devices. Because digital
goods are not automatically restored, it's up to you to
make sure that users can access these digital goods
again.
7-day Subscription: A 7-day subscription provides
users with renewable content, like news publications,
with a renewal period of 7 days.
30-day Subscription: A 30-day subscription provides
users with renewable content with a renewal period of
30 days.

Initial trial period

If you decide to offer digital goods as 7-day or 30-day


subscriptions, you can set an initial trial period for the
subscription.

Price

You can specify a price for your digital goods from a


list of pricing tiers that BlackBerry World provides. For
subscription-based digital goods, the price that you
specify in this field is for the initial trial period. You
can provide a free trial for your subscription-based
digital goods by specifying a price of $0.00

Renewal price

If your digital goods are subscription-based, you can


use this field to set the price for a renewal period, to

Adding Features

236

begin after the initial trial period expires. Users are


charged this amount every 7 days or 30 days after the
trial period expires, based on the license type.
License model

You may want to require that users have a license key


in order to run your digital goods. You can select any
of the following license models to define a license key
method for your digital goods.
Static: A static model doesn't use a license key.
Single: With a single license key, all users get the
same license key to access your digital goods.
Dynamic: If you select a dynamic license model, you
must provide an address for a website that generates
license keys for your digital goods. After a user
purchases your digital goods, the Payment Service
server connects to the website, retrieves the license
key, and provides it to the user. Choose this license
model if you want your content server to receive
notifications when users make purchases in your
application.
Pool: For a pool licence model, you are responsible
for providing a pool of unique license keys that
BlackBerry World can use to distribute a unique key
to each user. The pool must contain at least 100
license keys. If the number of available license keys in
the pool decreases to 50, BlackBerry World sends
you an email notification. If the number of license
keys in a pool decreases to 10, BlackBerry World
cancels distribution of the digital goods and sends
you an email notification.

Learn more about submitting applications and digital goods on the BlackBerry World vendor portal.

Distributing digital goods


You can distribute digital goods either by sending data files over the wireless network from your own server, or
by unlocking existing functionality from within the application's code.
If the digital goods for your application don't require dynamic updates, it's generally more efficient to include
the functionality for those goods in the source code. For example, if you sell a game that offers additional levels
as a digital good, your game logic can control access to the extra levels based on purchase logic.

Adding Features

237

If, however, you host your digital goods on a content server and deliver them to BlackBerry devices over the
wireless network, you can update and add to your offering of digital goods without having to submit a new
release of your application to the BlackBerry World storefront.

Distributing digital goods from a content server


There are two ways to keep your content server up to date on successful purchases: design your application to
send a notification to the content server, or request a notification from the Payment Service.
To request notifications from the Payment Service, you must set up a dynamic license model when you register
the digital goods in the BlackBerry World vendor portal.
The dynamic license model for digital goods requires an HTTPS URL for your content server. During each
successful purchase, the Payment Service server sends your content server a request for a license key, and
the following purchase parameters:

The device pin.


The email address associated with the user's BlackBerry ID account.
The product name for the application that the digital goods are purchased from.
The version of the application that the digital goods are purchased from.
The transactionid, used as a unique identifier for the successful purchase.
The product sku.
The results of a true or false test that indicates whether the purchase was initiated using a BlackBerry ID
account configured for testing.

Your content server needs to respond to the Payment Service server with a license key, which is then passed to
the user's device as part of the purchase transaction.

Initiating a purchase
You can initiate a purchase in your app by calling the purchase method.
When a user starts a purchase transaction, the blackberry.payment.purchase function is called. When
the user finishes interacting with the device to engage the payment process, the app receives a response.
When the blackberry.payment.purchase function is called, only the ID or SKU of the digital good to be
purchased is required; you don't need to provide both. If you do provide both, the ID takes precedence.
function purchase() {
alert("Trying to call purchase");
blackberry.payment.developmentMode = true;
try {
blackberry.payment.purchase({
"digitalGoodID":
"16823864",
"digitalGoodSKU":
"BB10-CG-02",
"digitalGoodName":
"SomeName",
"metaData":
"metadata",
"purchaseAppName":
"WebWorks APP",
"purchaseAppIcon":
null,
Adding Features

238

"extraParameters":
{
"key1":
"value1",
"key2":
"value2"
}
}, onPurchaseSuccess,
onPurchaseError);
} catch (e) {
alert("Purchase exception");
console.log(e);
}

The Payment Service SDK for BlackBerry WebWorks includes metaData property. You can use this property
to provide extra information that remains associated with the purchased good. For example, if a book vendor
offers multiple titles at a single price point and represents them on the vendor portal as a single digital good,
when a book is purchased, the vendor could set the metaData value as the ISBN for that book. Then, if the
user checks past purchases, the metaData property can be used to differentiate between past book
purchases.
By default, users see the app name and the icon that you registered with BlackBerry World when they interact
with purchase dialog banners. If you want users to see a customized name and icon on the purchase dialog
banners when they purchase your app, you can set the purchaseAppName and purchaseAppIcon
properties.
Using the purchaseAppName and purchaseAppIcon properties can be a good solution if you offer digital
goods with a single name and price point. For example, if you sell additional levels of a game at a single price
point, you can use a generic digital good called "My game level" for all such levels. When a user makes a
purchase, the game app should override "My game level" with the name of the level that the user purchased
(using the purchaseAppName property). This approach makes sure that the user is aware of exactly what
they are purchasing on the purchase confirmation screen.
If you use the purchaseAppIcon property, you can supply an icon in any standard format set to ?
height=100for a 100 x 100 size.
<script type="text/javascript">
function purchase() {
try {
blackberry.payment.purchase({
"digitalGoodID":"123",
"digitalGoodSKU":"someSKU",
"digitalGoodName":"SomeName",
"metaData":"metadata",
"purchaseAppName":"WebWorks APP",
"purchaseAppIcon":null,
"extraParameters": {
"key1": "value1",
"key2": "value2"
}
},
onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
Adding Features

239

Responding to a purchase
When the purchase process completes, your app calls either onSuccess if the purchase is successful, or
onFailure if the purchase is not successful.
<script type="text/javascript">
function purchase() {
try {
blackberry.payment.purchase({
"digitalGoodID":"123",
"digitalGoodSKU":"someSKU",
"digitalGoodName":"SomeName",
"metaData":"metadata",
"purchaseAppName":"WebWorks APP",
"purchaseAppIcon":null,
"extraParameters": {
"key1": "value1",
"key2": "value2"
}
},
onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(purchasedItem) {
var transId = purchasedItem.transactionID;
var sku = purchasedItem.digitalGoodSKU;
var dgId = purchasedItem.digitalGoodID;
alert("Purchased Item: " + transId + "," + sku +
}

"," + dgId);

function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Error responses for blackberry.payment.purchase
The paymentError object is returned as a parameter for callbackOnFailure if the purchase process is
unsuccessful. The paymentError object has two properties: Number errorID and an errorText string.
Number errorID
The error number returned as part of the paymentError object corresponds with a preset list of specific
error conditions, as follows:
-1 = an unexpected application error
Adding Features

240

1 = the user canceled the transaction


2 = the payment system is busy
3 = a general payment system error
4 = the digital good was not found
5 = an illegal application error (applies only to BlackBerry OS 5.0 and later)

String errorText
The paymentError object returns a text string that can display as a readable message for the user.

Checking for past purchases


You can avoid offering a digital good to a user who has already purchased it by checking the user's purchase
history with the blackberry.payment.getExistingPurchases function.
You can also use the blackberry.payment.getExistingPurchases function when a user initiates a
request to cancel a subscription, in order to obtain a purchase ID for the cancellation process.
The blackberry.payment.getExistingPurchases function includes a boolean parameter,
refresh, that allows you to specify how the purchase history is retrieved. Set refresh to True to retrieve a
purchase history from the Payment Service server; set it to False to attempt to use the local purchase history,
and only retrieve purchase history from the Payment Service server if no match is made locally.
If the transaction is successful, the onSuccess callback function returns a purchase object for each purchase
of the app, made by the user.
<script type="text/javascript">
function getExistingPurchases() {
try {
blackberry.payment.getExistingPurchases(true, onSuccess,
onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(purchases) {
for (var i = 0; i < purchases.length; i++) {
var transId = purchases[i].transactionID;
var sku = purchases[i].digitalGoodSKU;
var dgId = purchases[i].digitalGoodID;
alert("Purchased Item " + i + ": " + transId + "," + sku + "," +
dgId);
}
}
function onFailure(err) {
alert("Error occurred: " + err.errorText + ", " + err.errorID);
}
</script>

Adding Features

241

Managing a subscription
You can use the following functions in the Payment Service for BlackBerry WebWorks to manage subscriptions
in your app.
blackberry.payment.checkAppSubscription initiates a call to confirm that the user has rights to
the current app, offering an app-level subscription.
blackberry.payment.checkExisting initiates a call to confirm that the user has rights to a digital
goods subscription.
blackberry.payment.cancelSubscription initiates a request to cancel a subscription for a digital
good.
Subscriptions can be referred to as app-level subscriptions or digital goods-level subscriptions. When you add
your app to BlackBerry World you can select Subscription as the license type for your app. If you add a digital
good to your app, you can select Subscription as the license type for your in-app digital good.
Checking an app-level subscription
When a user tries to access an app-level subscription, the Payment Service calls
blackberry.payment.checkAppSubscription to verify that the user has rights to the subscription.
If the transaction is successful and the user's BlackBerry ID matches a currently active subscription to the
app, the Payment Service returns the onSuccess function with the parameter
data.subscriptionExists set to True. If no match is made, then data.subscriptionExists is set
to False.
If the transaction is not successfully completed, the Payment Service returns the onFailure function with a
PaymentError object.
<script type="text/javascript">
function checkAppSubscription() {
try {
blackberry.payment.checkAppSubscription(onSuccess, onFailure);
} catch (e){
alert("Error" + e);
}
}
function onSuccess(data) {
alert("User is " + (data.subscriptionExists ? "" : "not ") +
"subscribed to the app.");
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Checking a digital goods subscription

Adding Features

242

When a user tries to access a digital goods subscription, the Payment Service calls
blackberry.payment.checkExisting to verify that the user has rights to the subscription. The function
includes information to describe the digital good: id for the identifier assigned by BlackBerry World or sku for
the SKU of the digital good. If both arguments are included in the transaction, id takes precedence and sku is
ignored.
If the BlackBerry ID associated with the transaction is subscribed to the digital good, the Payment Service
returns the onSuccess function with the parameter data.subscriptionExists set to True. If the
transaction is successful, but no match is made, then data.subscriptionExists is set to False.
If the transaction is not successfully completed, the Payment Service returns the onFailure function with a
PaymentError object.
<script type="text/javascript">
function checkSubscription() {
try {
blackberry.payment.checkExisting({
"id": 12345"
}, onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(data) {
alert("User is " + (data.subscriptionExists ? "" : "not ") +
"subscribed to the item.");
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Canceling a subscription
A user can only cancel a subscription for a digital good; cancellation of other types of purchases (license types)
are not supported. A purchase ID is required in order to identify the subscription that a user wants to cancel, so
when a user makes a request to cancel a subscription, your app calls a getExistingPurchases function
first. A successful getExistingPurchases function returns the purchase ID so that the cancellation can
be completed.
If the blackberry.payment.cancelSubscription function is successful, the onSuccess function
returns data.subscriptionCancelled: True.
Note: If a user successfully cancels a subscription, the subscription remains valid until the end of the current
subscription period. For example, if the user has paid for a subscription to December 31st, and cancels the
subscription on December 15th, the subscription remains valid until the paid period expires on December
31st.

Adding Features

243

If the blackberry.payment.cancelSubscription function is not successful, the onFailure function


returns a PaymentError object.
function cancelSub() {
try {
blackberry.payment.cancelSubscription("18722506",
onCancelSubSuccess, onCancelSubError);
} catch (e) {
alert("cancelSubscription exception");
console.log(e);
}
}
function onCancelSubSuccess(data) {
console.log(data);
alert("Cancellation " + (data.subscriptionCancelled ? "" : "NOT ") +
"successful");
}
function onCancelSubError(error) {
console.log(error);
alert("Error occurred: " + error.errorText + ", " + error.errorID);

Testing in-app purchases


You can use two methods to test the purchase of your digital goods: Locally, with your app set to Development
Mode for simulated purchases; and BlackBerry World testing, with a sandbox user account.

Testing in development mode


Setting developmentMode to True in your app
allows you to use a simulated interface to locally test
digital purchases in your app.
In development mode, your app doesnt contact the
Payment Service server for any transactions. When
you test making a purchase, the purchase options are
displayed as a dialog box. You can choose what
response is returned to the application (either
Success or Failure) and you can specify the reason
for failures using standard error codes.
You can also view a list of successful purchases and
test other activities such as requesting prices,
subscription terms, and payment information.

Adding Features

244

Note: When you tap OK, responses are populated


with simulated data.

You can use development mode to test your logic for retrieving past purchases using purchase data for
transactions made in the current session. This is a great initial testing step for any application that sells digital
goods.

Testing with BlackBerry World


When you add new digital goods to the BlackBerry World vendor portal you can test them while they are still in
a Draft status using a sandbox user account. This is a great method for testing the purchase of your digital
goods in a way that is very close to the end-user experience.
When you use a sandbox user account to purchase digital goods from BlackBerry World, you are not charged
for the purchase. If you use the sandbox user account to purchase the goods or apps of another vendor,
however, you will be charged for the purchase.
To create a sandbox user account, you need to have a BlackBerry World vendor portal membership and sign in
with an Admin level user account.
To test the purchase of your digital goods with a sandbox user account:
1. Sign in to the BlackBerry World vendor portal with a user account that has Admin level priviledges, and
click Sandbox from the left pane.
2. Click Add New User and complete the form using a BlackBerry ID.

3. Add digital goods to a new or existing app that has been added to the vendor portal.
4. Enable Development Mode on your device by navigating to Settings > Security and Privacy > Development
Mode and enabling the Use Development Mode toggle button.

Adding Features

245

5. Start BlackBerry World on your device and swipe down from the top bezel to display the application menu.
Tap Settings > Development Mode, then enter the ID or SKU of your app and tap Load to download your
app.
Note: This Development Mode screen, where you can enter the ID of your application and download it right
from your vendor account, will be visible only if your device is in Development Mode.

After you install your app, you can make purchases of


in-app digital goods without being charged.
All purchases you make will appear on your device as
actual purchases, just like the image on the right.

Here are some things to consider when you use the BlackBerry World vendor portal to test your in-app digital
goods:
Make sure the connection mode in your app is set to Production so that your test purchases go through the
BlackBerry World server.
Apps that are in draft can only be downloaded from BlackBerry World when you are using a sandbox user
account (any other kind of user account won't work).
You can only retrieve past purchases for the current test session. Digital goods that are purchased in a draft
status are not written to the transaction database, so when you end the test session the cache is cleared.
You can test purchasing an app only from a physical device, not from the BlackBerry 10 Device Simulator.
BlackBerry World has a cache, so there may be a delay before your new digital goods are accessible from
BlackBerry World on your device.
You can use a sandbox user account to purchase your own apps and digital goods that are approved and
for sale on the BlackBerry World storefront without being charged.

Adding Features

246

You don't need to remove an existing app from sale on the BlackBerry World storefront to add new digital
goods in draft status, and test them with a sandbox user account.
If you add a new app (meta data) and digital goods to the BlackBerry World vendor portal, you must also
add a release (application data) in order to test the download and purchase of the digital goods.

Push Service
You can use the Push Service to develop a push-enabled app that runs on a BlackBerry device and receives
push messages from a Push Initiator. The Push Initiator can deliver up to 8 KB of content (images, text, or
audio) to many devices at the same time.
To use the Push Service, you must register with BlackBerry. For more information about registering, visit Push
Service in the Platform Services documentation. If you're using the Push Service with BlackBerry Enterprise
Service 10 or later, you don't need to register with BlackBerry. For more information, see Push technology for
the enterprise.

Architecture
The architecture diagram below shows a complete Push Service solution that includes the server-side library
and the client-side library. The libraries work together to deliver content from the Push Initiator to a pushenabled app.

Adding Features

247

Push Initiator
The Push Initiator is the app that creates request messages using the server-side library and sends them
to the push proxy gateway (PPG).
Server-side library
You can use the Push Service SDK as the server-side library or you can provide your own library. If you
use the Push Service SDK, the server-side library provides the Java APIs that the Push Initiator uses to
interact with the PPG. For information about developing a Push Initiator using the Push Service SDK, see
the Push Service SDK documentation.
Push Proxy Gateway
The PPG processes push request messages that it receives from the Push Initiator. After the PPG
processes a push request message, it sends a response message that communicates the overall result of
the push message. The response message contains a result code or a PAP error code.
Client-side library
The BlackBerry 10 WebWorks SDK contains the client-side library. The client-side library provides the
Qt-based APIs that the push-enabled app uses to create a PushService object, create and destroy a
channel, and receive push messages.
Push-enabled app
The push-enabled app runs on a device and acknowledges the push request to the PPG. The pushenabled app uses the client-side library to create a PushService object, create and destroy a channel,
and receive push messages.

What can the Push Service offer?


Increased efficiency
Using the Push Service, you can send content to:
Individual users (unicast)
Many users (multicast)
All of your users (broadcast)
The Push Initiator sends the content when it's available so that data traffic is generated only when
necessary.
Runs in the background
The Push Initiator sends content as bandwidth becomes available so that it doesn't interfere with other
apps.
Minimal battery drain
Adding Features

248

The Push Service minimizes the impact on device batteries because the push-enabled app listens in the
background for the Push Initiator to send content to it. The app doesn't need to poll the push server for
content.
Less coding
The Push Service SDK minimizes the amount of code that you need to write to create a Push Service
solution. You can use the APIs in the server-side and client-side libraries to perform common tasks.

Client-side app
A client-side push-enabled app runs on a device and communicates, through the Push Service, with a serverside app, called a Push Initiator. Before you develop your own push-enabled app, you may find it helpful to try
out the Push Capture sample app available on github.

Prerequisites
To develop and test a push-enabled app, you need the following:
Item

Requirement

Push Initiator

To test your push-enabled app, you need a Push Initiator. To develop the
Push Initiator, you can use our Push Service SDK or another library of your
choice. The Push Service SDK includes two sample Push Initiators that you
may be able to use to test your push-enabled app.

The application ID and PPG


URL for your Push Initiator

You get this information by email when you register your Push Initiator with
BlackBerry. For more information about registering your Push Initiator, see
Push Service and the Push Service Evaluation Form.
If you are using the push technology of the BlackBerry Enterprise Service
only, you don't need to register.

Client-side library

BlackBerry 10 WebWorks SDK 2.0 or later

BlackBerry device

A BlackBerry 10 device with access to a wireless network

Add the Push Service plugins to your project


Before you can use the Push Service APIs with your app, you need to add the following plugins to your project:
com.blackberry.push
com.blackberry.invoked
Adding Features

249

Adding a plugin copies the plugin to your project's plugins folder, and makes the APIs available to your app. It
also adds the required <feature> element to your app's config.xml file. After you add a plugin, the contents
of the plugin are packaged together with your other app resources the next time you build your app. You can
add the plugins from the command line or with the SDK web tool.
To add the plugins from the command line:
1. Open a command line in your app's project folder.
2. Run the following commands:
webworks plugin add com.blackberry.push
webworks plugin add com.blackberry.invoked
To add the plugins using the SDK web tool:
1. With your project open in the SDK web tool, in the navigation panel, click Plugins.
2. In the Plugin Name or URL field, type com.blackberry.push, then click Add plugin
3. Repeat the above step for the com.blackberry.invoked plugin.

Update your config.xml file


Before you can use the Push Service APIs with your app, you need to update your app's config.xml file with
the following statements.
1. Add an entry for the invoke events that your app receives for push messages.
<!-- config.xml -->
<!-- Need to put an invoke entry here for push. -->
<!-- The id here must match the invokeTargetId passed in -->
<!-- one of the ops to blackberry.push.PushService.create. -->
<rim:invoke-target id="sample.pushreceiver.invoke.push">
<type>APPLICATION</type>
<filter>
<action>bb.action.PUSH</action>
<mime-type>application/vnd.push</mime-type>
</filter>
</rim:invoke-target>
Note the value for the invoke-target id. This value must match the invokeTargetID that's passed
into the call to the PushService.create() function. For more information about the
invokeTargetID and PushService.create(), see Creating a PushService object.
Also note that the action tag is set to bb.action.PUSH. This value indicates that the invocation relates
specifically to push messages. The event listener in the sample app also uses this value to check that the
invoke event is a push message. For more information about the event listener and the push invoke event,
see Receiving a push message.

Adding Features

250

2. To allow your app to be opened from BlackBerry Hub notifications, add the following statements.
<!-- config.xml -->
<!-- Have an invoke entry here for when a notification is clicked
<!-- on in the BlackBerry Hub. This will cause the app
<!-- to be opened -->
<rim:invoke-target id="sample.pushcapture.invoke.open">
<type>app</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>text/plain</mime-type>
</filter>
</rim:invoke-target>
Note that the action tag is set to bb.action.OPEN. This value indicates that the invocation relates to
an open invoke event. In the sample app, an open invoke event occurs when a user taps a notification for a
push message in the BlackBerry Hub. The event listener in the sample app also uses this value to check
that the invoke event is an open invoke event. For more information about the event listener and the open
invoke event, see Handling notifications in the BlackBerry Hub.

Creating a PushService object


The sample app calls the static PushService.create() function to create a PushService object to
perform push-related operations. After the PushService object is instantiated, the sample app can make calls
to the object to receive and process push messages.
In your app, you need to call PushService.create() with one appID parameter and one
invokeTargetID parameter. If you try to create another PushService object with a different appID or
invokeTargetID parameter, the create operation fails with an exception.
The appID parameter corresponds to the application ID that you specified when you configured the sample
app. For details about configuring the sample app, see Configure the sample app.
The invokeTargetID is a value that you generate. The value identifies the push-enabled app that's the
target of a push message, and that's invoked when a push message arrives. The value must be the same in the
config.xml file for your app and in the PushService.create() function. For more information about
updating your config.xml file, see Update your config.xml file.

Call PushService.create()
The static PushService.create() function instantiates a PushService object. If the object is created
successfully, the create function calls the successCreatePushService() callback function with the
PushService object that the app can use. If the object isn't created, the create function calls the
failCreatePushService() callback function with a result number value. The result corresponds to
one of the error constants provided in the PushService class. For more information about the error
constants, see the PushService class in the API Reference.

Adding Features

251

The call to PushService.create() is different depending on whether or not the Push Service is used with
the BlackBerry Enterprise Service. If the Push Service is not used with the BlackBerry Enterprise Service, the
create function call looks like this:
var ops;
if (sample.pushcapture.usingpublicppg) {
// Consumer app using public push
ops = { invokeTargetId : sample.pushcapture.invokeTargetIdPush,
appId : sample.pushcapture.appid,
ppgUrl : sample.pushcapture.ppgurl
};
} else {
// Enterprise app using enterprise push
}
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
If the Push Service is used with the BlackBerry Enterprise Service, the create function call looks like this:
var ops;
if (sample.pushcapture.usingpublicppg) {
// Consumer app using public push
} else {
// Enterprise app using enterprise push
if (sample.pushcapture.usesdkaspi) {
// If we're using the Push Service SDK for our Push
// Initiator implementation, we will have specified
// our own application ID to use.
ops = { invokeTargetId :
sample.pushcapture.invokeTargetIdPush,
appId : sample.pushcapture.appid
};
} else {
ops = { invokeTargetId :
sample.pushcapture.invokeTargetIdPush };
}
}
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);

Adding Features

252

Call successCreatePushService()
The successCreatePushService() callback function stores the PushService object in a global
variable. The app can use the global variable to make calls to the other functions of the PushService class
without having to call PushService.create() again.
PushCapture.prototype.successCreatePushService = function(service) {

};

// Save the service into a global variable so that it can be


// used later for operations such as create channel, destroy
// channel, etc.
sample.pushcapture.pushService = service;
// ...

Call failCreatePushService()
The failCreatePushService() callback function shows the error handling if the PushService object
isn't created, and the error messages that you can use for debugging. In your app, you might want to handle
the errors differently. For example, you might want to retry an operation first before displaying an error
message. The API Reference lists the possible actions that you can take for each error constant. The API
Reference also tells you which error codes apply to which function calls.
PushCapture.prototype.failCreatePushService = function(result) {
// ...
if (result == blackberry.push.PushService.INTERNAL_ERROR) {
alert("Error: An internal error occurred while calling " +
"blackberry.push.PushService.create. Try restarting the
app.");
} else if (result == blackberry.push.PushService.
INVALID_PROVIDER_APPLICATION_ID) {
// This error only applies to consumer apps that use
// a public/BIS PPG
alert("Error: Called blackberry.push.PushService.create with
a missing " + "or invalid appId value. It usually means a
programming error.");
} else if (result == blackberry.push.PushService.
MISSING_INVOKE_TARGET_ID) {
alert("Error: Called blackberry.push.PushService.create with
a missing " + "invokeTargetId value. It usually means a
programming error.");
} else if (result ==
blackberry.push.PushService.SESSION_ALREADY_EXISTS) {
alert("Error: Called blackberry.push.PushService.create with an
appId or " + "invokeTargetId value that matches another
app. It usually means a " + "programming error.");
} else {
alert("Error: Received error code (" + result + ") after " +
"calling blackberry.push.PushService.create.");

Adding Features

253

};

Running an app in the background


You can use the Push Service APIs to start running your app when a push message arrives, and to continue
running it in the background. Using the Push Service saves valuable device resources because your app
doesnt have to be running all the time to receive push messages.
The sample app calls the launchApplicationOnPush() function with a value of true. This call registers
the app so that it starts running in the background if it isn't already running when a push message arrives. If
you don't want to register your app so that it starts running in the background when a push message arrives,
you can call launchApplicationOnPush() with a value of false. The push messages that arrive when
the value is false are delivered only if your app is running when the messages arrive.
PushCapture.prototype.successCreatePushService = function(service) {
// ...
sample.pushcapture.pushService.launchApplicationOnPush(
sample.pushcapture.launchapp,
sample.pushcapture.launchApplicationCallback);
};
The launchApplicationCallback() callback function shows the error handling if the launch operation
fails, and the error messages that you can use for debugging. In your app, you might want to handle the errors
differently. For example, you might want to retry an operation first before displaying an error message. The API
Reference lists the possible actions that you can take for each error constant. The API Reference also tells you
which error codes apply to which function calls.
if (result == blackberry.push.PushService.SUCCESS) {
// Successfully registered to launch
} else {
if (result == blackberry.push.PushService.INTERNAL_ERROR) {
alert("Error: An internal error occurred while calling
launchApplicationOnPush. " + "Try restarting the
app.");
} else if (result == blackberry.push.PushService.
CREATE_SESSION_NOT_DONE) {
alert("Error: Called launchApplicationOnPush without an " +
"existing session. It usually means a programming error.");
} else {
alert("Error: Received error code (" + result + ") after "
+ "calling launchApplicationOnPush.");
}
}
};

Adding Features

254

Creating a push channel


The sample app creates a push channel to the PPG to receive push messages. The app only needs to create a
channel the first time it starts, or if a destroy channel occurred previously, and you want to start receiving push
messages again.
If you chose to subscribe with the Push Service SDK when you configured the sample app, the Push Initiator
requires a username and password that it authenticates before allowing the subscription. The sample app
provides a Register screen where the user can type any username and password. For your app, check with
your push content provider to get a valid username and password.
You can open the Register screen by tapping Register at the bottom of the device screen. The Register screen
appears.

After you type the username and password, and tap Submit, the sample app tries to create a channel.
If you're not subscribing with the Push Service SDK, you don't need to provide a username and password. You
can simply tap Register and Submit, and the sample app tries to create a channel.

Call createChannel()
The sample app calls createChannel() to create a channel to the PPG. The createChannel() function
includes the createChannelCallback callback function as an argument. If the channel creation is
successful, createChannelCallback returns a token that isn't null. The token represents the device and
the app that receives push messages. You need to communicate the token to the Push Initiator so that the
Push Initiator can use the token to send push messages to the app. If the channel creation fails, the token is
null, and you should ignore it.
sample.pushcapture.pushService.createChannel(
sample.pushcapture.createChannelCallback);
The createChannelCallback callback function shows the error handling if the create channel operation
fails. In your app, you might want to handle the errors differently. For example, you might want to retry an
operation first before displaying an error message. The API Reference lists the possible actions that you can
take for each error constant. The API Reference also shows which error codes apply to which function calls.
sample.pushcapture.constructor.prototype.createChannelCallback =
function(result, token) {
if (result == blackberry.push.PushService.SUCCESS) {
// Success! Communicate the token to the Push Initiator.
} else {
Adding Features

255

};

// Error handling

Call subscribeToPushInitiator()
If the channel creation is successful, and you're subscribing with the Push Service SDK, the sample app calls
subscribeToPushInitiator() to subscribe with the Push Initiator. The subscribe function passes in the
token to the Push Initiator and the username and password that you typed on the Register screen. If you're not
subscribing with the Push Service SDK, the sample app doesn't call subscribeToPushInitiator().
sample.pushcapture.constructor.prototype.subscribeToPushInitiator =
function(token) {
document.getElementById("progressinfo").innerHTML
= "Subscribing to Push Initiator...";
var type;
if (sample.pushcapture.usingpublicppg) {
type = "public";
} else {
type = "bds";
}
var
var
var
var
var

username = document.getElementById("reguserid").value.trim();
password = document.getElementById("regpwd").value.trim();
address = token;
osversion = blackberry.system.softwareVersion;
model = blackberry.system.hardwareId;

var params = "appid=" + encodeURIComponent(sample.pushcapture.appid)


+ "&";
params += "address=" + address + "&";
params += "osversion=" + osversion + "&";
params += "model=" + model + "&";
params += "username=" + encodeURIComponent(username) + "&";
params += "password=" + encodeURIComponent(password) + "&";
params += "type=" + type;
var subscribeUrl = sample.pushcapture.piurl + "/subscribe?" +
params;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", subscribeUrl);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var status = xmlHttp.status;
var returnCode = xmlHttp.responseText;
sample.pushcapture.pushInitiatorSubscribeHandler(status,
returnCode);
Adding Features

256

};
};

xmlHttp.send();

Receiving a push message


The sample app registers an event listener that listens for invoke events. The invoke event can be a push
invoke event or an open invoke event. A push invoke event occurs when the app receives a push message. An
open invoke event occurs when a user taps a notification for a push message in the BlackBerry Hub. The
following code sample shows you how the sample app handles a push invoke event. To see how the sample
app handles an open invoke event, see Handling notifications in the BlackBerry Hub.
This is the event listener that the sample app registers.
// Add an event listener to handle incoming invokes
document.addEventListener("invoked", sample.pushcapture.onInvoke);
The onInvoke() function first checks the action property of the invokeRequest to see if it matches the
string value bb.action.PUSH. The function then calls extractPushPayload() which returns a
PushPayload object. The app processes the PushPayload object by calling
pushNotificationHandler(). In your app, you can provide the code to process the push message in a
way that's appropriate for your environment.
PushCapture.prototype.onInvoke = function(invokeRequest) {
if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.PUSH") {
var pushPayload = sample.pushcapture.pushService.
extractPushPayload(invokeRequest);

};

sample.pushcapture.pushNotificationHandler(pushPayload);
} else if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.OPEN") {
// Do something
}

The push message is stored in the data field of the PushPayload object. The type of the data field is Blob.
You need to convert the push message from a Blob object to a format that you can work with. The API
Reference shows you how to convert the Blob object to binary data and plain text.
You should also look at the sample.pushcapture.pushNotificationHandler() function in the
sample app code for examples of how to check for duplicate push messages, how to store push messages in
the database, and how to convert the Blob object to plain text and Base64 encoded strings for binary data.

Adding Features

257

Acknowledging the receipt of a push message


The Push Initiator can send a confirmed push message with application-level reliability. The push-enabled app
must acknowledge a confirmed push message. The push-enabled app can determine if it received a confirmed
push message by checking the Boolean field isAcknowledgeRequired from the PushPayload object. If
the property is set to true, the push-enabled app must acknowledge the push message by either accepting it
by calling pushpayload.acknowledge(true) or rejecting it by calling
pushpayload.acknowledge(false). For more information about these functions, see the API
Reference.
The sample app checks the isAcknowledgeRequired field when it calls
pushNotificationHandler(). The sample app acknowledges the receipt of the push message by
accepting it by calling pushpayload.acknowledge(true).
//
//
//
//
if

If an acknowledgement of the push is required (that is, the push


was sent as a confirmed push), then you must either accept or reject
the push. A confirmed push is equivalent terminology to the push
being sent with application level reliability.
(pushpayload.isAcknowledgeRequired) {
// In our sample, we always accept the push, but situations might
// arise where an app might want to reject the push. For
// example, after looking at the headers that came with the push
// or the data of the push, we might decide that the push received
// did not match what we expected, and so we might want to reject
// the push.
pushpayload.acknowledge(true);

Exiting after processing a push message


If you register your app to start running in the background when a push message arrives using the
launchApplicationOnPush() function, your app continues to run after it processes the message. This
can use up device resources, so it's a good practice to exit your app after it processes a push message. You
have to be careful, however, not to exit your app if it was ever displayed full screen (in the foreground) because
the user might still be using your app.
To exit after processing a push message, the sample app creates the hasBeenInForeground boolean
variable to check whether the app was ever displayed full screen. The variable is set initially to false.
/**
* Boolean indicating whether the app has ever been in the
* foreground. This boolean is used to determine whether we are
* dealing with the situation where the app is set to launch
* on a new push, the app is currently not running, and a new
* push comes in. The app will be launched in the background
* to process the push. If the user does not bring the app to the
* foreground while we are processing the push, then we exit
Adding Features

258

* the app. This is to save battery life and performance on


* the device by not having the app running in the background
* after every push that comes in.
*/
this.hasBeenInForeground = false;
The sample app checks the current window state when it starts to see if it starts full screen. If it does, the app
sets the hasBeenInForeground variable to true. The app also listens for the resume event. If this event
occurs, the app was displayed full screen by the user, and the hasBeenInForeground variable is set to
true.
PushCapture.prototype.initPushService = function() {
// Check if the app started up in the foreground.
// We are trying to determine if the app was launched in
// the background and so we would be able to process a push and
// exit from the app.
if (blackberry.app.windowState == "fullscreen") {
sample.pushcapture.hasBeenInForeground = true;
}
// We also use the resume event to help determine if the
// app has ever been brought to the foreground
// (from the background - hence it's being "resumed").
document.addEventListener("resume", sample.pushcapture.onResume);
// More code
};
PushCapture.prototype.onResume = function() {
sample.pushcapture.hasBeenInForeground = true;
};
After the sample app processes the push message, it checks the hasBeenInForeground variable. If the
variable is true, the app doesn't exit. If the variable is false, the app was never displayed full screen. The
app started in the background when a push message arrived, and can exit after it processes the message.
// Exit the app after processing the push if the
// app has not been brought to the foreground
if (!sample.pushcapture.hasBeenInForeground) {
setTimeout(function() {
blackberry.app.exit();
}, 1000);
}

Handling notifications in the BlackBerry Hub


The sample application handles notifications of push messages in the BlackBerry Hub in the following ways:
Adding Features

259

When a user taps on a notification in the BlackBerry Hub, the sample app receives an open invoke event,
and displays the push message that corresponds to the notification.
When the sample app receives a push message, it adds a notification to the BlackBerry Hub.
When a user taps on the push message in the sample app, the app removes the notification from the
BlackBerry Hub.
When a user deletes an individual push message in the sample app, the app removes the notification for
the push message from the BlackBerry Hub.
When a user taps Mark All Open or Delete All in the sample app, the app removes all the notifications for
the sample app from the BlackBerry Hub.

Display a push message for an open invoke event


The sample app registers an event listener that listens for invoke events. An open invoke event occurs when a
user taps a notification for a push message in the BlackBerry Hub.
// Add an event listener to handle incoming invokes
document.addEventListener("invoked", sample.pushcapture.onInvoke);
The onInvoke() function first checks the action property of the invokeRequest to see if it matches the
string value bb.action.OPEN. If the property matches the string value, the user tapped a notification in the
BlackBerry Hub. The sample app displays the push message that corresponds to the notification.
PushCapture.prototype.onInvoke = function (invokeRequest) {
if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.PUSH") {
// Do something
} else if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.OPEN") {
// The payload from the open invoke is the seqnum for the push
// in the database.
var payload = sample.pushcapture.b64_to_utf8(invokeRequest.data);
if (sample.pushcapture.isDomReady) {
if (document.getElementById("push-list") == null) {
// We are not on the home screen.
// Pop off the current screen so that the push can
// be opened properly.
bb.popScreen();
// We have to wait until the pop finishes and the home
// screen loads before we can open the push, so we do
// it after the pushes are displayed by the call to
// initPushList() in pushlist.js.
sample.pushcapture.isOpenInvoke = true;
sample.pushcapture.selectedPushSeqnum = payload;
} else {
// We are on the home screen, simply open the push.
sample.pushcapture.openPush(payload);
}
Adding Features

260

};

} else {
// The home screen has not loaded up yet. We need to wait
// until it loads before we can open the push, so we do it
// after the pushes are displayed by the call to
// initPushList() in pushlist.js.
sample.pushcapture.isOpenInvoke = true;
sample.pushcapture.selectedPushSeqnum = payload;
}

Add a notification to the BlackBerry Hub


To add a notification for the sample app to the BlackBerry Hub, the sample app creates a Notification
object.
// Add a notification to the BlackBerry Hub for this push
var title = "Push Capture";
var options = {
body: "New " + extension + " push received",
tag: seqnum + sample.pushcapture.notificationSuffix,
target: sample.pushcapture.invokeTargetIdOpen,
targetAction : "bb.action.OPEN",
// We set the data of the invoke to be the seqnum of the
// push so that we know which push needs to be opened
payload : sample.pushcapture.utf8_to_b64(seqnum.toString(10))
};
new Notification(title, options);
Notice that targetAction matches the bb.action.OPEN action in the config.xml file. The
sample.pushcapture.invokeTargetIdOpen constant has a value of
sample.pushcapture.invoke.open which matches the invoke-target id in the config.xml file.
For more information about the config.xml file, see Update your config.xml file. Additionally, when you
create a notification, you need to encode the payload that you specify in Base64.

Remove a notification from the BlackBerry Hub


To remove a notification for the sample app from the BlackBerry Hub, the sample app calls
Notification.remove(), and passes in the sequence number of the push message that needs to be
removed. This code is called when the user taps the trash can icon next to a push message in the sample app,
and answers Yes to the confirmation message. The sample app also deletes the push message from the app.
Notification.remove(sample.pushcapture.selectedPushSeqnum +
sample.pushcapture.notificationSuffix);

Adding Features

261

Remove all notifications from the BlackBerry Hub


To remove all the notifications for the sample app from the BlackBerry Hub, the sample app calls
Notification.remove() with the sequence number of each push message in the sample app. This code
is called when the user taps either Mark All Open or Delete All in the sample app.
for (var i = 0; i < results.rows.length; i++) {
Notification.remove(results.rows.item(i).seqnum +
sample.pushcapture.notificationSuffix);
}

Destroying a push channel


The sample app destroys the push channel to the PPG to stop receiving push messages.
If you chose to subscribe with the Push Service SDK when you configured the sample app, the Push Initiator
requires a username and password that it authenticates before unsubscribing. The sample app provides an
Unregister screen where the user can type any username and password. For your app, check with your push
content provider to get a valid username and password.
You can open the Unregister screen box by tapping Unregister at the bottom of the device screen. The
Unregister screen appears with the currently registered user's name and password.

After you tap Submit, the sample app tries to destroy the channel.
If you're not subscribing with the Push Service SDK as the Push Initiator, you don't need to provide a username
and password. You can tap Unregister and Submit, and the sample app tries to destroy the channel.

Call destroyChannel()
The sample app calls destroyChannel() to destroy the channel to the PPG. The destroyChannel()
function includes the destroyChannelCallback callback function as an argument.
sample.pushcapture.pushService.destroyChannel(
sample.pushcapture.destroyChannelCallback);
The destroyChannelCallback callback function shows the error handling if the destroy channel
operation fails. In your app, you might want to handle the errors differently. For example, you might want to
retry an operation first before displaying an error message. The API Reference lists the possible actions that

Adding Features

262

you can take for each error constant. The API Reference also shows which error codes apply to which function
calls.
sample.pushcapture.constructor.prototype.destroyChannelCallback =
function(result) {
if (result == blackberry.push.PushService.SUCCESS ||
result == blackberry.push.PushService.
CHANNEL_ALREADY_DESTROYED ||
result == blackberry.push.PushService.
CHANNEL_ALREADY_DESTROYED_BY_PROVIDER ||
result == blackberry.push.PushService.
CHANNEL_SUSPENDED_BY_PROVIDER ||
result == blackberry.push.PushService.
PPG_SUBSCRIBER_NOT_FOUND ||
result == blackberry.push.PushService.
CREATE_CHANNEL_NOT_DONE) {
// Success!
} else {
.
.
.
// Error handling
}
};

Call unsubscribeFromPushInitiator()
If the destroy channel operation is successful, and you're subscribing with the Push Service SDK, the sample
app calls unsubscribeFromPushInitiator() to unsubscribe from the Push Initiator. The unsubscribe
function passes in the username and password that you typed on the Unregister screen. If you're not
subscribing with the Push Service SDK, the sample app doesn't call
unsubscribeFromPushInitiator().
sample.pushcapture.constructor.prototype.unsubscribeFromPushInitiator
= function() {
document.getElementById("progressinfo").innerHTML = "Unsubscribing
from Push Initiator...";
var username = document.getElementById("unreguserid").value.trim();
var password = document.getElementById("unregpwd").value.trim();
var params = "appid=" + encodeURIComponent(sample.pushcapture.appid)
+ "&";
params += "username=" + encodeURIComponent(username) + "&";
params += "password=" + encodeURIComponent(password);
var unsubscribeUrl = sample.pushcapture.piurl + "/unsubscribe?"
+ params;
var xmlHttp = new XMLHttpRequest();
Adding Features

263

xmlHttp.open("GET", unsubscribeUrl);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var status = xmlHttp.status;
var returnCode = xmlHttp.responseText;

};
};

sample.pushcapture.pushInitiatorUnsubscribeHandler(status,
returnCode);

xmlHttp.send();

Detecting a changed SIM card


When a user changes a SIM card in a BlackBerry device, the BlackBerry 10 WebWorks SDK automatically
destroys the channel to the PPG for security purposes. A new user might be using the device, and that user
shouldn't receive push messages that were intended for the previous user. In your app, you should
authenticate all new users, and create a new channel to the PPG.
The sample app passes in the onSimChange() callback function as part of the call to
PushService.create() which creates the PushService object.
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
The onSimChange() callback function performs the following actions when a user changes a SIM card in a
device:

Removes the user and all the push messages associated with the user from the database.
Removes notifications in the BlackBerry Hub that are associated with the user.
Unsubscribes the user from the Push Initiator if the user chose to subscribe with the Push Service SDK.
Displays a message indicating that the SIM card has changed.
Displays the Register screen so that a new user, or the same user with a new SIM card, can register.

Handling a push transport error or PPG server error


There might be occasions when the sample app can't create or destroy a channel because of a push transport
error or a PPG server error. These errors don't occur if you're using the Push Service with the BlackBerry
Enterprise Service.

Adding Features

264

Push transport error


This error occurs when there's a problem with the mobile network, the user's wireless connection, or the lowlevel communications layer that the Push Service uses. When the channel operations fail because of one of
these problems, the Push Service issues a
blackberry.push.PushService.PUSH_TRANSPORT_UNAVAILABLE error code. The sample app
displays an error message to the user when it receives this error code.
else if (result == blackberry.push.PushService.PUSH_TRANSPORT_UNAVAILABLE)
{
// This error code only applies to a consumer app using the
// public/BIS PPG
document.getElementById("errormsg").innerHTML = "Error: Create
channel failed as the push transport " + "is unavailable. Verify
your mobile network and/or Wi-Fi are turned on. If they are on,
you will " + "be notified when the push transport is available
again.";
}

PPG server error


This error occurs when the PPG server is unavailable and returns an error. When the channel operations fail
because of this server error, the Push Service issues a
blackberry.push.PushService.PPG_SERVER_ERROR error code. The sample app displays an error
message to the user when it receives this error code.
else if (result == blackberry.push.PushService.PPG_SERVER_ERROR) {
// This error code only applies to a consumer app using the
// public/BIS PPG
document.getElementById("errormsg").innerHTML = "Error: Create
channel failed as the PPG is " + "currently returning a server
error. You will be notified when the PPG is available again.";
}

Call onPushTransportReady()
To handle the push transport error and PPG server error, the sample app specifies an
onPushTransportReady() callback in its call to the static PushService.create function so that the
app can try to create or destroy the channel again.
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);

Adding Features

265

The onPushTransportReady() callback checks the value of lastFailedOperation to determine


which operation failed. The callback also displays a message to the user to register again if the create channel
operation failed, or to unregister again if the destroy channel operation failed. The user needs to register or
unregister again because the errors prevented the user from successfully registering or unregistering in the
first place. For details about registering or unregistering the user, see Creating a push channel or Destroying a
push channel.
sample.pushcapture.constructor.prototype.onPushTransportReady =
function(lastFailedOperation) {
var message = "The push transport/wireless network/PPG is now
available. Please try ";
if (lastFailedOperation == blackberry.push.PushService.
CREATE_CHANNEL_OPERATION) {
message += "registering ";
} else {
message += "unregistering ";
}
message += "again.";
};

alert(message);

The sample app handles these errors by explicitly telling the user about the errors. In your app, you could
handle the errors the same way, or your onPushTransportReady callback could check which operation
failed, and then try the operation again without telling the user about the errors.

Adding Features

266

Frameworks
Find out more about the community frameworks that you can use in your WebWorks apps.

jQuery
If you want to use jQuery or jQuery Mobile in your BlackBerry WebWorks app, you might find the information in
this section helpful.

What is jQuery?
jQuery is a JavaScript library that simplifies many complex actions, such as DOM manipulation and web service
calls, using JSON or AJAX. When you use jQuery, you can minimize the amount of code you write, reduce
development cycles, and simplify the maintenance of your application.
To find out more about jQuery, visit the official jQuery website.
It's important to remember that since jQuery is built on top of JavaScript, the functionality of your code on a
given platform depends on the platform's support of JavaScript. If you already have a desktop web application
that uses jQuery, there is a very good chance that currently existing as well as future desktop and mobile
platforms will simply run your code.
You can use jQuery for commercial application development. To use jQuery in commercial projects, view the
jQuery license.

What is jQuery Mobile?


jQuery Mobile is a UI framework based on jQuery Core APIs. jQuery Mobile includes a number of widgets (also
called components or controls). For more information, visit the jQuery Mobile website.
jQuery Mobile works in the following way:
You define jQuery Mobile components in your DOM by specifying the appropriate jQuery Mobile markup.
Once your app loads, the jQuery Mobile framework replaces the components you identified with the
appropriate controls.
For example, let's say you define a layout grid by specifying the ui-grid-a class on a <div> tag. jQuery
Mobile uses the class information only as a reference and attaches any additional CSS, and when applicable,
HTML and JavaScript, that are necessary for the component to function.

Frameworks

267

Things to consider when you're using jQuery


Cross-browser compatibility
jQuery is a JavaScript framework, so its functionality is subject to the features that the underlying browser
specifically supports. If you already have a web application that uses jQuery, you likely tested a variety of
scenarios on the more popular browsers, such as Windows Internet Explorer, Mozilla Firefox, Google Chrome,
Opera, or Safari.
jQuery itself supports the most popular browsers. For information about jQuery support for each browser, visit
the Browser Compatibility page on the jQuery site.

Device hardware capability


Most desktop computers now have multiple cores, at least 2.0 GHz of processing power, and enough RAM to
accommodate the most inefficiently built applications. Mobile devices like smartphones and tablets have
come a long way, but fall short of many computer benchmarks. The differences in hardware among different
models of BlackBerry devices can significantly affect application performance. Devices with similar hardware
but that run different OS versions also affect application performance.
If you're porting a jQuery-based desktop application to the BlackBerry platform, and even if all jQuery features
are supported on your target BlackBerry platform, you may still need to optimize your app to address the
resource limitations of the platform. jQuery is not designed to be a light framework, such as jqlite, zepto.js,
jq.Mobi, or others, so you might notice a slight overhead in performance in your app, even with the minified
form of jQuery. On the latest BlackBerry devices, limited hardware capability or resouce limitations is much
less of an issue.

UI considerations
BlackBerry WebWorks uses all aspects of HTML5, including JavaScript and CSS, and provides you with
standard UI components that you can use in your application. This gives you the opportunity to be as creative
with your application design as you want.
However, there are times when you simply want to focus on development, and not spend too much time laying
out, skinning, and tweaking various UI components.
You can use the jQuery UI library to simplify the process. This library provides you with many powerful
components. However, this flexbility comes with the same considerations previously noted for using the jQuery
framework in general. Specifically, there will be additional performance overhead. There are options available
that can help you minimize this overhead. For example, jQuery Mobile is better suited for developing on the
mobile platform as it addresses a lot of the performance concerns. Using jQuery Mobile tends to result in
leaner, performance-conscious components. But since jQuery Mobile relies on the core jQuery framework,
there is still some overhead.

Getting that native feeling


You can use any number of UI libraries and extensions to meet the needs for performance and style. A
common concern, however, is that many of these libraries lack the look and feel of native BlackBerry
Frameworks

268

applications. This includes the jQuery Mobile framework. The jQuery Mobile framework does not provide any
BlackBerry specific look and feel either. There are two options to address this.
One option is from an open-source project that is integrated with jQuery Mobile to provide a BlackBerry 10 look
and feel to your BlackBerry WebWorks apps. For more information, visit the GitHub repository for the jQuery
Mobile BlackBerry 10 theme.
The other option is to use the bbUI.js framework. It is a UI framework that is designed specifically for the
BlackBerry platform with a focus on BlackBerry 10. This framework makes a number of optimizations to
increase performance and reduce the memory footprint. Similar to using the jQuery Mobile framework, to use
the bbUI.js framework you set <div> attributes to identify components that the bbUI.js framework then
replaces to turn the components into compelling controls. For more information, visit the GitHub repository for
the bbUI.js framework.
.

Debugging
Eventually, you're bound to run into issues. With some luck, the problem is simply a missing semicolon. Other
times, you might come across something that's really broken. Here are some ways to more easily solve your
problem.

JavaScript validation
Before you run your code, you should be fairly confident that it will run. JSLint is a great tool for validating code.
Depending on which HTML or text editor you're using, there is likely a JSLint plug-in that you can leverage as
well. Running JSLint will pick out the most common errors for you, including syntax or formatting.

Web Inspector
If you have developed a web application for desktop computers, chances are you've come across some form of
Web Inspector tool to let you examine the source code as it runs. This functionality is also available for
BlackBerry WebWorks applications. See Debugging using Web Inspector on page 292 for details on using Web
Inspector.

Reporting bugs
If you find a bug, you can report it at the appropriate site below:
jQuery Core
BlackBerry WebWorks APIs
If you have feedback regarding your experience with BlackBerry WebWorks and jQuery, visit the Web and
WebWorks Development forums to share your insight or see what others are saying.

Resources
Here are some resources that can help you with your jQuery application:
Frameworks

269

BlackBerry WebWorks
Common BlackBerry WebWorks development pitfalls that can be avoided

Code signing
Set up your computer for testing and signing
Building and signing your completed app

Debugging
JSLint
Debugging using Web Inspector on page 292

GitHub repositories
blackberry/WebWorks-Samples - Sample BlackBerry WebWorks applications

Other resources
BlackBerry World

Sencha Touch 2
Sencha Touch 2 is a widget library for creating web apps for mobile devices. It contains widgets (also known as
components) that enable you to create web apps for mobile devices with the look and feel of native mobile
apps. It is based entirely on web standards such as HTML5, JavaScript, and CSS3.

Benefits of using Sencha Touch 2


You can use the widgets in Sencha Touch 2 to make your apps robust and user-friendly. Some of the widgets
available in Sencha Touch 2 include:

Tab panels
Nested lists
Navigation views
Form controls
Carousels
Cards

Sencha Touch 2 also has the following features:


Data management: Sencha Touch 2 translates JSON objects to Model objects automatically. This enables
you to feed in different types of data sources or destinations. You have the option to use JSON, JSONP,
AMF, and SOAP out-of-the-box.
Frameworks

270

Offline capabilities: APIs are available to provide offline data storage functionality that is based on HTML5
local storage and session storage mechanisms.
AJAX support: Full AJAX support, including CORS and JASON-P.
DOM support: Support for manipulating HTML and XML using the DOM-related methods.
Feature detection: Automatic detection of features such as geolocation, canvas, and orientation.
Touch events: Support for a full range of touch events and gestures such as tap, swipe, and pinch.
Further reading
Getting started with Sencha Touch
Features of Sencha Touch

Support for Sencha Touch on the BlackBerry Application Platform


Sencha Touch 2.1 is supported on devices that run the BlackBerry 10 OS. The 2.1 version addresses some of
the performance-related issues that might have affected BlackBerry apps that were built using the 2.0 version
and had complex nested layouts.
Note: The performance improvements in Sencha Touch 2.1 result from changes to the DOM structure and
additional CSS rules to help the browser render complex layouts better, without making any changes to the
APIs. If you built your app using Sencha Touch 2.0 and used custom CSS, consider reviewing those CSS
selectors if you are updating your app to Sencha Touch 2.1.

Applying the BlackBerry theme


Sencha Touch can detect a mobile device platform automatically and loads the appropriate theme. Sencha
Touch 2.1 contains a predefined theme for the BlackBerry 10 OS, so it lets you automatically apply a look and
feel to your apps that is native to the BlackBerry 10 OS, in addition to applying your own styles. You can
download the beta theme for BlackBerry 10 from the following webpage: http://www.sencha.com/blog/
introducing-sencha-touch-2-1-and-more/

Packaging, testing, and debugging your BlackBerry 10 app


You must package your app for the BlackBerry 10 OS before you can deploy your app on a BlackBerry
simulator or a device. You can package, test, and debug your app using the BlackBerry 10 WebWorks SDK.
Further reading:
Modifying your config.xml file
Building your app for testing
Building and signing your completed app

Frameworks

271

Dojo Toolkit
Overview
The Dojo Toolkit is a JavaScript toolkit for creating cross-platform JavaScript/AJAX applications. It contains a
rich collection of lightweight and independent modules. The toolkit enables you to use its lightweight solution
for DOM manipulation and AJAX services by allowing you to choose only the modules you need for your
application. It also allows you to create complex JavaScript classes with multiple inheritance.

Benefits of using the Dojo Mobile module


Dojo Mobile is a lightweight module that contains widgets (also known as components) for developing mobile
apps. The widgets contain HTML, CSS, and JavaScript code, and you can use them to make your applications
robust and user friendly. The widgets in the Dojo Mobile module enable you to display grids, charts, forms, and
data that are optimized for viewing and interaction on a mobile device. Some of the widgets available in the
Dojo Mobile module include:

Date/time picker
Accordion views
Pop up menu with icons
TabBar views
Image/content carousel
Transition effects

Using modules from other packages


DojoX package
You are not limited to using only the widgets in the Dojo Mobile module of the DojoX package. There are many
widgets in other modules of the DojoX package that you can use (for example, widgets for dynamic charts,
enhanced grid displays, cross-platform graphics, mapping using OpenLayers, and so on).

Dijit package
You can also add functionality from the Dijit package. The Dijit package includes an extensive library of UI
controls and other useful widgets that are not available in the Dojo Mobile module, such as a color palette or a
calendar. While the widgets in Dojo Mobile are specifically tailored for mobile devices, you might still want to
explore the widgets available in Dijit. As of version 1.8, most widgets in Dijit support mobile device events such
as touch and gesture events.
Frameworks

272

Note: There are plenty of GUI widgets in the DojoX package and there are other packages, such as dgrid
( http://dgrid.io/ ), which offer a high-performance grid that works on mobile and desktop browsers.

Using Dojo in BlackBerry WebWorks apps


Using the AMD module loader
Asynchronous Module Definition (AMD) is an API for defining reusable modules that you can load
asynchronously in your application. Using asynchronous loading of AMD modules in your application reduces
application load time by up to ten times when compared to synchronous loading of modules, making it suitable
for mobile applications.
To use asynchronous loading of AMD modules, set the "async" property of the Dojo Toolkit to true. It
switches Dojo into baseless Dojo (async mode or AMD mode). With baseless Dojo, your application loads the
module loader first, so that you can pick only the modules that you need in your application. This keeps your
BlackBerry WebWorks application lightweight. Include the following code in your BlackBerry WebWorks
application's index.html file to use the AMD module loader:
<script data-dojo-config="async:true"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js"></
script>
Note:
While you can include the Dojo loader using a protocol-less URL in desktop applications, in a BlackBerry
WebWorks application, you must include the http or https protocol identifier to properly locate the external
resource. If you do not specify a protocol, the location that is local to your BlackBerry WebWorks application
becomes the location of the resource by default.
Due to the large number of modules that the Dojo Toolkit provides and the dependencies of some of the
modules, it is suggested that you call the Dojo loader from an online resource. This also means that your
application will require an active Internet connection.
With the AMD module format, module identifiers look like paths (for example: dojox/mobile). Without AMD,
the syntax looks like object references (for example: dojox.mobile).

Using the mobile parser


It is suggested that you explicitly include dojox/mobile/parser and call parser.parse() in your
application. The mobile parser is significantly more lightweight compared to the base parser, which results in a
faster loading time. The mobile parser parses your application's pages once the DOM and initial dependencies
have been loaded, and it converts all widgets that you created declaratively to enable them to work with the
Dojo Toolkit.

Frameworks

273

Resources to help you get started


Code sample
The following code shows how to structure the modules and the AMD syntax:
require([
"dojox/mobile/parser", /* This mobile app uses
declarative programming with
fast mobile parser. (Optional) */
"dojox/mobile", /* This is a mobile app. (Required) */
"dojox/mobile/deviceTheme" /* Detects the devices OS and
formats styles accordingly.
[we can use this to automatically
detect the BlackBerry device]
(Optional) */
],
function(parser, mobile, compat)
{
parser.parse(); /* Parse the page for widgets
and instantiate them. */
});

Sample application
Visit the WebWorks-Samples repository on GitHub and check out the DojoAppDetails sample. It's a sample
application that displays the application's details by retrieving the details from the application's configuration
file (config.xml).

Packaging, testing, and debugging


Once your sample application is ready, you can package, test, and debug using the the BlackBerry WebWorks
SDK. You can run your application on a BlackBerry simulator or a device.

Further reading
Getting Started with dojox/mobile: http://dojotoolkit.org/documentation/tutorials/1.8/mobile/tweetview/
getting_started/
Modern Dojo syntax: http://dojotoolkit.org/documentation/tutorials/1.8/modern_dojo/
DOM and event handling: http://dojotoolkit.org/documentation/tutorials/1.8/events/
Frameworks

274

Dynamic content loading: http://dojotoolkit.org/reference-guide/1.8/dojox/mobile/dynamic-contentloading.html

Enyo 2.0
Overview
Enyo 2.0 is a free and open source JavaScript framework for building cross-platform web apps. You can use
Enyo 2.0 to build apps for the BlackBerry platform. If you already have an Enyo 2.0 based app, you can port it
to the BlackBerry platform.

Porting process demo using the Onyx Sampler sample app


Onyx is a UI library for the Enyo 2.0 JavaScript framework. Onyx includes a variety of commonly used widgets,
such as toolbars, text input fields, buttons, check boxes, progress bars, and so on. You can use the widgets
from the Onyx UI library to build BlackBerry WebWorks apps.
We are going to demonstrate the porting process using the Onyx Sampler sample app. If you already have an
app built with Enyo 2.0, you can follow the same instructions to port your own app by adapting the instructions
as necessary. Alternatively, you can get the Onyx Sampler sample app and use it to follow the instructions.
Porting apps built using the Enyo 2.0 framework to the BlackBerry platform involves the following activities:
Incorporate the Enyo core files and the necessary libraries with the app source files.
Build a BlackBerry WebWorks app from the app source files.
Install the BlackBerry WebWorks app on the device.
Obtain the OnyxSampler source files
1. Download the OnyxSampler app source files from the BlackBerry WebWorks Community Samples repo on
GitHub.
2. Extract the contents of the compressed file at a location of your choice.
3. From the extracted files, navigate to the following location:
\Enyo-2.0-OnyxSampler\lib\onyx\examples\
4. Copy the OnyxSampler folder to a convenient location (for example, C:\OnyxSampler).

Frameworks

275

Incorporating the Enyo core files and the necessary


libraries
The OnyxSampler folder contains the app's source code. To deploy the app, we incorporate the Enyo core files,
and other libraries that the source code refers to, in the OnyxSampler folder. One of the ways you can do this is
to use Enyo Bootplate. Enyo Bootplate contains the latest release of Enyo core files and the most common
libraries. We also use the icon file available in Enyo Bootplate. Here are the steps to accomplish all of this:
1. Download the Enyo Bootplate (bootplate-<x.x.x>.zip) from the Enyo website, where <x.x.x> denotes the
version of Enyo.
2. Extract the contents of the compressed file to a location of your choice.
3. Copy the enyo and lib folders and the icon.png file from the extracted content into the OnyxSampler folder.
4. In the OnyxSampler folder, edit the index.html file as follows:
a. Locate the index.html file and open it in any text editor.
b. To update the reference to the Enyo core files, find the <script> element with the attribute
src="../../../../enyo/enyo.js" and replace it with src="./enyo/enyo.js".
The updated <script> element appears as follows:
<script src="./enyo/enyo.js" type="text/javascript"></script>
c. To update the reference to the Onyx UI library, find the <script> element with the attribute
src="../../../onyx/package.js" and replace it with src="./lib/onyx/package.js".
The updated <script> element appears as follows:
<script src="./lib/onyx/package.js" type="text/javascript"></script>
d. To update the reference to the fittable package in the layout library, find the <script> element
with the attribute src="../../../layout/fittable/package.js" and replace it with
src="./lib/layout/fittable/package.js".
The updated <script> element appears as follows:
<script src="./lib/layout/fittable/package.js" type="text/
javascript"></script>
e. Save the file and close the text editor.
5. In the OnyxSampler folder, in the enyo subfolder, delete the minify, samples, and tools folders.

Further reading
Enyo Bootplate
Onyx UI library
Frameworks

276

Layout library

Building a BlackBerry WebWorks app package


A BlackBerry WebWorks app is packaged into a file with a .bar extension.
Building a BlackBerry WebWorks app from your source files involves the following activities:
1.
2.
3.
4.

Creating a new BlackBerry WebWorks project. For more information, see Creating a WebWorks project.
Placing your app source files in the /www folder of your new project.
Generating an unsigned .bar file for testing. For more information, see Building your app for testing.
Generating a signed .bar file containing your complete project. For more information, see Building and
signing your complete app.

To complete this task, you must have the BlackBerry 10 WebWorks SDK installed on your computer. You can
download the SDK from the Downloads page.

Construct 2
Construct 2 includes an Export Project wizard that allows you to export your project to BlackBerry 10. The
export process creates an HTML5 version of your game's project files. You can use the BlackBerry 10
WebWorks SDK to package those files into a BlackBerry 10 WebWorks app.
Before you attempt to export your Construct 2 game into a BlackBerry 10 app, you need to complete the
following steps:
Download and install the BlackBerry 10 WebWorks SDK.
Set up your computer for testing and signing by creating your BlackBerry ID token and then creating your
developer certificate.
Once you have the WebWorks SDK installed and your signing token in place, you can create a WebWorks
project, then export your Construct 2 project assets into that project.

Create a WebWorks project


Before you port your Construct 2 game, you need to create the WebWorks project which will house the
Construct 2 code. You can use either the SDK web tool or the command-line tools to create your new
WebWorks project. For this sample, we'll use the web tool.
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Click [+] beside the Projects heading in the navigation panel.
3. Enter C2Sample in the Project Name field.

Frameworks

277

4. Enter C:\TestApps in the Project Path field. This folder is the root folder for your WebWorks project,
represented by <project-root> later in this tutorial.
5. Click Save. The tool creates a pre-populated WebWorks sample project.
Leave the SDK web tool open for now. You'll return to it once you have added your Construct 2 project
assets to the WebWorks project.
6. On the command line or in a file manager, navigate to <project-root>\www folder and delete the entire
contents of the folder, including all subfolders. You can now populate your WebWorks project with the
Construct 2 content.

Export your Construct 2 project to HTML5


1. Open your game file in Construct 2.
2. Click File > Export project > HTML5 Website.
3. In the Export files to field, leave all other fields as their default values and click Next.
Note: Do not enable the Minify Script check box. Minifying your script may interfere with certain plugins.

4. On the HTML5 export options screen, select Embed Style to export the content with no margins and no
scroll bar. This format is the most suitable for a BlackBerry WebWorks app.
5. On the HTML5 export options screen, click Export.
The following window appears:

Frameworks

278

6. Copy the files from the export folder to the <project-root>\www folder in your WebWorks project.

Update your project configuration details


Before you can build your project, you need to make a few modifications to your project's configuration. Your
project configuration details are stored in the config.xml file for your project and allow you to define general
app information, such as the app name, description, start page, and home screen icon. You can also specify
the platform features and functionality that the app can access.
You can modify your project configuration either by manually modifying the config.xml file, or by modifying the
entries on the Config page in the SDK web tool, which then updates the appropriate config.xml file entries for
you. For this sample, we'll use the web tool to modify a few basic configuration settings. For information on
modifying the config.xml file directly, see Modifying your config.xml file on page 68.
To modify the project configuration details:
1. Return to the BlackBerry 10 WebWorks SDK web tool.
2. Navigate to your project and click Config.
3. Specify your own values for at least the following configuration settings.
Preference

Description

App ID

The ID of your application. The ID should be unique. You should


use a reverse DNS format for all platforms, for example,
id="com.somedomain.C2Sample".

App Name

The name of your proeject. This name identifies your app on the
device Home screen.

Frameworks

279

Preference

Description

App Description

A description of your app. The description

Author

Your name, or the name of your organization.

To learn more about the other configuration settings available, see Configuring your app preferences on
page 56.
4. Click Save. You can now test your Construct 2 app on a device or simulator.

Test and debug the app


With the Construct 2 project assets added to your WebWorks project file structure, you can launch the app on
a device or simulator for testing.
1. On your BlackBerry device or BlackBerry 10 Device Simulator, enable Development Mode.
a. On the home screen, swipe down from the top of the screen or find the Settings app on your home
screen.
b. Navigate to Settings > Security and Privacy > Development Mode.
c. Set the Development Mode toggle button to On.
d. When you are prompted, enter the password for your device or simulator, and tap OK.
2. Perform one of the following:

3.
4.
5.
6.
7.
8.
9.

Connect your device to your computer via USB.


Start your BlackBerry 10 Device Simulator.
Return to the BlackBerry 10 WebWorks SDK web tool.
Click Build.
Select Debug Mode as the build mode.
Select either Device or Simulator as the target type.
From the Install Target drop down list, select Autodetect.
Enter your device or simulator password.
If you are testing on a device, enter your keystore password, which you defined when you requested your
BlackBerry ID token. If you are testing on a simulator, a keystore password is not necessary.

Note: If you have not yet requested your BlackBerry ID token, see set up your computer for testing and
signing.
10.Click Build & Install. After creating and installing a debug token, if necessary, the tool builds, installs, and
launches the app.

Frameworks

280

Build the release version of your app


With your testing and debugging complete, you can build your completed app in release mode. When you build
your app in release mode, the SDK packages your app resources and plugins together in a .bar file, then signs
the app.
You can install the resulting signed .bar file on the BlackBerry 10 Device Simulator or on a BlackBerry 10
device, without restrictions. You can also submit it to BlackBerry World where it is reviewed, and if approved,
made available to users.
To build your app in release mode:
1. In the BlackBerry 10 WebWorks SDK web tool, navigate to your project and click Build.
2. Select Release Mode.
3. Enter your keystore password, which you defined when you requested your BlackBerry ID token.
Note: If you have not yet requested your BlackBerry ID token, see set up your computer for testing and
signing.
4. Click Build.
When the tool has finished building and signing your app, it places the signed copy of the .bar file in the
following location: <project_root>\platforms\blackberry10\build\device.

Best practices
In Construct 2, you can modify the viewport fairly easily to create games for specific BlackBerry 10 devices. For
more information on designing for different screen sizes, you can reference the screen size chart in the UI
guidelines.
BlackBerry 10 supports both WebGL and 2D Context for rendering, so you can choose which one you prefer to
use. You can also export your game for each API separately, so it can be deployed on a wider range of
operating systems.

bbUI toolkit
The bbUI toolkit is an open source JavaScript toolkit that allows you to give your BlackBerry WebWorks
applications the look and feel of a native BlackBerry application.
The bbUI toolkit was created to provide a design language for HTML5 applications using the BlackBerry
WebWorks framework. It provides common UI constructs that are found on the BlackBerry platform so that
you can create an application that follows BlackBerry specific UI guidelines and looks at home on a BlackBerry
device with very little effort.
The bbUI toolkit supports all BlackBerry platforms from BlackBerry Device Software 5.0 through to BlackBerry
7, as well as BlackBerry PlayBook OS and BlackBerry 10. In each case, the toolkit uses CSS that achieves a
similar user experience to the native applications on the platform, and tailors it to suit the capabilities of the
device.
Frameworks

281

Getting the toolkit


The bbUI.js toolkit is available through GitHub as a downloadable .zip or tar.gz file. The toolkit contains the
necessary JavaScript and CSS files which you include in your WebWorks project, as well as some samples with
their resources.
Download the bbUI.js toolkit.

Further reading
To learn more about the specific implementation details and functionality of the bbUI toolkit, refer to the bbUI
toolkit project in GitHub. This project site contains overview information, samples, and an extensive wiki that
provides in-depth documentation on how the toolkit is used.
Some useful links include:

Application structure
config.xml requirements
Toolkit initialization
Data attribute reference
bbUI screens and UI components reference

Frameworks

282

Building and Testing


Test your app on a device or a simulator. Debug using Web Inspector. Build and distribute your completed
app.
Configure, package, and test your app. Find out more about using Web Inspector to debug your app.

Setting up test targets


A test target refers to a BlackBerry device or simulator that you use to test your app. You can define one or
more targets.
Targets are created outside of your project. Any targets you create are available for use by any projects you are
working on. You can define as many targets as you have device or simulator PINs. In each case, you specify a
unique target ID and associate that ID with a specific PIN. Then, when you deploy your app to a particular
target device or simulator, you can simply refer to that target by ID.
If you attach a device over USB or launch the simulator, the tools will auto-detect those targets. You only need
to set a test target manually if you want to deploy your app over Wi-Fi or when you have multiple simulators or
devices that you want to test on.

Set up targets using the SDK web tool


To set up a test target:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. In the navigation panel, click Target Management.
3. In the Target Name field, specify a unique name for the target.
4. In the Target IP field, specify the IP address of the device or simulator. For information on how to locate the
IP address, see Find the IP address for your target on page 285.
5. In the Target Password field, specify the password for the device or simulator.
6. In the Target PIN field, specify the PIN of the device or simulator.
7. In the Target Type drop-down, specify whether the test target you've defined is a BlackBerry 10 device, or
a BlackBerry 10 Device Simulator.
8. Click Update Target List.
The target is added to the target list. You can remove or edit the values for any of your test targets at any time.

Building and Testing

283

Set up targets from the command line


Set up your simulator or device as a target
To set up your device or simulator as target:
1. On the command line, run the following command:
webworks target add <target_id> <ip-address> [ -t device | simulator]
p <password>] [--pin <device-pin>]

[-

For example, the following command defines the simulator as a target with an ID of mysim:
webworks target add mysim 192.168.180.130 -t simulator --pin FFFF9B90
Check the table below for details for each parameter.
Parameter

Description

<target_id>

A unique name for the target.

<ip-address>

The IP address of the BlackBerry device or simulator.

-t device | simulator

The target type. If not provided, the default value is device.

-p <password>

The password for the device or simulator. This argument is required


only if the device or simulator is password-protected.

--pin <device-pin>

The PIN of the BlackBerry device, which identifies that device as a


valid host for the debug token. This argument is required only if you
are creating a debug token.

Removing a target
To remove an existing target:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks target remove <target_id>

Building and Testing

284

Viewing existing targets


To view a list of existing targets:
1. On the command line, navigate to your project folder.
2. Run the following command to view your list of targets:
webworks target

Find the IP address for your target


To create a target, you need the IP address of your device or simulator. To get the IP address, follow the steps
below.
On a BlackBerry 10 device:
1.
2.
3.
4.

On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.
Navigate to Settings > About.
In the Category drop-down list, click Network.
Under the Wi-Fi heading, note the value under IPv4. This is the IP address you should be supplying when
setting up the device as a test target.
Note: To view the Wi-Fi section on the Network Settings page, you must have Wi-Fi turned on, and the
device must be connected to the Wi-Fi network.

On the BlackBerry 10 Device Simulator:


1. Start the BlackBerry 10 Device Simulator.
2. In the lower-left corner of the simulator window, note the IP address:

Building and Testing

285

Previewing your app in a browser


You can use the serve command to load your app in your default browser on your computer. To quickly
preview your layout or check basic HTML5 or JavaScript functionality, view your app on your local browser.
Note that testing in your local browser does not replace the need to test your app on a BlackBerry 10 device or
simulator. Only a device or simulator can effectively replicate the experience of a user in a real world setting.
To preview your app in your local browser:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks serve
3. In your browser, navigate to the following url:
localhost:8000/blackberry10/www

Building your app in debug mode


Building your app in debug mode will produce an unsigned version of your app, which you can then distribute
to others for testing.
You can build your app in one of two modes.
Debug mode: Debug mode should be used when you are preparing your app for testing. When you build the
app in debug mode, the command packages your resources and plugins together in a .bar file, but does not
sign it.
Debug mode also enables Web Inspector for the app, which allows you to remotely inspect the source code.
A prompt displays the URL that you can use to connect to and inspect your app. For more information on
using Web Inspector, see Debugging using Web Inspector on page 292.
Release mode: Release mode should be used at the end of the development cycle when you are preparing
your app to be submitted to BlackBerry World. When you build your app in release mode, the command
packages your resources and plugins together in a .bar file, then signs the app. For more information, see
Building and signing your completed app on page 316.

Build your project using the SDK web tool


To build your app in debug mode:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
Building and Testing

286

4. Click Build.
The tool packages your app into a .bar file, and places the unsigned copy of the .bar file in the following
location: <your_app_project_directory>\platforms\blackberry10\build\device.

Build your project from the command line


To build your app and package it as an unsigned .bar file:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks build [--debug] [-p|--params <JSON-file>] [-l|--loglevel
<level>]
All parameters are optional. Check the table below for parameter details:
Parameters

Description

--debug

Indicates that the app will be built in debug mode.


This parameter is optional; --debug is the default
build mode.

-p|--params <JSON-file>

A JSON file containing additional parameters to pass


to downstream tools.
This argument is optional.

-l|--loglevel <level>

The log level. The level may be one of error, warn,


or verbose.
This argument is optional.

Deploying your app to a simulator


You can deploy your app to a BlackBerry 10 Device Simulator using the SDK web tool or the command line.
The tool builds your app in debug mode, then installs and launches it on the simulator.
When you build the app in debug mode, the command packages your resources and plugins together in a .bar
file, but does not sign it.
Debug mode also enables Web Inspector for the app, which allows you to remotely inspect the source code. A
prompt displays the URL that you can use to connect to and inspect your app. For more information on using
Web Inspector, see Debugging using Web Inspector on page 292.
Building and Testing

287

Before you begin:


Make sure your BlackBerry 10 Device Simulator is running.
Turn on Development Mode on the simulator. Note that for security reasons, Development Mode expires
after 10 days and whenever the simulator is rebooted. For more information, see Enable Development
Mode on a device or simulator.

Deploy your project using the SDK web tool


To build your app in debug mode and deploy it to a simulator for testing:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. From the Install Target drop down list, select a target that represents a simulator.
5. Enter the device password used by your simulator.
6. Click Build & Install.
The tool packages your app into a .bar file, installs it on your simulator, and opens it.

Deploy your project from the command line


You can build and deploy your app to a BlackBerry 10 simulator using the emulate command.
The emulate command first packages your app resources into a .bar file, deploys the .bar file onto the
simulator, and automatically launches the app. If a .bar file with the same name already exists on the
simulator, the emulate command first uninstalls the existing .bar file before deploying the new .bar file. If you
choose, you can skip the build or launch steps of the process.
To build your app and launch it to a simulator:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks emulate [--devicepass <password>]
[--target <target_id> [--no-build] [--no-launch]
If successful, the emulate command launches the app on the simulator. It also places a copy of the
unsigned .bar file in the following location: <your_app_project_directory>\platforms\blackberry10\build
\simulator.
For example, the following sample will deploy the app on the target simulator with the ID of "myZ10sim". If the
app has already been deployed to myZ10sim, it uninstalls the previous version before installing the new
version.
webworks emulate --target myZ10sim
All parameters are optional. Check the table below for parameter details:
Building and Testing

288

Parameters

Description

--devicepass <password>

The simulator password. If you omit this parameter,


you will be prompted to supply the simulator
password, if necessary.

--target <target_id>

The target ID of a pre-defined target simulator. In


most cases, this parameter is unnecessary.

--no-build

Causes the command to skip the build step. The


command deploys the most recently built version of
the application.

--no-launch

Causes the command to skip the launch step. The


command deploys the app on the simulator, but does
not actually launch the app.

Deploying your app to a device


You can deploy your app to a device using the SDK web tool or the command line. The tool builds your app in
debug mode, then installs and launches it on the device.
When you build the app in debug mode, the command packages your resources and plugins together in a .bar
file, but does not sign it.
Debug mode also enables Web Inspector for the app, which allows you to remotely inspect the source code. A
prompt displays the URL that you can use to connect to and inspect your app. For more information on using
Web Inspector, see Debugging using Web Inspector on page 292.
Before you begin:
Turn on Development Mode on the test target. Note that for security reasons, Development Mode expires
after 10 days and whenever the device is rebooted. To enable the Development mode on your device,
navigate to Settings > Security and Privacy > Development Mode.
Define your device as a test target, if you intend to test on a device over a Wi-Fi network (If you are testing
on a device connected by USB, defining the device as a test target is unnecessary; the tools automatically
detect it). For more information, see Set up your simulator or device as a target on page 284.

Deploy your project using the SDK web tool


To build your app in debug mode and deploy it to a device for testing:

Building and Testing

289

1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. From the Install Target drop down list, select one of the following:
To deploy to a device connected via USB, select Autodetect.
To deploy to a device over Wi-Fi, select appropriate device target from the list.
5. Enter your device password.
6. Enter your keystore password, which you defined when you requested your BlackBerry ID token. If you have
not yet requested your BlackBerry ID token, see set up your computer for testing and signing.
7. Click Build & Install.
The tool packages your app into a .bar file, installs it on your device, and then opens it. If a .bar file with the
same name exists on the device, the SDK first uninstalls the existing .bar file before deploying the new .bar file.
If a valid debug token is not already present on the device, the tool creates and installs the debug token for you
before installing and opening the app. For more information about debug tokens, see Signing and debugging:
Frequently Asked Questions on page 16.
If you don't supply a device or keystore password, or supply an incorrect password, the SDK prompts you to
enter the correct password before continuing the deployment process.

Deploy your project from the command line


You can build and deploy your app to a BlackBerry 10 device using the run command. The target device must
be connected to your computer by USB connection or be connected to the same Wi-Fi network as your
computer.
The run command first builds your app in debug mode and packages the app and its resources into a .bar file.
It then deploys the .bar file onto the device, and automatically launches the app. If a .bar file with the same
name already exists on the device, the run command first uninstalls the existing .bar file before deploying the
new .bar file. If you choose, you can skip the build or launch steps of the process.
If you have not already created and installed a debug token, or your debug token has expired, specify the -keystorepass <keystore_pw> argument when running the run command. The command creates and
installs the debug token for you as well. For more information about debug tokens, see Signing and debugging:
Frequently Asked Questions on page 16.
To build your app and launch it to a device:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks run [--devicepass <password>]
[--target=<target_id>] [-k|--keystorepass <keystore_pw>]
[--no-build] [--no-launch]

Building and Testing

290

If successful, the run command launches the app on the device. It also places a copy of the unsigned .bar
file in the following location: <your_app_project_directory>\platforms\blackberry10\build\device.
For example, the following sample will deploy the app on the default target device, as well as create and install
a debug token, if one does not already exist on the device. If the app has already been deployed to the default
target, it uninstalls the previous version before installing the new version.
webworks run --keystorepass mypass
All parameters are optional. Check the table below for parameter details:
Parameters

Description

--devicepass <password>

The device password. If you omit this parameter, you will


be prompted to supply the device password, if necessary.

--target <target_id>

The target ID of a pre-defined target device.


If no target is provided and you have a BlackBerry 10
device that is connected to your computer via USB, the
run command automatically detects it and launches the
app on the connected device.

-k | --keystorepass <keystore_pw>

The keystore password, which you defined when you


configured your computer to sign applications. This
argument allows the run command to create and deploy
a debug token to the device on your behalf to allow your
unsigned application to run.
If you omit this parameter and you have not already
created and installed a debug token on the device you are
deploying your app on, you will be prompted to provide
the keystore password.

--no-build

Causes the command to skip the build step. The


command deploys the most recently built version of the
application. This is useful to test an application in release
mode.

--no-launch

Causes the command to skip the launch step. The


command deploys the app to the device, but does not
actually launch the app.

Building and Testing

291

Debugging using Web Inspector


Web Inspector is a built-in feature of the BlackBerry Browser that allows you to inspect and debug your
webpage source code. Web Inspector allows you to inspect web content that is displayed through the
BlackBerry Browser or in BlackBerry WebWorks applications. You can use Web Inspector to manipulate the
DOM, edit and debug JavaScript code, analyze resource requests, and audit the performance of web content
and web applications in near real-time.
You can access Web Inspector functionality using a BlackBerry device or simulator with the Google Chrome
desktop browser.

Getting Web Inspector up and running


Inspecting and debugging your webpage source code
Enabling Web Inspector
How you enable Web Inspector depends on whether you are inspecting content in a BlackBerry WebWorks app
or in the BlackBerry Browser:
In a WebWorks app, Web Inspector is enabled by default when you build your app without signing it (debug
mode). You can also enable Web Inspector for signed apps (release mode) by specifying a command-line
flag.
To use Web Inspector with the BlackBerry Browser, you must first enable it in the BlackBerry Browser
options. Enabling Web Inspector in the browser options allows you to inspect only the content that is
displayed in the BlackBerry Browser.
Once Web Inspector is enabled, the browser or app displays the IP address and port number it uses to serve
the content.

Enable Web Inspector for a BlackBerry WebWorks app


In a BlackBerry WebWorks app, Web Inspector is enabled by default for unsinged apps. Typically, during your
development cycles, you build your app without signing it so you can test it (called debug mode). You can build
your app in debug mode using the SDK web tool, or from the command line. For more information, see:
Building your app in debug mode on page 286
Deploying your app to a simulator on page 287
Deploying your app to a device on page 289
Building and Testing

292

To enable Web Inspector in a signed app, you must build your app from the command line (using webworks
build --release command), and include the --web-inspector flag in the command. See Building and
signing your completed app on page 316 for more information.
Note: You should enable Web Inspector for signed apps sparingly. Leaving the debugging port open may allow
unintentional access to your application.
When you load a Web Inspector enabled BlackBerry WebWorks application on a BlackBerry device or
simulator and run it, a dialog appears that provides the IP address and the port number required to connect
from your desktop browser.

Enabling Web Inspector for the BlackBerry Browser


1. On a BlackBerry 10 device or on the BlackBerry 10 Device Simulator, open the BlackBerry Browser.
2. In the browser, tap

> Settings > Developer Tools.


3. Set the Web Inspector switch to On. The browser displays the IP address and the port number required to
connect from your desktop browser.
4. If prompted, type your device password to complete the enabling process.
5. Click the Back button at the bottom of the display to save the new settings and return to the browser
window.
You can now open a connection to the BlackBerry Browser to remotely inspect the page that it is displaying.

Getting started with Web Inspector


Web Inspector functionality is made available using a client-server architecture. On the device (or simulator),
the BlackBerry WebWorks app or BlackBerry Browser acts as a web server and serves the webpage over HTTP
over a USB or Wi-Fi connection. Using the Google Chrome browser on your desktop, you can navigate to the IP
address and port number used by the server app and begin inspecting the code.

Launch Web Inspector to remotely inspect and modify


content
To connect to a device, verify that your computer is connected to your BlackBerry device via a USB
connection, or is communicating on the same Wi-Fi network as the BlackBerry device.
Note: Note that Web Inspector provides a USB IP address (required if you intend to use Web Inspector over
a USB connection) only if your device is already connected via a USB connection when Web Inspector is
enabled.
To connect to a simulator, verify that the simulator is running.
Building and Testing

293

Verify that your computer has the Google Chrome desktop browser installed.
Verify that development mode is enabled on your device or simulator.
Once you have enabled Web Inspector in your BlackBerry WebWorks app or in the BlackBerry Browser, you
can remotely connect to your BlackBerry device or simulator to inspect and modify the content.
1. On your computer, open Google Chrome.
2. In the address bar, type the IP address of the BlackBerry device or simulator, and specify the port number
used by the app serving the content. The port number is displayed when you open a BlackBerry WebWorks
app that is Web Inspector enabled, or when you first enable Web Inspector in the BlackBerry Browser.
Typically, port numbers are assigned starting at 1337, and increase sequentially for each additional
WebWorks app or browser tab that you choose to inspect. For example:
http://<IP_address>:<port_number>
A list of one or more links is displayed in your browser, representing the webpage currently displayed in
each of the tabs open in the BlackBerry Browser.
3. Click any of the available links to view the content in Web Inspector.

Finding the IP address used to connect to the BlackBerry device


On a BlackBerry 10 device:
1.
2.
3.
4.

On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.
Navigate to Settings > About.
In the Category drop-down list, click Network.
Under the Wi-Fi heading, note the value under IPv4. This is the IP address you should be supplying when
setting up the device as a test target.
Note: To view the Wi-Fi section on the Network Settings page, you must have Wi-Fi turned on, and the
device must be connected to the Wi-Fi network.

On the BlackBerry 10 Device Simulator:


1. Start the BlackBerry 10 Device Simulator.

Building and Testing

294

2. In the lower-left corner of the simulator window, note the IP address:

Web Inspector panels


Web Inspector contains a number of panels, each of which provides different functionality that you can use to
help you to improve the appearance and performance of your webpage. You can display a panel by clicking the
icons in the toolbar at the top of the Web Inspector window.
Web Inspector includes the following panels:
Panel

Icon

Description

Elements

The Elements panel allows you to inspect the DOM of the current webpage or your
BlackBerry WebWorks app, and adjust settings for attributes and CSS properties.
Changes you make are reflected in the content.

Resources

The Resources panel displays information about all the resources that are used by
the current webpage or in your BlackBerry WebWorks app.

Network

The Network panel displays information about each HTTP request made as
resources are requested, received, and displayed in the BlackBerry Browser or in
your BlackBerry WebWorks app.

Sources

The Sources panel allows you to debug JavaScript code. You can set breakpoints
and step through your code to locate and correct issues.

Building and Testing

295

Panel

Icon

Description

Timeline

The Timeline panel allows you to view how much time it takes for the browser to
load and render the webpage and its resources.

Profiles

The Profiles panel allows you to examine how your JavaScript code is utilizing
memory. With the Profiles panel, you can determine where programmatic
inefficiencies exist.

Audits

The Audits panel allows you to examine the network utilization and webpage
performance and suggests areas where performance can be improved.

Console

The Console panel provides a command-line driven utility that allows you to debug
JavaScript errors or HTML parsing errors.

Optimizing layout and style


As you try to achieve an optimal layout for small screens such as those on BlackBerry smartphones, the
Elements panel can be a very useful tool. The Elements panel allows you to view the DOM and trace style
values for an element to see where values are applied, how they have been inherited, and where style values
have been superseded. You can adjust style settings to tweak the appearance of the webpage components to
achieve the desired result. The changes you make to the webpage are applied in near real time in the
BlackBerry Browser, so you can see how your changes affect the appearance of the content. Once you achieve
the results you want, you can propagate the updated values into the source file.

The Elements panel


You can click the Elements icon on the toolbar to display the Elements panel.

Building and Testing

296

The Elements panel is divided into two sections. On the left is the document pane, which displays the DOM
tree of the HTML source document. Each element is displayed as a separate node. You can expand the nodes
of the DOM tree to view the children of a container element. The document pane of the Elements panel is a
good tool to use to view the source of a page; because the panel displays the page as a tree, the document is
easy to view and to navigate, even when the original webpage is minified or poorly formatted and difficult to
read. Within the document pane, you can edit aspects of the DOM, such as attribute values or text.
On the right is a set of collapsible panes which display various pieces of information related to the element
currently selected in the document pane. Some of these panes, such as the Computed Style pane and the
Event Listeners pane, are informative; you use them simply to track information about the element. Other
panes are editable, and allow you to change the styles or properties associated with the selected element. You
can edit content in the following panes:
Styles: The Styles pane is divided into sections which show each matched CSS rule, and the associated
style declarations. It also displays style values that have been inherited. Inherited values that have been
overwritten by other style declarations are displayed with strikethough text.
Metrics: The Metrics pane provides a visual representation of the box model, which you can edit to
optimize the layout of a container element on the screen. The box model refers to the amount of space a
container element occupies in a rendered webpage. You can apply styles such as margins, borders, and
padding to an element to adjust the size of the content block and improve the page layout.
Properties: The Properties pane allows you to view the page as it is viewed by JavaScript code, as a
collection of DOM objects with associated property values. Although some of the property values are
editable, in most cases, it is easier to edit style values in the Styles pane.

Building and Testing

297

Inspect and modify element styles


1. Click the Elements icon on the toolbar to display the Elements panel.
2. In the document pane, locate and select the element for which you want to alter a style.
3. In the data sidebar, expand the Styles pane to display the style declarations applied to the selected
element.
4. Perform any of the following actions:
To change the value for a style declaration, double-click the value in the Styles pane to make the value
editable, and type the new value. You can use the Tab key to cycle through the declarations within a
selector to modify more than one value.
To disable a style declaration, deselect the adjacent check box.
To add a new style declaration for a selector, double-click the white space below the last style
declaration, and type the new declaration.
To modify the selector, double-click the selector, and type the new selector value.
5. When you achieve the desired results, propagate the changes to the source document.

Inspect and modify the DOM


1. Click the Elements icon on the toolbar to display the Elements panel.
2. In the document pane, navigate to the node that you want to view or change.
3. Perform any of the following actions:
To change the value of an attribute, double-click the value in the document pane to make the value
editable and type the new value. You can use the Tab key to cycle through each of the element's
attributes to modify more than one value.
To change an attribute name, double-click the attribute name and type the new value.
4. When you achieve the desired results, propagate the changes to the source document.

Modify the box model for an element


1. Click the Elements icon on the toolbar to display the Elements panel.
2. In the Elements panel, expand the Metrics pane to display the box model associated with the selected
element.
3. Click any of the top, bottom, left, or right values and type the new value. The changed value is propagated
to the associated style declaration in the Styles pane.
4. When you achieve the desired results, propagate the changes to the source document.

Analyzing page resources


The Resources panel allows you to view the complete set of resources that are loaded by a web page. You can
view and interact with resources such as CSS and JavaScript, check image content and information, and view
which font sets are used on the page. In addition, the Resources panel allows you to view and interact with the
client-side resources created by your page, including cookies, databases, storage objects, and application
cache, if they exist.
Building and Testing

298

The Resources panel


You can click the Resources icon on the toolbar to display the Resources panel.

The Resources panel displays a complete list of the resources that the WebKit engine must request and load to
render the webpage, as well as any client-side resources created and used by the web page. You can also use
the Resources panel to view the content of any resource file. Resources are organized in the panel into the
following categories:
Frames: Contains the resources for each frame displayed in the content, including images, fonts, scripts,
stylesheets, and other content resources, such as embedded video or Flash files. Subframes within the
main window are displayed as subfolders beneath the main Frames folder.
Databases: Contains all the database tables that are associated with your content or app.
Local Storage: Contains all Local Storage objects, that is, storage objects which persist after a browser
session has ended.
Session Storage: Contains all Session Storage objects, that is, storage objects which are only valid for the
current browser session.
Cookies: Contains all the cookies associated with the webpage or app.
Application Cache: Contains the resources included in the manifest of an offline web application.

View resource content


1. Click the Resources icon on the toolbar to display the Resources panel.

Building and Testing

299

2. In the list in the left pane of the Resources panel, double-click a category to show the resources and
subgroups. Continue to drill down until you locate the resource you are interested in viewing.
3. Double-click the resource in the left pane. The right pane displays the contents of that resource. For
example, selecting an image resource displays the image itself, as well as the file size and URL of the image
file. Selecting a script or style sheet displays the content of that script or style sheet.

View resource network information


You can quickly see additional information about a specific resource by viewing the resource in the Network
panel, which displays information such as file size and transfer rate information.
1. In the list in the left pane of the Resources panel, double-click a category to show the resources and
subgroups. Continue to drill down until you locate the resource you are interested in.
2. Right-click the resource and click Reveal in Network Panel. Web Inspector opens the Network panel and
briefly highlights the selected resource.

Analyzing network usage


The Network panel allows you to determine the network efficiency of your content. The panel displays
information about each HTTP request made as the browser engine requests and downloads resources.

The Network panel


You can click the Network icon in the toolbar to display the Network panel. Initially, the panel displays no
information; you must reload the content on the device or simulator to allow Web Inspector to track the HTTP
requests. When loading is complete, the Network panel displays a table similar to the following:

Building and Testing

300

By default, the table lists each of the requested resources in the order in which they were requested, and
charts the network activity as a waterfall timeline, with resources color-coded by type.
The waterfall timeline plots resources by the total time required to load the resource, from the initial request to
the completion of the download. The pale segment of the resource bar in the chart represents the total latency,
that is, the time the browser engine must wait from the moment it initially makes the request to the moment it
receives the first packet of data for the resource. Two vertical lines on the chart provide mark key page load
milestones:
The blue line indicates the time at which parsing of the content is complete and the DOMContent event
fires.
The red line indicates the time at which all the resources have been loaded and the load event fires.
You can customize how the content is displayed in the Network panel; resources can be filtered based on type
or sorted by any of the table headings, and the chart can be reformatted to highlight different time measures.

Apply a filter to display a specific resource type


By default, the Networks panel displays all resource requests in the table. The status bar at the bottom of the
panel contains buttons that allow you to filter which resources are displayed based on the resource type.
1. Click the Network icon on the toolbar to display the Network panel.
2. If you have not already done so, on the device or simulator, reload the page to allow Web Inspector to track
and record network activity.
3. In the status bar at the bottom of the Network panel, choose the type of resource you want to display.
Building and Testing

301

Change which time measure is displayed


By default, when you measure the network activity, Web Inspector charts the network activity in a waterfall
timeline. You can reformat the chart to highlight different time measures.
1. Click the Network icon on the toolbar to display the Network panel.
2. If you have not already done so, on the device or simulator, reload the page to allow Web Inspector to track
and record network activity.
3. In the drop-down list above the chart, select one of the following load time measures:

Timeline: Displays the network activity in a waterfall timeline.


Start time: Highlights the time at which each resource was requested.
Response time: Highlights the time at which the resource is initially received.
End time: Highlights the time at which the resource is completely loaded.
Duration: Displays the total length of time it takes to load the resource.
Latency: Displays the amount of delay between the start time value and the response time value.

Reorder the list of resources


1. Click the Networks icon on the toolbar to display the Networks panel.
2. If you have not already done so, on the device or simulator, reload the page to allow Web Inspector to track
and record network activity.
3. Click a column heading to reorder the list based on the column data

Debugging scripts
The Sources panel allows you to debug the JavaScript code used by your webpage. By allowing you to set
breakpoints and to step through your code, the Web Inspector can help to locate and correct problems within
your code. When you determine that the script is functioning as intended, you can copy the changes back into
the source file.
To use the Sources panel, you must first enable debugging. Web Inspector prompts you to enable debugging
when you first view the Sources panel; you can choose to enable debugging for just the current session, or to
always enable debugging.

The Sources panel


You can click the Sources icon in the toolbar to display the Sources panel. If you have not already enabled
debugging, the Web Inspector prompts you to do so.

Building and Testing

302

The Sources panel is divided into two sections. On the left is the document pane, which allows you to view and
debug JavaScript. On the right is a set of collapsible panes which display information related to the displayed
script.
A toolbar at the top of the Sources panel allows you to choose the script file you want to inspect and to cycle
between open scripts. It also provides a set of controls that allow you to step through the script displayed in the
document pane.

Set and use breakpoints


1. Click the Sources icon on the toolbar to display the Sources panel.
2. In the line gutter of the document pane, click the line at which you want to set a breakpoint. A breakpoint
marker appears in the line gutter, and the new breakpoint is added to the Breakpoints pane, identified by
the script filename and line number. The execution of the script pauses at the specified breakpoint.
3. Perform any of the following actions:
To continue the execution of the script beyond the current breakpoint, click the Continue button in the
Sources panel toolbar.
To display the line of code associated with breakpoint in the documents pane, click the breakpoint entry
in the Breakpoints pane. The document pane displays and highlights the associated line.
To disable a single breakpoint without removing it, in the Breakpoints pane, uncheck the break point.
The execution of the script no longer pauses at the disabled breakpoint.
To deactivate or activate all the breakpoints listed in the Breakpoints pane without removing them,
toggle the breakpoint activation switch at the right side of the Scripts panel toolbar.
Building and Testing

303

To remove a breakpoint, locate and click the breakpoint marker in the line gutter of the document pane.
The marker no longer appears in the line gutter, and the breakpoint is removed from the Breakpoints
pane.

Pause script execution


You can pause the script at any time to get a snapshot of the call stack and variable values.
1. Click the Sources icon on the toolbar to display the Sources panel.
2. In the Sources panel toolbar, click the Pause button.
When the script pauses, the last line of JavaScript to be executed is highlighted. The call stack and the current
in-scope variable values appear in the appropriate panes at the right of the panel.

Pause script execution on exceptions


You can configure Web Inspector to pause the execution of scripts whenever exceptions are thrown. A tri-state
toggle allows you to specify whether to pause for all exceptions, only for uncaught exceptions, or to not pause
for any exceptions.
1. Click the Sources icon on the toolbar to display the Sources panel.
2. Use the Exceptions button in the status bar at the bottom of the Web Inspector window to choose one of
the following behaviors:
To pause on all exceptions, click the Exceptions button until the icon turns blue.
To pause only on uncaught exceptions, click the Exceptions button until the icon turns red.
To not pause on any exceptions, click the Exceptions button until the icon turns gray.

Analyzing load, execution, and rendering times


You can use the Timelines panel to analyze the time it takes to load and render your webpage.

The Timeline panel


Click the Timeline icon in the toolbar to display the Timeline panel. Initially, the panel displays no information;
you must click Record in the status bar to record the browser engine activity.
Web Inspector adds data to the Timeline panel when it records browser engine activity.

Building and Testing

304

All browser engine activity pauses when the device or simulator screen is locked, or the BlackBerry Browser or
BlackBerry WebWorks application that you are inspecting is minimized.To record any activity, the BlackBerry
Browser or BlackBerry WebWorks application must be the active application, and the device or simulator
screen must not be locked.
The Timeline panel is divided into two panes.
In the top pane, the Timeline panel allows you select which timeline view you want to display. You can choose
three views:
Events: Displays the time it takes for the browser engine to complete each of the events required to
completely load the content.
Frames: Displays the browser engine activity for each screen refresh.
Memory: Displays memory consumption over time.
In the lower pane, the Timeline panel displays a waterfall timeline for the timespan that was selected in the top
pane. The data in the timeline is determined by which mode you select in the top pane of the Timelines panel.

Record browser engine activity


1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. In the status bar at the bottom of the Timeline panel, click
to begin recording browser engine activity.
Building and Testing

305

3. To stop recording browser engine activity, click


.

Constrain the display to a specific time span


You can constrain the time span shown in the timeline. In the top pane of the Timeline panel, the portion of
time displayed in timeline in the lower pane is represented with a white background. Two grey slider handles at
the top left and right edges of this white background allow you to increase or decrease the timespan that
appears in the timeline.

1. On the toolbar, click the Timeline icon on the toolbar to display the Timeline panel.
2. If necessary, record the browser engine activity to generate timeline data.
3. In the top pane of the Timeline panel, click and drag a grey slider handle to increase or decrease the time
span.

Filter which events are displayed


Web Inspector organizes events by four types: loading (blue), scripting (yellow), rendering (purple), and
painting (green) events. By default, the Timeline panel displays all event types in the table. The status bar at
the bottom of the panel contains check boxes that allow you to show and hide events based on type.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. If necessary, record the browser engine activity to generate timeline data.
3. In the status bar at the bottom of the Timeline panel, deselect the event types you want to remove from the
timeline.

Analyze records
The Records pane displays a detailed timeline of events based on the view you have selected. Events are listed
chronologically in the left panel and displayed graphically in the main panel.
Hover over the record you wish to inspect to display a tooltip that lists important information about the event
such as duration or stack traces for rendering and scripting events.

Building and Testing

306

Hover over a paint record to see the affected region of the screen by overlaying the area with a transparent
blue rectangle.

Building and Testing

307

Building and Testing

308

Nest asynchronous events


Web Inspector automatically nests synchronous events under their initial event. You can expand and collapse
the events by clicking the arrow beside the initial event. You can also nest asynchronous events using the Glue
asynchronous events to causes button.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. If necessary, record the browser engine activity to generate timeline data.
3. In the status bar at the bottom of the Timeline, click Glue asynchronous events to causes
(

) to nest asynchronous events. Click the button again to turn nesting off.

Save and Load Timeline Data


You can revisit past recordings by saving and loading your sessions in the Timeline panel. Timeline data is
stored in .json format.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. Right-click anywhere in the panel. Select Save Timeline data to save your recording or select Load
Timeline data to load a past recording.

Analyzing memory usage and processing demands


The Profiles panel allows you to analyze the memory usage and processing demands of your content. You can
use the Profiles panel to create a performance profile for your JavaScript and CSS files.
For JavaScript files, Web Inspector examines and reports on the CPU usage for each function. You can view
the CPU usage for a particular function, as well as the number of times that function was called.
For CSS files, Web Inspector examines the processing demands for each selector. Web Inspector records
the amount of time it took to search for matches for a particular selector, as well as the total number of
matches for that selector.
To use the Profiles panel, you must first enable profiling. Web Inspector prompts you to enable profiling when
you first view the Profiles panel; you can choose to enable profiling for just the current session, or to always
enable profiling.

The Profiles panel


You can click the Profiles icon in the toolbar to display the Profiles panel. If you have not already enabled
profiling, Web Inspector prompts you to do so.

Building and Testing

309

Profile the memory usage of your scripts


1. Click the Profiles icon on the toolbar to display the Profiles panel.
2. On the Profiles panel, select Collect JavaScript CPU Profile.
3. To start profiling your memory usage, click Start. The button turns red as the Web Inspector is recording
the memory usage.
4. To stop recording, click Stop. When you stop recording, the new profile is added under the CPU Profiles
section in the left pane, and the profile's contents are displayed in the right pane:

Building and Testing

310

The profile results indicate the amount of time the browser engine spent executing each function during the
recording process, as well as the number of times each function was called. An excessive amount of time
spent in any one function can indicate that there is an issue.
5. To sort the data, perform any of the following actions:
To sort the data by values in any column, double-click the column heading.
To display calls based on greatest impact on all exceptions or where they occurred in the call stack, in
the status bar at the bottom of the panel, toggle between Heavy (Bottom Up) and Tree (Top down).
To specify whether values are presented as a time value or as a percentage of the total CPU usage
required to process all the functions, toggle the percent button
(
) on or off.
To view a single function, select the call in the table and click the focus button
(
).
To exclude a single function from the data, select the function in the table and click the exclude button
(
).
Building and Testing

311

To reload the original profile after focusing on or excluding a function, click the reload button
(
).

Profile the performance of your CSS selectors


1. Click the Profiles icon on the toolbar to display the Profiles panel.
2. On the Profiles panel, select Collect CSS Selector Profile.
3. To start profiling your memory usage, click Start. The button turns red as the Web Inspector is recording
the memory usage.
4. To stop recording, click Stop. When you stop recording, the new profile is added under the CSS Selector
Profiles section in the left pane, and the profile's contents are displayed in the right pane:

The profile results indicate the amount of time the browser engine spent matching each selector in the
associated stylesheets, as well as the total number of times the browser engine found a match for the
selector.
5. To specify whether the value of the Total column is presented as a time value or as a percentage of the total
time required to process the CSS, toggle the percent button
(
) on or off.
Building and Testing

312

Auditing your webpage


Web Inspector can audit your webpage for inefficiencies and, based on a set of best practices for web design,
suggest changes you can make that can help improve network utilization and performance. The Audits panel
allows you to run an audit, and provides a list of perceived inefficiencies in your webpage design. For example,
Web Inspector can analyze your resources and determine where you might consider combining script files or
style sheets. The Audits panel can also inform you where you have needlessly downloaded styles that are not
used, specify resources for which you have set no cache control directives, and suggest other optimizations.
The Audits panel can be especially helpful when you design pages for mobile browsers. On mobile browsers,
network latency extends download times, and constrained processing power tends to increase rendering time
and slow webpage performance. As a result, eliminating inefficiencies in your webpage design can have an
significant positive impact.

The Audits panel


You can click the Audits icon in the toolbar to display the Audits panel.

The Audits panel provides a few options; you can choose to audit network utilization, page performance, or
both. You can also choose to run the audit against the static page, or reload the page and run the audit as the
page loads.
Once you have run an audit, Web Inspector adds the report to the list at the left of the panel and displays the
results in the main pane. The audit results suggest improvements you can make to your webpage to increase
efficiencies.
Building and Testing

313

Using the Console


The console in Web Inspector lets you access and modify the DOM and JavaScript of your web application. Its
methods are defined by the Console and Command Line APIs.

Open the Console


You can access the console through the Console panel or as a split-screen view in the other panels.
To open the Console panel, click the Console icon in the top toolbar.
To open the split-screen Console view in another panel, click
in the bottom toolbar.

Use the Console to inspect DOM elements


The console in Web Inspector lets you inspect DOM elements and objects. Use the inspect() function to
open and select the specified element or object in either the Elements panel or Profiles panel respectively.
1. Open the Elements panel and click the Show/hide Console split-view button
(
) in the bottom toolbar.
2. Select the element you want to inspect using $(selector).
Building and Testing

314

3. Pass the last evaluated expression property ($_) to the inspect() function.

To learn more about the Console, and view the Console and Command Line API reference guides, visit Chrome
Developer Tools Guide.

Testing and debugging apps in the work space


If you develop enterprise apps, you can test your apps in the work space of a BlackBerry 10 device that is
running BlackBerry 10 OS version 10.2 or later. In the development environment that you use, set your launch
configuration to run or debug on a device, and switch to the work space before you deploy the app.
There are a few considerations when you test apps in the work space:
You must be running BlackBerry 10 OS version 10.2 or later on your device.
If your device is activated with BlackBerry Enterprise Service 10 (BES10):
The "Restrict Development Mode" IT policy rule must be set to No.
The "Development Mode Access to Work Space" IT policy rule must be set to Allow.
Note: The "Development Mode Access to Work Space" IT policy is supported only on BlackBerry
Enterprise Service 10 version 10.1.3 or later.
If the "Development Mode Access to Work Space" IT policy rule is disabled, apps that you previously
tested in the work space are removed.
Building and Testing

315

You can overwrite an app that your administrator pushes, but if the "Development Mode Access to Work
Space" IT policy rule is disabled, your app is removed and isnt reinstalled.
If your device is activated with BlackBerry Enterprise Service 12 (BES12):
The "Restrict development mode" IT policy rule must not be selected.
The "Allow development mode access to work space" IT policy rule must be selected.
If the "Allow development mode access to work space" IT policy rule is disabled, apps that you
previously tested in the work space are removed.
You can overwrite an app that your administrator pushes, but if the "Allow development mode access to
work space" IT policy rule is disabled, your app is removed and isnt reinstalled.

Using Web Inspector in the work space


You can use Web Inspector to debug apps in the work space.
The following information applies to debugging apps in the personal space and the work space:
When you package your app, set the debug flag (-d). For more information, see Enabling Web Inspector on
page 292.
Enable development mode on your device.
You can deploy your app to your device using a USB cable or over Wi-Fi.
When you debug apps in the work space, you must connect to your device using a Wi-Fi or VPN connection.
You can use a Wi-Fi profile that was pushed to your device by the BlackBerry Enterprise Server so that the
network is recognized as a work network. You cannot use a Wi-Fi profile that was added manually to debug
an app in the work space. You can find the Wi-Fi IP address under Settings > About > Network.
Alternatively, you can log in from a wireless network or from a personal or public Wi-Fi network if you use a
VPN that was pushed to your device by the BlackBerry Enterprise Server. You need to use the VPN IP
address. You can find the VPN IP address under Settings > About > Network.

Building and signing your completed app


When your development and testing are complete, you can build your completed app in release mode. When
you build your app in release mode, the SDK packages your app resources and plugins together in a .bar file,
then signs the app.
You can install the resulting signed .bar file on the BlackBerry 10 Device Simulator or on a BlackBerry 10
device, without restrictions. You can also submit it to BlackBerry World where it is reviewed, and if approved,
made available to users.
Note: Although you can build your app in release mode at any time, even if you just intend to test it, be aware
that with each release build, you must increase the version number of your app. If you are still in the
development and testing phase and your app is not yet complete, you should build the app in debug mode
instead. For more information about building your app in debug mode, see Building your app in debug mode on
page 286.
Building and Testing

316

Before you begin:


Set up your computer for signing. For more information, see Setting up your computer for debugging and
signing on page 14.

Build your project using the SDK web tool


To build your app in release mode:
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Release Mode.
4. Click Build.
When the tool has finished building and signing your app, it places the signed copy of the .bar file in the
following location: <your_app_project_directory>\platforms\blackberry10\build\device.

Build your project from the command line


To build your app in release mode, you include the --release switch in your build command.
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks build --release [-k|--keystorepass <keystore_pw>]
[-b|--buildId <number>] [-d|--web-inspector ]
[-p|--params <JSON-file>]
Once the tool has finished running the command, it places a signed copy of the .bar file in the following
location: <your_app_project_directory>\platforms\blackberry10\build\device.
For example, the following command builds version 3 of the app, then packages it in a .bar file, and signs it
using the keystore password provided:
webworks build --release --keystorepass mypass --buildId 3
Check the table below for parameter details:
Parameters

Description

--release

Required. Indicates that the app is built in release


mode.

Building and Testing

317

Parameters

Description

-k, --keystorepass <keystore_pw>

Required. The keystore password, which is used to


sign your app. You define this password when you
configure your computer to sign applications.

-b, --buildId <version_num>

Optional. The build version number of your


application. This value is appended to the app version
value that you specify in the web tool, or using the
<widget> on page 106 element of the config.xml. The
build version should be a whole number. Typically,
this number should be incremented from the previous
signed version.
For example, if you specify an app version of 1.2.0,
and a build version of 3, the complete build version for
the app will be 1.2.0.3.
Note: The --buildId option is only valid when the
--release switch is specified.

-d, --web-inspector

Optional. When included, indicates that Web


Inspector is enabled in the packaged app.

-p, --params <JSON-file>

Optional. A JSON file containing additional


parameters to pass to downstream tools, such as
blackberry-signer.
If you use the BlackBerry 10 WebWorks SDK behind a
firewall, you might have to specify the proxy settings
so that you are able to successfully sign your app. You
can include a params.json file, which is stored in.
You specify the proxy parameters in JSON format, as
in the following example:
{

"blackberry-signer": {
"-proxyhost": "host",
"-proxyport": "port",
"-proxyusername": "user
name",
"-proxypassword": "password"
}
}

Building and Testing

318

Parameters

Description
When you execute the build command and include
the --params params.json, the proxy settings
specified in the file are passed to the blackberrysigner command, enabling the command to
communicate with the BlackBerry Signing Authority
to sign your app.

Deploy your signed project from the command line


You can build and deploy your app to a BlackBerry 10 device using the run command and specifying the -release parameter. The target device must be connected to your computer by USB connection or be
connected to the same Wi-Fi network as your computer.
When you run this command with the --release parameter, the command builds your app, packages the
app and its resources into a .bar file, then signs it. It then installs the signed .bar file onto the device, and
automatically opens the app. If a .bar file with the same name exists on the device, the run command first
uninstalls the existing .bar file before deploying the new .bar file. If you choose, you can skip the build or
launch steps of the process.
To build and sign your app and open it on a device:
1. On the command line, navigate to your project folder.
2. Run the following command:
webworks run --release [-k|--keystorepass <keystore_pw>]
[-b|--buildId <number>] [-d|--web-inspector ]
[-p|--params <JSON-file>]
If successful, the run command installs and opens the app on the device. It also places a copy of the
signed .bar file in the following location: <your_app_project_directory>\platforms\blackberry10\build
\device.
For example, the following sample builds version 0.3 of the app, then packages it in a .bar file, signs it using the
keystore password provided, and installs and opens the app on the default target device. If the app exists on
the default target, the command uninstalls the previous version before installing the new version.
webworks run --release --keystorepass mypass --buildId 3
Check the table below for parameter details:

Building and Testing

319

Parameters

Description

--release

Required. Indicates that the app is built in release


mode.

-k, --keystorepass <keystore_pw>

Required. The keystore password, which is used to


sign your app. You define this password when you
configure your computer to sign applications.

-b, --buildId <version_num>

Optional. The build version number of your


application. This value is appended to the app version
value that you specify in the web tool, or using the
<widget> on page 106 element of the config.xml. The
build version should be a whole number. Typically,
this number should be incremented from the previous
signed version.
For example, if you specify an app version of 1.2.0,
and a build version of 3, the complete build version for
the app will be 1.2.0.3.
Note: The --buildId option is only valid when the
--release switch is specified.

-d, --web-inspector

When included, enables Web Inspector in the


packaged app.

-p, --params <JSON-file>

Optional. A JSON file containing additional


parameters to pass to downstream tools, such as
blackberry-signer.
If you use the BlackBerry 10 WebWorks SDK behind a
firewall, you might have to specify the proxy settings
so that you are able to successfully sign your app. You
can include a params.json file, which is stored in.
You specify the proxy parameters in JSON format, as
in the following example:
{

"blackberry-signer": {
"-proxyhost": "host",
"-proxyport": "port",
"-proxyusername": "user

Building and Testing

320

Parameters

Description
name",
}

"-proxypassword": "password"

When you execute the build command and include


the --params params.json, the proxy settings
specified in the file are passed to the blackberrysigner command, enabling the command to
communicate with the BlackBerry Signing Authority
to sign your app.

Distributing your app


The main way to distribute your BlackBerry WebWorks app to BlackBerry devices is via the BlackBerry World
storefront. However, there are other ways to distribute apps, depending on the OS that the app is targeting.

BlackBerry World storefront


This method installs your app using BlackBerry World on a smartphone, BlackBerry PlayBook, or BlackBerry
10 device. To be approved for distribution through BlackBerry World, apps must be signed to verify the
authorship of your app to users and to the OS.
You use the .bar file that is produced by the BlackBerry WebWorks Packager.
For more information about the BlackBerry World storefront, see the following resources:
BlackBerry World Vendor Support
BlackBerry World storefront site
For more information about signing apps, see Setting up your computer for debugging and signing on page 14.

Building and Testing

321

Building and Testing

322

Best Practices
Learn about the best practices for developing web apps for the BlackBerry device.
When you follow best practices, you can improve the performance of your app and make it easier to debug and
maintain.

UI guidelines
Personally identifiable information
Note: The following best practices are based on the BlackBerry Guidelines for Personally Identifiable
Information, published on February 7, 2014. For information about what PII is, and what your responsibilities
as an app developer are, see the Guidelines.
A primary privacy concern for most mobile customers is what happens to information that personally identifies
them, commonly called personally identifiable information (PII). When handling customers PII, BlackBerry
recommends app developers use the following best practices:
Use the principle of least permissions. Only collect, use, or disclose personal information for purposes that
are reasonable. Likewise, only request the permissions your app reasonably needs to perform its intended
functions. Do not request or require permissions that your app can function without, and always explain why
you are seeking the permissions requested.
Consider the impact of third-party code. If your app includes third-party code, understand how it works,
the functionality it provides, and if or how it handles customers information. Ensure that appropriate
contracts are in place with any third-party service that you use. Consider how SDKs and third-party add-ins
affect your app. For example, a third-party ad service might access and use PII that your app would not
otherwise access.
Get consent and implement a privacy policy. If your app processes PII, you should have a publicly available
privacy policy that complies with applicable law and explains what you do with information you gather.
Ensure that your privacy policy is easily available and understandable to users. If you use unexpected practices
or process sensitive information, be explicit about your practices and the reasons for them when obtaining
consent from users.
Be accountable. Understand where your app is being sold and what legal privacy protection is in place for
users in those locations. Ensure your app and its policies comply with all applicable laws. Be aware that
data collected about minors or children can require additional special protection depending on the particular
jurisdiction in which the app is sold.
Best Practices

323

Be transparent. Build trust with your customers by explaining clearly and simply how your app works, what
data it collects, and what it does with that data. The explanation should include information about whether
the information is sent off the device to remote servers. Consider options to explain these aspects, such as a
separate link to how the app works or a special notice page in the app.
Secure your customers data. If the app collects, accesses, stores, or sends data to an external server,
always safeguard that data. Use encryption at all layers, including encrypting the data stored on the phone,
and use a secure transport layer for off device access such as SSL or TLS. Limit access to all user data to those
who have a legitimate business purpose for accessing the data
Empower your customers to control their information. Give users additional choices and controls,
including the use of a settings menu or privacy-sensitive default settings. For example, if you are collecting
additional PII that is not strictly necessary for the app, make it clear to the customer that providing it is optional
and allow users to opt out. Consider providing a paid version that doesnt include ad packages.

HTML best practices


In this section, we'll provide some tips and best practices for your HTML documents.

Start with a template


This may seem like common knowledge, but creating and using a template for your HTML document can save
you time and improve the development process. There's no sense re-inventing the wheel, so once you set up a
structure for a basic web page, save it and reuse it. Your HTML template should include the key elements and
tags that you typically find in a web page.
Here's an example of a typical HTML template for a BlackBerry WebWorks application:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,
user-scalable=no">
<title>Heading</title>
<link href="favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="css/app.css">
<style type="text/css">
</style>
</head>
<body>
<h1>Heading</h1>
<p>The quick brown fox jumps over the lazy dog.</p>
<script src="js/app.js"></script>
</body>
</html>

Best Practices

324

In this template, there are a few things to note:


The application is set to full screen by using the following values in the viewport meta tag: initialscale=1.0, minimum-scale=1.0, maximum-scale=1.0
Zooming functionality is turned off by setting user-scalable=no
For performance improvements, the JavaScript is placed near the bottom of the HTML document. See Put
scripts at the bottom on page 329 for more details.

Specify a document type


The DOCTYPE declaration tells the browser what version of HTML the page is written in, which informs the
browser how to render the content. When you validate your web page, the HTML validator uses the DOCTYPE
to determine which HTML version to validate against; the validator checks your code against the applicable
standards and reports which portions are compliant and non-compliant.

Why should I specify it?


If you don't include a document type declaration, your content will not be rendered consistently across
browsers. Each browser might render your content differently. By including a DOCTYPE, browsers are required
to process your content according to the standards for that document type.

Which DOCTYPE should I use?


HTML5 is the current standard, which you should be using in your BlackBerry applications. HTML5 includes
great new features and functionality that you can leverage in your application.
<!DOCTYPE html>
For BlackBerry devices running BlackBerry 6 and earlier, the browser doesn't support all of the HTML5
features, so you might choose to use the HTML 4.01 Strict or XHTML 1.0 Strict document types instead of the
HTML5 document type.

Design your content for offline use


With mobile devices, there's an increasing demand for users to access their applications at any time, even
when they are offline. For your web application, you can take advantage of the W3C HTML5 application cache
feature to:
Make your web application available offline
Increase the speed of your application by caching resources locally
Reduce load times and data usage by only downloading updated or changed resources
The application cache (also known as AppCache), allows you to specify the files to cache and make available
even when the user is offline.

Best Practices

325

Create a manifest
To use the AppCache feature, your web application must provide a "manifest" to the browser that lists all the
resources that it needs so that the application can function when offline. After the first time a web page is
loaded, the resources specified in the manifest file are obtained from the application cache, not from the web
server. The manifest is simply a text file that typically has a file extension of .appcache.
CACHE MANIFEST
# 2012-03-08:v1
# Explicitly cached resources
index.html
css/app.css
js/app.js
# offline.html displays if the user is offline
FALLBACK:
/ /offline.html
# All other resources require an online connection
NETWORK:
*
# Additional cached resources
CACHE:
img/logo.png
Your manifest file must be served with the mime-type text/cache-manifest. You may need to add a
custom file type to your web server or configuration. For example, to serve this mime-type in Apache, add this
line to your configuration file (httpd.conf):
AddType text/cache-manifest .appcache
To access the manifest file, you must declare it in your HTML document by adding the manifest attribute to
the <html> tag. The manifest attribute points to the manifest file. If your web application has more than
one page, make sure that each page includes the manifest attribute, otherwise those pages won't be part of
AppCache, and they won't work offline.
<html manifest="html5.appcache">

Updating the appcache


Once your application is cached, it remains cached until one of the following actions occurs:
The user clears their cache.
The manifest file is modified. Note: Updating the resources on your server will not trigger a cache update.
You must change the manifest file itself.
The application cache is programmatically updated.
Best Practices

326

Related resources
To learn more about appcache, visit the following resources:
ApplicationCache API specification
Article from A List Apart Magazine

Use the correct viewport syntax


The viewport is the rectangular area that the user sees on their mobile device. You can override the default
viewport by using the viewport <meta> tag in the <head> section of your HTML document.
Keep in mind that the syntax for the viewport meta tag is not the same as the syntax for the @viewport
rule in CSS. This means that you must use commas as delimiters between viewport values, and not
semicolons. If you use semicolon delimiters, the viewport values can be interpreted incorrectly.
Here's an example showing the correct syntax for the viewport meta tag:
<meta name="viewport" content="width=device-width,
initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, userscalable=no">

Create a site icon


Every web browser looks for a favicon.ico (short for favorites icon) file and displays the file as the site's icon.
You often see the small icon displayed in the address bar, tabs, user's bookmarks or favorites.

When the browser looks for your web page, it will also make a request for your favicon.ico file. If the favicon.ico
file can't be found, you'll see 404 errors in your web server's log. To avoid this, you should always specify a
favicon.ico file in your web pages.
[Mon Aug 20 15:17:49 2012] [error] [client 192.0.2.2] File does not exist:
C:/www/favicon.ico
In the <head> section of your HTML5 documents, add a link tag pointing to your favicon.ico file.
<link href="favicon.ico" rel="icon" type="image/x-icon">

Use external files


Using external files for your JavaScript and CSS has many benefits, but one of the major benefits is making
your web pages load faster. Why do they load faster? Here are a couple reasons:
Best Practices

327

External files are cached by the browser. This reduces the number of HTTP requests; however, inline
JavaScript and CSS is downloaded each time the HTML document is requested.
Reduces the size of the HTML document. Since the JavaScript and CSS files are external, there is less
inline code in the original HTML document to parse and render.
Note:
For BlackBerry WebWorks applications, the resources are typically bundled with the application. The following
information applies mainly to web (browser-based) applications.
The benefits for external files aren't experienced in every situation. Before you start externalizing your
application's resources, consider only making the resource external if:
The resource is used in more than one HTML document
The resource changes infrequently
Here are some tips when using external files in your web application:
Source your files off a well-known host, which can reduce the number of DNS lookups.
Spread the resources out to another domain. The browser has a limited number of connections that it will
open to a particular domain; if you spread the files out to another domain, it increases the browsers
freedom to parallelize requests.
Use CDN (Content Delivery Network) hosted files for common JavaScript libraries (for example, jQuery).
This can improve your web application's performance by decreasing latency and improving what's cached.
For example, if a user has visited another site that uses CDN hosted files, those files will already be cached
on the device. When the user visits your site for the first time, the library will already be available. Here's a
code example that uses the Google's CDN-hosted jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
jquery.min.js">
</script>
Analyze the performance of your web application by using the Web Inspector. For more information about
the Web Inspector, see Debugging using Web Inspector on page 292.

Put your stylesheets at the top


Another way to improve the loading speed of your page is to place your stylesheets at the top of your HTML
document. When you have stylesheets in the <head> section of your document, the page renders
progressively so it appears to load faster and provides visual feedback to the user as they wait. If your
stylesheets are near the bottom of the document, the browser blocks progressive rendering to avoid having to
redraw elements of the page if their styles change, so the user ends up with a blank white page. Having
stylesheets at the top also increases parallelization because, unlike scripts, stylesheets do not require
synchronous processing.
You can add your stylesheets to your HTML document by using the <link> tag.
<!DOCTYPE html>
<html>
<head>
Best Practices

328

...
<link rel="stylesheet" href="styles1.css">
</head>
<body>
...
</body>
</html>

Do not import stylesheets


When adding external stylesheets to your HTML document, do not use the @import rule. You should use the
<link> tag instead.
If you use the @import rule to import style sheets, in some browsers, it behaves as though your stylesheet is at
the bottom of the HTML document. This is not the behavior you want because because it prevents the web
page from loading progressively.
Not recommended: Using @import
<style>
@import url("styles2.css");
</style>

Recommended: Using a LINK tag


<link rel="stylesheet" href="styles1.css">
In addition, the @import rule can be nested inside CSS files, preventing the browser from loading your
stylesheets in parallel. For example, if styles1.css contained the following:
@import url(styles2.css)
The browser must first retrieve styles1.css and then retrieve styles2.css.

Put scripts at the bottom


Although the W3C spec allows you to put your SCRIPT element in either the head or the body of your HTML
document, there are several reasons why adding scripts to the body is preferred. Where you place your scripts
can affect the progressive rendering of your HTML page. Because the browser stops and processes JavaScript
code as it encounters it, progressive rendering is blocked for all content below the script. If your script is lower
in the HTML document, more content is rendered progressively.
Putting your script at the bottom also improves parallel downloading components in parallel. While a script is
downloading, parallel downloading is disabled. If the script is at the top, the browser must wait for the script to
download before downloading any other components.

Best Practices

329

Unless you're using the deprecated document.write to generate the body, your scripts can typically be
moved to the bottom of the HTML document.
Another advantage to putting the script in the BODY (before the closing body tag) is that you don't need to
check to see if the DOM is loaded, because everything in the DOM has already loaded.
Recommended: Placing the script near the bottom of the BODY
<html lang="en">
<body>
...
<script src="js/app.js"></script>
</body>
</html>

Not recommended: Placing the script in the HEAD


<html lang="en">
<head>
<script src="js/app.js"></script>
</head>
<body onload="init();">
...
</body>
</html>
Note:
Some third-party frameworks require that you include the scripts at the very top of the HTML document. Refer
to the third-party's documentation for more information.

Defer script loading


An alternative to moving your JavaScript files to the bottom of your HTML document is to use deferred scripts.
The DEFER attribute tells the browser to execute the script after the page has loaded.
<script src="js/app.js" defer></script>
Unfortunately, the DEFER attribute behaves differently between browsers. To avoid cross-browser issues, you
can use the "lazy loading" approach. That is, avoid loading scripts until they are needed.
Here's an example of an unobtrusive lazy load pattern:
function lazyload() {
var elem = document.createElement("script");
elem.type = "text/javascript";
elem.async = true;
elem.src = "app.js"; // contains more than 25 uncalled functions
Best Practices

330

document.body.appendChild(elem);

if (window.addEventListener) {
window.addEventListener("load", lazyload, false);
} else if (window.attachEvent) {
window.attachEvent("onload", lazyload);
} else {
window.onload = lazyload;
For more information on lazy loading, see the following resources:
Google Analytics - Tracking Basics (Asynchronous Syntax)
Microjs

CSS best practices


In this section, we'll provide some tips and best practices for your stylesheets.

Use efficient CSS selectors


To create an efficient web application, you should understand how a browser reads your web pages and
renders them. When a browser reads your HTML document, it parses the HTML elements and assembles them
into a document tree. The browser then matches the elements to the style rules that you specified in your
stylesheets. The browser reads your style rule from right to left, starting from the rightmost selector, called the
key selector, and moving left through each additional selector, or descendant selector, until it finds a match or
discards the style rule. To make this matching efficient, you need to decrease the time it takes for the browser
to find a matching style rule.
Consider the following example:
#home a {color: blue;}
We'd expect to read this selector as: find the element with the id="home", then apply the color style to every
anchor (<a> tag) it contains. You might think this would be quick because we are using an ID tag and ID
selectors are typically fast. However, because the browser reads the selectors from right to left, here's how the
browser actually reads the rule: find every anchor tag, then check that its parent element has an id="home",
keep checking until a match is found or until the end of the HTML document is reached.
A more efficient way to write this style is to avoid the descendant selector and use a class that's associated
with the anchor tag, such as:
.home-anchor {color: blue;}

Best Practices

331

So, the idea is to write more specific style rules so that the browser spends less time looking to match your
style.
#main-navigation {
}
body.home #page-wrap {
.main-navigation {
}
ul li a.current {
}
ul {
}
ul li a { }
* {
}
#content [title='home']

/*
/*
/*
/*
/*
/*
/*
/*

ID (Fastest) */
ID */
Class */
Class *
Tag */
Tag */
Universal (Slowest) */
Universal */

Note:
Although there might be a performance benefit in using appropriate CSS selectors, you shouldn't take the
selector rules too far because you might see a disproportionate increase in maintenance costs vs. the
performance benefits you gain. As always, you should analyze the performance of your application by using the
Web Inspector. For more information about the Web Inspector, see Debugging using Web Inspector on page
292.
There are four types of selectors. ID and class selectors are more efficient than tag or universal selectors.
Selector

Description

ID

This selector matches the unique element in the page with the specified ID.
Example: #chapter1 {text-align: center; }

Class

This selector matches all elements with a class attribute contain the class name.
Example: .chapter1 { font-weight: bold; }

Tag or type

This selector matches every instance of the element type in the document tree.
Example: h1 { font-family: sans-serif; }

Universal

This selector, written using *, matches every element in the document.


Example: * {font-family: Arial; }

The following example shows where a class selector would be more efficient that a descendant selector:
Slower
ul li {color: blue;}
ol li {color: red;}
Best Practices

332

Faster
.unordered-list-item {color: blue;}
.ordered-list-item {color: red;}

Specify image dimensions


To improve the rendering speed of your web page, if your page has embedded images, it's a good practice to
specify the dimensions of your image.
<img src="img/logo.png" style="width: 100px; height: 100px;">
Because a browser downloads each image separately, it helps the browser to know the image's height and
width. This allows the browser to create an appropriately sized placeholder so it can determine the page layout
while the image downloads. Otherwise, the browser has to reflow the page after each image downloads and the
image's real size becomes known. This slows the rendering of the page and negatively affects the user
experience.
When you specify the dimensions of the image, it should be the actual image size. Do not scale images on the
fly by specifying a different width/height than the actual image. For example, say an image file is actually 50 x
50 pixels, but you want the image to display smaller, so you set the dimensions to 20 x 20 pixels in the HTML.
Rescaling images consumes CPU cycles, causes repainting which uses more memory, and slows page
rendering.
Instead, create your images at the appropriate size. This will not only improve rendering speed, but also avoid
downloading an unnecessarily large file. Remember that most mobile data plans are not unlimited, so you want
to reduce the data usage for the user.
To set an image's size, you can use the width and height attributes of the <img> tag or the width and height
CSS properties. There is no need to use both because CSS properties override HTML attributes.

Examples
HTML

Inline CSS

<img id="logo" src="logo.jpg"


alt="Company logo" height="100"
width="100" />

<img id="logo" src="logo.jpg"


style="width: 100px; height:
100px;">

Best Practices

333

External CSS

#logo { width: 100px; height:


100px; }

Use CSS sprites


You can reduce the number of HTTP requests for images on your web page by using CSS sprites. The CSS
sprites technique allows you to combine all your background images into one large image and use background
positions to show or hide a portion of that image in an HTML element. Not only does this technique reduce load
times but it also provides cleaner markup and cleaner projects (fewer image files to manage). CSS sprites can
be used in many ways but it's ideal for rollover buttons and navigation menus.

Here's an example that uses the nth-child notation along with CSS sprites to create a navigation menu:
#navcontainer li {
background-image: url('spritebg.jpg'); /* single image */
}
#navcontainer ul li:nth-child(1) {
background-position: -130px -700px; /* position = xpos ypos */
}
#navcontainer ul li:nth-child(2) {
background-position: -130px -718px;
}
#navcontainer a {
width: 250px; /* size */
height: 18px;
}

Best Practices

334

Trigger hardware acceleration


If you are using animations in your application, you can improve the user experience for your app and create
smooth transitions by triggering hardware acceleration. By default, most browsers do not have hardware
acceleration turned on. The browser typically uses hardware acceleration for elements that would benefit from
it (for example, WebGL components, transitions, and 3D transformations). However, if you want a specific
element to benefit from hardware acceleration, you can manually trigger hardware acceleration on that
element by adding the -webkit-transform property to your element.
... {
-webkit-transform: <transform function>;
}
The transform property applies a 2D or 3D
transformation to an element. You can use the
transform property to rotate, scale, skew, and
translate elements.
In the following example, we animate an image by
using the transform property and applying a 15
degree rotation around the Z and Y axis.

img.rotate3d {
-webkit-transition: -webkit-transform 1s ease-in-out;
-webkit-transform: rotate3d(0, 0, 1, 0deg);
}
img.rotate3d:hover {
-webkit-transform: rotate3d(0, 0, 1, 15deg);
}
Keep in mind that triggering hardware acceleration doesn't mean you'll have a faster app. An element with a
3D transform applied to it (or other hardware-accelerated elements) is painted into GPU memory so that it can
take advantage of accelerated transforms. This technique does not speed up the cascade, layout, JavaScript,
or the painting of anything, it simply speeds up the transform.
Note:
Important: You should use this technique sparingly! The GPU is not shy about using resources, including
battery power and memory.

Optimize scrolling performance


Hardware acceleration can also improve a user's interaction with any scrolling content in your app, such as
lists or grids. By default, the overflow CSS property is not hardware-accelerated, and using it on a list that
Best Practices

335

contains a lot of content can result in performance issues, such as sluggish scrolling or an inconsistent
response to touch input.
To benefit from hardware acceleration, include the -webkit-overflow-scrolling: touch property if
you use an overflow property in your app. Here's an example:
... {
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
}
When you make this addition, it allows for momentum and smoother scrolling, a visual bounce effect when the
user reaches the top or bottom of the list, and a more responsive touch interaction.

JavaScript best practices


In this section, we'll provide some tips and best practices for JavaScript.

Use literal notation for objects and arrays


You can choose to create objects and arrays in many ways, but the simplest and fastest way is to use literal
notation. The traditional method uses the built-in constructors Object() and Array() as in the following
example:
//create an object
var obj = new Object();
obj.debug = false;
obj.lang = "en";
//create an array
var arr = new Array("one", "two", "three");
Although the traditional method of creating objects and arrays is technically accurate, the literal notation
evaluates more quickly and requires less code. Here's the previous code written using literal notations:
//create an object
var obj = {debug: false, lang: "en"};
//create an array
var arr = ["one", "two", "three"];

Avoid using global variables and functions


You can reduce the risk of name collisions and improve the performance of your application by binding
properties and methods to a namespace object rather than creating global variables and functions.

Best Practices

336

Namespace collisions occur when two regions of code use the same global variable name for different
purposes. In JavaScript, variables defined outside a function or object are globally available and are part of the
global namespace. As your application grows and you add libraries to it, the risk of naming collisions increases.
Using global variables can also affect the performance of your script. If code inside a function or another scope
references a particular global variable, the script engine must go through each scope until it reaches the global
scope. A variable in the local scope is found more quickly. Variables in the global scope also persist through
the life of the script, whereas local scope variables are destroyed when the local scope is lost. The memory that
local variables use can then be freed by the garbage collector.
The following code snippet defines a function and variables that are global in scope. As a result, it is both
inefficientsince it persists in memory much longer than necessaryand at risk for future namespace
collisions.
//define global variables
var lang = "en";
var debug = true;
//define global function
function setLang (arg) {
lang = arg;
}
In the following example, we've rewritten the previous snippet to define and use a namespace. The namespace
object, myApp, is created and assigned values and functions to it. By using this technique, we limit the scope
of the variables and functions.
var myApp = {
lang: "en",
debug: true,
};
myApp.setLang = function (arg) {
this.lang = arg;
}
Structuring your code this way helps avoid name collisions and as your code base grows, you can neatly
separate the objects into logical files.

Use try-catch blocks effectively


You can use try-catch statements to intercept thrown errors before they are handled by the browser. The
try-catch statements are useful when you are trying to hide errors from the user, or when you want to
produce custom errors for the benefit of your user.
When an error occurs in the try block, execution immediately stops and jumps to the catch block, where the
error object is provided. When the catch block is executed, the error object is assigned to a new variable and
that new variable lasts for the duration of the catch block; it's destroyed when the catch block ends. The
creation and handling of this new runtime variable might affect the performance of your application. You
should avoid using try-catch blocks within a critical function or loop.
Best Practices

337

The following example shows a loop than might throw several exceptions affecting the performance of the
script:
var object = ['foo', 'bar'], i;
for (i = 0; i < object.length; i++) {
try {
// do something
} catch (e) {
// handle exception
}
}
We've re-written the previous code to improve the effectiveness of the try-catch block. Instead of including
the try-catch block within the loop, we restructure the code so that the try-catch block surrounds the
loop.
var object = ['foo', 'bar'], i;
try {
for (i = 0; i < object.length; i++) {
// do something
}
} catch (e) {
// handle exception
}

Concatenate strings with the assignment operator


Concatenating, or joining strings, is commonly used in JavaScript, but the way you concatenate strings can
affect the peformance of your application. You can concatenate strings in any of the following ways:
Method

Example

Using the concatenation (+) operator

str = "h" + "e";

Using the shorthand assigment (+=) operator

str += "l";

Using string.concat()

str = str.concat("l", "o");

Using array.join()

str = ["h", "e", "l", "l",


"o"].join("");

If you're concatenating just a few strings, then any of the above methods are acceptable and perform equally.
However, if the length and number of strings increase then you should optimize how you concatenate strings.

Best Practices

338

Slower: Concatenating strings with + operator


str += "x" + "y";
When you concatenate strings by using the concatenation (+) operator, the following occurs:
1.
2.
3.
4.

A temporary string is created in memory,


The concatenated value ("xy" in the example below) is assigned to the temporary string.
The temporary string is concatenated with the variable's current value.
The result is assigned to the variable.

Faster: Concatenating strings with += operator


You can speed up concatenation and use less memory by avoiding the temporary string. In the following
example, we create two distinct statements and directly assign the result with the assignment operator.
str += "x";
str += "y";

Optimize your loops


When you're using loops in JavaScript, you can optimize the overall performance of the loop by reducing the
work that's done in each iteration. One way to reduce this work is to minimize the number of object lookups by
caching the objects.
In the following example, we create a typical but inefficient loop. For each iteration of the loop, the
arr.length object is re-calculated, causing an unncessary hit on performance.
for (var i = 0; i < arr.length; i++) {
// length of arr is recalculated every time
}
You can improve the previous loop by caching the arr.length object so it's calculated only once. Now, the
control condition uses only local variables, thereby improving the speed of the loop.
for (var i = 0, len = arr.length; i < len; i++) {
// cache the length of the array
}
To further improve your loop, consider executing the loop in reverse. If you're not concerned about the order in
which the array is processed, you can improve the loop execution by reversing the order with the decrement

Best Practices

339

operator and by combining the control conditions. In the following example, the control condition is reduced
from two comparisons (is i < len and is the condition true?) to one (is the condition true?):
for (var i = arr.length; i--;) {
// in reverse
}

Avoid using the eval() method


To improve the performance of your script, you should avoid using the eval() method. The eval() method
evaluates a string of JavaScript code and executes it. The code can contain an expression or JavaScript
statements.
The use of eval() is discouraged for the following reasons:
Poor performance: The eval() method must invoke the compiler to pass the string and execute the
results. In addition, the evaluated code is not cached.
Security issues: The eval() method can make your code vulnerable to various injection attacks as it
executes any code given to it. You should never use eval() with strings of unknown or untrusted origins.
Impairs debugging: Code that includes eval() can be more difficult to debug because the code from
eval() is dynamically generated. Also, the eval form is harder to read and can often be written in a
cleaner and clear way without the use of eval().
Incorrect usage: Using eval to set a value
eval("myValue = myObject." + myKey + ";");

Correct usage: Using subscript notation to set a value


myValue = myObject[myKey];
The timeout methods setTimeout() and setInterval() can also take a string and execute code thereby
acting like the eval() method. You should avoid passing a string to setInterval() and setTimeout()
and instead pass a function.
Incorrect usage: Passing a string to setInterval()
var oElement = null;
setInterval('oElement = document.getElementById("pepe");', 0);

Best Practices

340

Correct usage: Passing a function to setInterval()


var oElement = null;
setInterval(function() {
oElement = document.getElementById("pepe");
}, 0);

Use event delegation


When handling DOM events, you can improve the efficiency and performance of your script by attaching an
event to a single parent element instead of attaching events to every element. This is called event delegation.
Event delegation takes advantage of event bubbling to assign a single event handler to manage all the events of
a particular type. For example, if there are 10 buttons inside a <div> element, you can attach one event
listener to the <div> as opposed to attaching 10 listeners for the 10 buttons.
The HTML in the following example contains two buttons that should perform an action when clicked.
Traditionally, we would simply attach an event handler to each item like this:
<a href="javascript:handleClick();">Click</a>
<button id="btn1" onclick="handleClick();">One</button>
<button id="btn2" onclick="handleClick();">Two</button>
To improve the performance of this code, we use event delegation by adding a single onclick event handler
to the div that contains the buttons. Since all the buttons are children of the div, their events bubble up and
are handled by the function. The event target is the button that was clicked, so we can check the id property
to determine the appropriate action. With this approach, we retrieved one DOM element and attached a single
event handler, thereby reducing the amount of memory used.
<div id="btngroup">
<button id="btn1">One</button>
<button id="btn2">Two</button>
</div>
document.getElementById("btngroup").addEventListener("click", function
(event) {
switch (event.srcElement.id) {
case "btn1":
handleClick();
break;
default:
handleClick;
}
}, false); // type, listener, useCapture (true=beginning, false=end)
Using event delegation also makes it easier to add and remove buttons in the future.

Best Practices

341

Minimize DOM access


Working with the DOM at any point can be a performance drainer. The DOM is a complex API that manages a
lot of information, so even minor operations can take longer to execute because they often require re-rendering
the page. To improve the performance of your application you should try to minimize your interactions with the
DOM. Here are some tips for minimizing those interactions:

Reduce the number of DOM elements


The size of the DOM slows down all operations related to it, including manipulations, reflows, and traversing
the DOM. One way to improve these operations is to make your DOM smaller.
Avoid extra tags and nested tables.
Try to aim for less than 500 elements in your DOM. You can track the size with
document.getElementsByTagName('*').length.

Cache references to accessed elements


Whenever you are accessing DOM elements, you should be caching the objects that you access. More often
than not, your script will repeatedly access a certain object, as in the following example:
Slow:
for (var i = 0; i < document.images.length; i++) {
document.images[i].src = "blank.gif";
}
In the above example, the document.images object is accessed multiple times. This is inefficient because
for every iteration of the loop, the browser must look up the document.images object twice: once to read
the .length property and ascertain if i < document.images.length and once to read and change the
value of the .src property.
A more efficient version uses a variable to store document.images, which can then be accessed by your
script.
Better:
var imgs = document.images;
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = "blank.gif";
}

Minimize reflows and repaints


In addition to reducing the number of DOM interactions, you can improve the performance of your application
by minimizing the number of DOM updates, such as changing elements, removing elements, or adding new
ones. Updates to the DOM can cause the browser to repaint the screen as well as reflow, which can be
expensive operations.
Best Practices

342

A repaint (often called a "redraw") occurs when you change an element that modifies its visibility but does not
affect its layout (for example, changing the background color). The browser recognizes the visual change and
repaints the document.
A reflow involves changes that affect the layout of a portion of the page (or the whole page) and causes the
reflow of all child and ancestor elements (for example, a table). With a reflow, the browser looks to see how
your changes affect the overall layout of the document. The browser recalculates the geometrics of the
changed element as well as the geometrics and positions of other elements that could be affected by the
change.

What causes a reflow?


A reflow is needed whenever you change the layout of the page. A reflow can occur if you:
Add or remove a DOM node
Change the position of an element
Change the size of an element (by changing the margin, padding, border thickness, font, width, height,
etc.)
Resize the browser window
Add or remove a stylesheet
Change the content (for example, a user types text in an input box)
Activate CSS pseudo-selectors such as :hover
Manipulate the class attribute
Utilize a script to manipulate the DOM
Retrieve a measurement that must be calculated (for example, calculating offsetWidth and
offsetHeight)
Set a property on a style attribute

How do you minimize repaints and reflows?


Here are some CSS and JavaScript tips for minimizing reflows and repaints:
CSS tips
Change classes on the element you wish to style as low in the DOM tree as possible to limit the scope of the
reflow to as few nodes as possible.
Avoid setting multiple inline styles and try instead to combine the styles into a external class, which causes
only one reflow when the attribute is changed.
Apply animations to elements whose position are fixed or absolute as they don't affect the layout of other
elements, so only a repaint will occur rather than a reflow.
Avoid using tables for layout. If you need to use a table for data, use a fixed layout (tablelayout:fixed).
JavaScript tips
Cache computed styles.
Best Practices

343

For static styles, change the class names not the styles. For dynamic styles, edit the cssText property.
// bad - changing the stle - accessing DOM multiple times
var myElement = document.getElementById('mydiv');
myElement.style.borderLeft = '2px';
myElement.style.borderRight = '3px';
myElement.style.padding = '5px';
// good - use cssText and modify DOM once
var myElement = document.getElementById('mydiv');
myElement.style.cssText = 'border-left: 2px; border-right: 3px; padding:
5px;';
When you have a number of changes to apply to a DOM element, batch the changes and perform them
outside the "live" document tree before any reflow-triggering actions.
Create a copy of the node you want to update by using cloneNode(), work on that copy, and then
replace the old node with your updated copy.
// slower - multiple reflows
var list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
elem.appendChild(content);
document.body.appendChild(elem); // multiple reflows
}
// faster - create a copy
var orig = document.getElementById('container'),
clone = orig.cloneNode(true), // create a copy
list = ['foo', 'bar', 'baz'], elem, contents;
clone.setAttribute('width', '50%');
Modify an invisible element. If you need to modify an element, temporarily change its display
property to none, modify the element, and then set the display property to block. This technique
temporarily removes the element from the document flow, thus reducing the number of reflows.
// slower
var subElem = document.createElement('div'),
elem = document.getElementById('animated');
elem.appendChild(subElem);
elem.style.width = '320px';
// faster
var subElem = document.createElement('div'),
elem = document.getElementById('animated');
elem.style.display = 'none'; // will not be repainted
elem.appendChild(subElem);
elem.style.width = '320px';
elem.style.display = 'block';
Best Practices

344

Create a document fragment by using DocumentFragment() to make multiple changes to the DOM
in a single operation. After you've made your changes, append that fragment to the original document.
// slower
var list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
elem.appendChild(content);
document.body.appendChild(elem); // multiple reflows
}
// faster
var fragment = document.createDocumentFragment(),
list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
fragment.appendChild(content);
}
document.body.appendChild(fragment); // one reflow

Best Practices

345

Best Practices

346

Legal notice
2015 BlackBerry. All rights reserved. BlackBerry and related trademarks, names, and logos are the

property of BlackBerry Limited and are registered and/or used in the U.S. and countries around the world.

Adobe, Adobe Illustrator, and Photoshop are trademarks of Adobe Systems Incorporated. Bluetoothis a
trademark of Bluetooth SIG. Facebook and the Facebook logo is a trademark of Facebook, Inc. Slate Pro Font
is a trademark of Monotype Imaging Inc. and may be registered in certain jurisdictions. Twitter is a trademark
of Twitter, Inc. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are the property of their
respective owners.
This documentation including all documentation incorporated by reference herein such as documentation
provided or made available on the BlackBerry website is provided or made accessible "AS IS" and "AS
AVAILABLE" and without condition, endorsement, guarantee, representation, or warranty of any kind by
BlackBerry Limited and its affiliated companies ("BlackBerry") and BlackBerry assumes no responsibility for
any typographical, technical, or other inaccuracies, errors, or omissions in this documentation. In order to
protect BlackBerry proprietary and confidential information and/or trade secrets, this documentation may
describe some aspects of BlackBerry technology in generalized terms. BlackBerry reserves the right to
periodically change information that is contained in this documentation; however, BlackBerry makes no
commitment to provide any such changes, updates, enhancements, or other additions to this documentation
to you in a timely manner or at all.
This documentation might contain references to third-party sources of information, hardware or software,
products or services including components and content such as content protected by copyright and/or thirdparty web sites (collectively the "Third Party Products and Services"). BlackBerry does not control, and is not
responsible for, any Third Party Products and Services including, without limitation the content, accuracy,
copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other
aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Services
in this documentation does not imply endorsement by BlackBerry of the Third Party Products and Services or
the third party in any way.
EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL
CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS,
GUARANTEES, REPRESENTATIONS OR WARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR
PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NON-INFRINGEMENT, SATISFACTORY
QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF
TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE
OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES
REFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY
STATE OR PROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF
IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED
WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE
EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROM
Legal notice

347

THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE
CLAIM.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL
BLACKBERRY BE LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE,
OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD
PARTY PRODUCTS AND SERVICES REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE
FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL,
PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGES FOR LOSS OF PROFITS OR REVENUES, FAILURE TO
REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS
OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE
ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH
BLACKBERRY PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF BLACKBERRY
PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OF
SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR
PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN
IF BLACKBERRY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, BLACKBERRY
SHALL HAVE NO OTHER OBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR
OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY.
THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE
NATURE OF THE CAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO
BREACH OF CONTRACT, NEGLIGENCE, TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND
SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE
OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B) TO BLACKBERRY AND ITS
AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIME
SERVICE PROVIDERS), AUTHORIZED BLACKBERRY DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE
PROVIDERS) AND THEIR RESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS.
IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY
DIRECTOR, EMPLOYEE, AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF BLACKBERRY
OR ANY AFFILIATES OF BLACKBERRY HAVE ANY LIABILITY ARISING FROM OR RELATED TO THE
DOCUMENTATION.
Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to
ensure that your airtime service provider has agreed to support all of their features. Some airtime service
providers might not offer Internet browsing functionality with a subscription to the BlackBerry Internet
Service. Check with your service provider for availability, roaming arrangements, service plans and features.
Installation or use of Third Party Products and Services with BlackBerry's products and services may require
one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third
party rights. You are solely responsible for determining whether to use Third Party Products and Services and if
any third party licenses are required to do so. If required you are responsible for acquiring them. You should
not install or use Third Party Products and Services until all necessary licenses have been acquired. Any Third
Party Products and Services that are provided with BlackBerry's products and services are provided as a
convenience to you and are provided "AS IS" with no express or implied conditions, endorsements,
Legal notice

348

guarantees, representations, or warranties of any kind by BlackBerry and BlackBerry assumes no liability
whatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject
to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties,
except to the extent expressly covered by a license or other agreement with BlackBerry.
The terms of use of any BlackBerry product or service are set out in a separate license or other agreement with
BlackBerry applicable thereto. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY
EXPRESS WRITTEN AGREEMENTS OR WARRANTIES PROVIDED BY BLACKBERRY FOR PORTIONS OF ANY
BLACKBERRY PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION.
BlackBerry Limited
2200 University Avenue East
Waterloo, Ontario
Canada N2K 0A7
BlackBerry UK Limited
200 Bath Road
Slough, Berkshire SL1 3XE
United Kingdom
Published in Canada

Legal notice

349

Legal notice

350

Вам также может понравиться