BlackBerry WebWorks 2.1-Development Guide

326
BlackBerry WebWorks 2.1 Development Guide

Transcript of BlackBerry WebWorks 2.1-Development Guide

Page 1: BlackBerry WebWorks 2.1-Development Guide

BlackBerry WebWorks 2.1

Dev

elop

men

t Gui

de

Page 2: BlackBerry WebWorks 2.1-Development Guide

Published: 2014-05-14SWD-20140514113835862

Page 3: BlackBerry WebWorks 2.1-Development Guide

Contents

Getting Started ........................................................................................................................................... 5What's a BlackBerry WebWorks app?..............................................................................................................5Components of the BlackBerry 10 WebWorks SDK..........................................................................................7Setting up your tools.....................................................................................................................................11Creating a WebWorks project........................................................................................................................19Creating your first app.................................................................................................................................. 21

Porting and Upgrading............................................................................................................................... 25Upgrading from WebWorks 1.0.....................................................................................................................25Porting from Cordova................................................................................................................................... 32Porting to other platforms.............................................................................................................................34Porting AIR apps to WebWorks..................................................................................................................... 35

Adding Features........................................................................................................................................ 41Adding and removing plugins....................................................................................................................... 41Using custom plugins................................................................................................................................... 45Modifying your app configuration..................................................................................................................53Creating headless WebWorks apps............................................................................................................... 93App integration............................................................................................................................................ 98BBM Social Platform.................................................................................................................................. 200Payment Service........................................................................................................................................ 209Push Service.............................................................................................................................................. 223

Frameworks.............................................................................................................................................249jQuery ....................................................................................................................................................... 249Sencha Touch 2......................................................................................................................................... 252Dojo Toolkit................................................................................................................................................254Enyo 2.0.................................................................................................................................................... 257bbUI toolkit................................................................................................................................................ 259

Building and Testing................................................................................................................................ 261Setting up test targets................................................................................................................................ 261Previewing your app in a browser................................................................................................................263Building your app for testing.......................................................................................................................264Debugging using Web Inspector................................................................................................................. 270Testing and debugging apps in the work space .......................................................................................... 294Building and signing your completed app................................................................................................... 295Distributing your app..................................................................................................................................299

Page 4: BlackBerry WebWorks 2.1-Development Guide

Best Practices......................................................................................................................................... 301UI guidelines..............................................................................................................................................301HTML best practices.................................................................................................................................. 301CSS best practices..................................................................................................................................... 308JavaScript best practices........................................................................................................................... 313

Legal notice............................................................................................................................................. 323

Page 5: BlackBerry WebWorks 2.1-Development Guide

Getting StartedLearn 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 open-source 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 platform-dependent. 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 5

Page 6: BlackBerry WebWorks 2.1-Development Guide

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

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 6

Page 7: BlackBerry WebWorks 2.1-Development Guide

Components of the BlackBerry 10 WebWorks SDKThe 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.

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 7

Page 8: BlackBerry WebWorks 2.1-Development Guide

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 8

Page 9: BlackBerry WebWorks 2.1-Development Guide

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 Description

com.blackberry.app Provides basic app support.

com.blackberry.bbm.platform Lets you access the social features and functionality of BBM.

Required permission: bbm_connect

com.blackberry.connection Lets you access the cellular and Wi-Fi connection information for the BlackBerry device.

com.blackberry.display Allows you to control whether the screen dims while the app is in the foreground.

com.blackberry.identity Provides information about the user's identity and accounts.

Required permission: read_device_identitying_information

com.blackberry.invoke Lets your app invoke and interact with other apps on the device.

com.blackberry.invoke.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.

com.blackberry.io Provides access to the unsandboxed file systems.

com.blackberry.io.filetransfer Lets your app upload and download files to/from a remote server.

com.blackberry.notification Lets your app to provide notifications to the user.

Required permission: post_notification

com.blackberry.payment Lets you sell digital goods in your app.

com.blackberry.pim.calendar Lets you access and manage entries in the Calendar application.

Required permission: access_pimdomain_calendars

com.blackberry.pim.contacts Lets you create and find contacts.

Getting Started 9

Page 10: BlackBerry WebWorks 2.1-Development Guide

Plugin Description

Required permission: access_pimdomain_contacts

com.blackberry.push Lets you access the BlackBerry push architecture to receive push content in your app.

Required permissions:

• sys_use_consumer_push• run_when_backgrounded

com.blackberry.sensors Lets you get access to system level sensors and attributes of the BlackBerry device.

com.blackberry.system Lets you access system level functions and attributes of the BlackBerry device.

com.blackberry.ui.contextmenu 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.

com.blackberry.ui.dialog Lets you manipulate system dialog boxes.

com.blackberry.ui.toast Lets you display system toasts in your app.

Cordova plugins installed with BlackBerry WebWorks SDK

Plugin Description

org.apache.cordova.device-motion Captures device motion in the x, y, and z directions.

org.apache.cordova.camera Provides access to the device's default camera application.

org.apache.cordova.media-capture Provides access to the device's audio, image, and video capture capabilities.

org.apache.cordova.device-orientation Obtains the direction that the device is pointing.

org.apache.cordova.network-information

Provides information about the device's cellular and Wi-Fi connection.

org.apache.cordova.contacts Provides access to the device's contact database.

Getting Started 10

Page 11: BlackBerry WebWorks 2.1-Development Guide

Plugin Description

org.apache.cordova.device Describes the device's hardware and software.

org.apache.cordova.file Provides the functionality to read, write, and navigate file system hierarchies.

org.apache.cordova.geolocation Provides access to location information based on the device's GPS sensor or inferred from network signals.

org.apache.cordova.inappbrowser Provides a browser view that displays when calling window.open(), or when opening a link formed as <a target="_blank">.

org.apache.cordova.media Lets your app play back audio and video files on a device.

org.apache.cordova.dialogs, org.apache.cordova.vibration

Lets your app create visual, audible, and tactile notifications.

org.apache.cordova.splashscreen Lets your app hide and show the splash screen.

Setting up your toolsThe 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

OS • Windows XP SP3 32-bit

Getting Started 11

Page 12: BlackBerry WebWorks 2.1-Development Guide

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

Set 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 by creating your BlackBerry ID token and then creating your developer certificate.

Getting Started 12

Page 13: BlackBerry WebWorks 2.1-Development Guide

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.

Set up your computer for testing 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 signing. There are two tasks to complete this process:

• Request your BlackBerry ID token.• Create your developer certificate.

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.

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 create another BlackBerry ID token, then recreate your developer certificate.

3. Accept the license agreement and click Get Token.

The BlackBerry ID token is included in the keystore file you downloaded. The Signing Authority Service uses this token 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 allow 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 create 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.

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.

Getting Started 13

Page 14: BlackBerry WebWorks 2.1-Development Guide

4. Click Add Signing Key. The signing key (bbidtoken.csk) is installed to the following location:

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:

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

Parameters Description

-genkeypair Generates a key pair that consists of a private key and a public key.

-storepass <keystore_pw> Specifies the password that is used to control access to the keystore, which is your BlackBerry ID token password.

-dname Specifies the name to associate with the certificate that the tool creates.

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.

Getting Started 14

Page 15: BlackBerry WebWorks 2.1-Development Guide

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.

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 blackberry-debugtokenrequest 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.

Getting Started 15

Page 16: BlackBerry WebWorks 2.1-Development Guide

Options Description

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

-proxyusername<user name>

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

-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 blackberry-signer 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:

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.

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

Getting Started 16

Page 17: BlackBerry WebWorks 2.1-Development Guide

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:

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.

-devicepinlist<device_PIN_list_file>

The name of a file containing the PINs of the BlackBerry 10 devices on which you want to install this debug token. For example, the contents of a file called device_PINs.txt might appear as follows:

12G34H56 2K672HVP 221Q2958You would specify it like using the following syntax:

Getting Started 17

Page 18: BlackBerry WebWorks 2.1-Development Guide

option Description

-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, blackberry-debugtokenrequest 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.

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.

Getting Started 18

Page 19: BlackBerry WebWorks 2.1-Development Guide

Creating a WebWorks projectYou 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 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.

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.

To create a WebWorks project:

1. On the command line, navigate to the folder where you installed the BlackBerry WebWorks SDK.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:

Getting Started 19

Page 20: BlackBerry WebWorks 2.1-Development Guide

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> element in the config.xml file.

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.

Folder structure of a WebWorks project

A WebWorks 2.0 project has the following folder structure:

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.

Getting Started 20

Page 21: BlackBerry WebWorks 2.1-Development Guide

Folder Description

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.

.cordova/ This folder contains Cordova-specific configuration files.

Creating your first appThis 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 tools.

Set up your project

To create your project:

Getting Started 21

Page 22: BlackBerry WebWorks 2.1-Development Guide

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 Hello World in the Project Name field.4. Enter C:\TestApps in the Project Path field.5. Click Save.

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.4. Click Build & Install.

The tool packages your app into a .bar file, installs and launches it on your simulator.

View the app on a device

Verify the following on your BlackBerry 10 device:

• Development Mode is enabled ( Settings > Security and Privacy > Development Mode )• Debug token is installed and valid

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.

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. Also, each time the app opens, a dialog box appers to inform you that Web Inspector is enabled.

Getting Started 22

Page 23: BlackBerry WebWorks 2.1-Development Guide

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:

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.

Getting Started 23

Page 24: BlackBerry WebWorks 2.1-Development Guide

Getting Started 24

Page 25: BlackBerry WebWorks 2.1-Development Guide

Porting and UpgradingLearn 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.0As 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 tools.

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.• For more information about getting set up for testing and signing with BlackBerry WebWorks 2.0 or later,

see Set up your computer for testing and signing.

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.

Porting and Upgrading 25

Page 26: BlackBerry WebWorks 2.1-Development Guide

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.

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.

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.

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

Page 27: BlackBerry WebWorks 2.1-Development Guide

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 27

Page 28: BlackBerry WebWorks 2.1-Development Guide

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

com.blackberry.io.filetransfer

<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

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

Porting and Upgrading 28

Page 29: BlackBerry WebWorks 2.1-Development Guide

If you added this <feature> element: You need to add this plugin:

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

Page 30: BlackBerry WebWorks 2.1-Development Guide

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

Coding differences

If you have previously created a BlackBerry 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 30

Page 31: BlackBerry WebWorks 2.1-Development Guide

.}

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 Set up your computer for testing and signing.

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.8. Click Link Signing Keys. The developer certificate (the author.12 file) is created in the same location as

your signing key.

Porting and Upgrading 31

Page 32: BlackBerry WebWorks 2.1-Development Guide

Link accounts using the command line

When using the command-line tools, you have a few options:

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.

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 32

Page 33: BlackBerry WebWorks 2.1-Development Guide

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 33

Page 34: BlackBerry WebWorks 2.1-Development Guide

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.

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 34

Page 35: BlackBerry WebWorks 2.1-Development Guide

• 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 WebWorksWith 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 35

Page 36: BlackBerry WebWorks 2.1-Development Guide

• 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. Convert your Flash content to HTML52. Create a BlackBerry WebWorks project3. Add your HTML5 resources to your WebWorks project4. Rebuild your AIR Native Extensions as Cordova plugins5. Add plugins to your project6. Set configuration settings for your project7. Build and test your app

Before you begin

If you are new to BlackBerry WebWorks, before you start to port your app, look at the Getting Started 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 36

Page 37: BlackBerry WebWorks 2.1-Development Guide

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 tools).

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 tutorial. This tutorial walks you through the construction of the basic Echo plugin.

Porting and Upgrading 37

Page 38: BlackBerry WebWorks 2.1-Development Guide

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

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.

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 Deploy your app to a device.

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.

• Turn on Development Mode on the simulator. For security reasons, Development Mode expires after ten days and whenever the simulator is restarted. For more information, see Enable Development Mode on a device or simulator.

Porting and Upgrading 38

Page 39: BlackBerry WebWorks 2.1-Development Guide

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.

Porting and Upgrading 39

Page 40: BlackBerry WebWorks 2.1-Development Guide

Porting and Upgrading 40

Page 41: BlackBerry WebWorks 2.1-Development Guide

Adding FeaturesLearn 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 pluginsTo 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.

Each plugin you add to your project is 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 plugins/ 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.

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 41

Page 42: BlackBerry WebWorks 2.1-Development Guide

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 42

Page 43: BlackBerry WebWorks 2.1-Development Guide

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 Description

com.blackberry.app Provides basic app support.

com.blackberry.bbm.platform Lets you access the social features and functionality of BBM.

Required permission: bbm_connect

com.blackberry.connection Lets you access the cellular and Wi-Fi connection information for the BlackBerry device.

com.blackberry.display Allows you to control whether the screen dims while the app is in the foreground.

com.blackberry.identity Provides information about the user's identity and accounts.

Required permission: read_device_identitying_information

com.blackberry.invoke Lets your app invoke and interact with other apps on the device.

com.blackberry.invoke.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.

com.blackberry.io Provides access to the unsandboxed file systems.

com.blackberry.io.filetransfer Allows you to upload and download files to/from a remote server.

com.blackberry.notification Lets your app to provide notifications to the user.

Required permission: post_notification

com.blackberry.payment Lets you sell digital goods in your app.

com.blackberry.pim.calendar Lets you access and manage entries in the Calendar application.

Required permission: access_pimdomain_calendars

com.blackberry.pim.contacts Lets you create and find contacts.

Adding Features 43

Page 44: BlackBerry WebWorks 2.1-Development Guide

Plugin Description

Required permission: access_pimdomain_contacts

com.blackberry.push Lets you access the BlackBerry push architecture to receive push content in your app.

Required permissions:

• sys_use_consumer_push• run_when_backgrounded

com.blackberry.sensors Lets you get access to system level sensors and attributes of the BlackBerry device.

com.blackberry.system Lets you access system level functions and attributes of the BlackBerry device.

com.blackberry.ui.contextmenu 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.

com.blackberry.ui.dialog Lets you manipulate system dialog boxes.

com.blackberry.ui.toast Lets you display system toasts in your app.

Cordova plugins installed with BlackBerry WebWorks SDK

Plugin Description

org.apache.cordova.device-motion Captures device motion in the x, y, and z directions.

org.apache.cordova.camera Provides access to the device's default camera application.

org.apache.cordova.media-capture Provides access to the device's audio, image, and video capture capabilities.

org.apache.cordova.device-orientation Obtains the direction that the device is pointing.

org.apache.cordova.network-information

Provides information about the device's cellular and Wi-Fi connection.

org.apache.cordova.contacts Provides access to the device's contact database.

Adding Features 44

Page 45: BlackBerry WebWorks 2.1-Development Guide

Plugin Description

org.apache.cordova.device Describes the device's hardware and software.

org.apache.cordova.file Provides the functionality to read, write, and navigate file system hierarchies.

org.apache.cordova.geolocation Provides access to location information based on the device's GPS sensor or inferred from network signals.

org.apache.cordova.inappbrowser Provides a browser view that displays when calling window.open(), or when opening a link formed as <a target="_blank">.

org.apache.cordova.media Lets your app play back audio and video files on a device.

org.apache.cordova.dialogs, org.apache.cordova.vibration

Lets your app create visual, audible, and tactile notifications.

org.apache.cordova.splashscreen Lets your app hide and show the splash screen.

Using custom pluginsWhen 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.

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.

Adding Features 45

Page 46: BlackBerry WebWorks 2.1-Development Guide

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.

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

Adding Features 46

Page 47: BlackBerry WebWorks 2.1-Development Guide

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

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

Adding Features 47

Page 48: BlackBerry WebWorks 2.1-Development Guide

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

JNEXT.registerEvents(self); };

self.m_id = "";

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

Adding Features 48

Page 49: BlackBerry WebWorks 2.1-Development Guide

} 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

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.

Adding Features 49

Page 50: BlackBerry WebWorks 2.1-Development Guide

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.

• 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

Adding Features 50

Page 51: BlackBerry WebWorks 2.1-Development Guide

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

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

Adding Features 51

Page 52: BlackBerry WebWorks 2.1-Development Guide

• www

• client.js• src

• blackberry10

• index.js• *.cpp (native files)• *.hpp (native files)

• device

• *.so (binary files)• simulator

• *.so (binary files)

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>

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.

Adding Features 52

Page 53: BlackBerry WebWorks 2.1-Development Guide

Modifying your app configurationWhen 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.

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.

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.

Adding Features 53

Page 54: BlackBerry WebWorks 2.1-Development Guide

Preference Description

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.

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.

Adding Features 54

Page 55: BlackBerry WebWorks 2.1-Development Guide

Preference Description

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.

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.

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.

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.

Adding Features 55

Page 56: BlackBerry WebWorks 2.1-Development Guide

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

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. Navigate to your project and click Config.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

Adding Features 56

Page 57: BlackBerry WebWorks 2.1-Development Guide

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 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. Navigate to your project and click Config.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.

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.

Adding Features 57

Page 58: BlackBerry WebWorks 2.1-Development Guide

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.

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

Permission value Description

Camera use_camera Allows the app to take pictures, record video, and use the camera's flash.

Device information read_device_identifying_information

Allows the app to access device identifiers such as serial number and PIN.

Location information access_location_services Allows the app to access the device’s current or saved locations. This permission replaces read_geolocation, and includes

Adding Features 58

Page 59: BlackBerry WebWorks 2.1-Development Guide

Functionality or capability

Permission value Description

access to location information from GPS, Wi-Fi, and cell ID.

Shared files 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.

Push _sys_use_consumer_push Allows the app to use push functionality.

Run in background 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 processing in the background. Running the app in the background can negatively impact the battery life of the device.

BBM Social Platform bbm_connect Allows the app to connect to BBM so that the user can chat or update their BBM profile without leaving the app.

Email and PIN messages

access_pimdomain_messages Allows the app to access email and PIN messages, including viewing, creating, sending, and deleting messages.

Adding Features 59

Page 60: BlackBerry WebWorks 2.1-Development Guide

Functionality or capability

Permission value Description

Contacts access_pimdomain_contacts Allows the app to access contacts, including viewing, creating, and deleting contacts.

Calendar access_pimdomain_calendars Allows the app to access the calendar, including viewing, adding, and deleting appointments.

Notifications post_notifications Allows the app to post a notification to the notification area of the screen.

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.

Note: Although multiple copies of the config.xml file may exist within your project subfolders, you should edit only the master copy. The master copy of the file is located in your project's root folder. Other versions of the file are overwritten by the tools when a project is built, and any modifications made to those files are lost.

For a list of all the elements that you can use in a configuration document, see Elements in config.xml.

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

Adding Features 60

Page 61: BlackBerry WebWorks 2.1-Development Guide

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

<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. A dash indicates that the element is ignored for the specified platform.

Element Description

<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

Adding Features 61

Page 62: BlackBerry WebWorks 2.1-Development Guide

Element Description

<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

<license> Specifies end user license and copyright information.

zero or one

<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:invoke-target> Registers your application as a handler for an invocation event.

zero 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 child of <rim:permissions>.

one or more

<rim:splash> Specifies the image to display on the screen while your application loads.

zero or more

<widget> Provides a container for all other elements. one

widget element

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>

Adding Features 62

Page 63: BlackBerry WebWorks 2.1-Development Guide

Description

The <widget> element provides a container for all other elements, and it's the root element in the configuration document for a BlackBerry WebWorks application.

Parent elements

None

Child elements

Many. For a list of elements, see the Elements in config.xml table.

Occurrences

One, at the root of the configuration document.

Attributes

You can use the following attributes in the <widget> element:

Attribute Description

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

This attribute is required.

xmlns:rim 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".

This attribute is required.

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

Adding Features 63

Page 64: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

This attribute is required.

rim:header 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 those coming from the BlackBerry Browser. The attribute value can be any string.

This attribute is optional.

rim:userAgent 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.

This attribute is optional.

id 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".

The id attribute is required. 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 Specifies the language that is used in the element. For more information about this attribute, visit www.w3.org/TR/html401/struct/dirlang.html.

This attribute is optional.

Adding Features 64

Page 65: BlackBerry WebWorks 2.1-Development Guide

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>

access element

Syntax

<access origin="string" subdomains=["true" | "false"] />

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 only has access to local resources, 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.

Parent elements

<widget>

Child elements

None

Occurrences

Zero or more

Attributes

You can use the following attributes in the <access> element:

Adding Features 65

Page 66: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

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

The origin attribute is optional.

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

This attribute is optional.

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: Whitelisting an external resource

<access origin="https://somedomain.com" subdomains="true"/>

author element

Syntax

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

Description

The <author> element specifies information about the people or organizations that are involved with the creation of a BlackBerry WebWorks application.

Adding Features 66

Page 67: BlackBerry WebWorks 2.1-Development Guide

For BlackBerry smartphone applications running BlackBerry 7 or earlier, author information appears in the Vendor property when BlackBerry device users view the list of applications that are installed on the BlackBerry device.

You can access this element by using the blackberry.app.author property that is provided in the BlackBerry WebWorks API.

Parent elements

<widget>

Child elements

none

Occurrences

One

Attributes

You can use the following attributes:

Attribute Description

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

This attribute is optional.

Adding Features 67

Page 68: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

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

This attribute is optional.

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

This attribute is optional.

its:dir 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 element

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.

Adding Features 68

Page 69: BlackBerry WebWorks 2.1-Development Guide

Parent elements

<widget>

Child elements

None

Occurrences

One

Attributes

You can use the following attributes:

Attribute Description

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

This attribute is required.

rim:allowInvokeParams 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.

This attribute is optional.

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

This attribute is optional.

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

This attribute is optional.

Adding Features 69

Page 70: BlackBerry WebWorks 2.1-Development Guide

Examples: Specifying a start page

<content src="startpage.html" />

description element

Syntax

<description>string</description>

Description

The <description> element specifies a human-readable description for a BlackBerry WebWorks application.

You can access this element by using the blackberry.app.description property that is provided in the BlackBerry WebWorks API.

Parent elements

<widget>

Child elements

None

Occurrences

One

Attributes

You can use the following attributes in this element:

Attribute Description

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

This attribute is optional.

its:dir 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.

Adding Features 70

Page 71: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

You can use this attribute for localization.

Example

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

icon element

Syntax

<icon src="string" />

Description

The <icon> element specifies a custom icon for a BlackBerry WebWorks application. The icon that you specify in the src attribute is the application's icon that appears on the Home screen of the BlackBerry device. The icon must meet the requirements for custom or default icons.

This element is optional.

Parent elements

<widget>

Child elements

None

Occurrences

Zero or more

Attributes

You can use the following attributes in this element:

Adding Features 71

Page 72: BlackBerry WebWorks 2.1-Development Guide

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.

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

This attribute is optional.

BlackBerry 10 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.

If you do not specify an icon for your BlackBerry 10 application, the BlackBerry WebWorks Packager uses the default application icon.

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.

<icon src="icon-86.png" /><icon src="icon-150.png" />

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 non-localized 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/en-US", "/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

Adding Features 72

Page 73: BlackBerry WebWorks 2.1-Development Guide

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 non-localized image files that you specified in the icon element. You can store the non-localized 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 non-localized icon image located in the root.

Example: Using localized icons

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.

Icon elements in the config.xml file:

<icon src="icon-86.png" /><icon src="icon-150.png" />

File and folder structure:

locales/de/icon-86.pnglocales/de/icon-150.pnglocales/fr/icon-86.pngicon-86.pngicon-150.png

license element

Syntax

<license>string</license>

Description

The <license> element specifies the end user license agreement or a copyright statement for a BlackBerry WebWorks application. 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 in the application.

Parent elements

<widget>

Adding Features 73

Page 74: BlackBerry WebWorks 2.1-Development Guide

Child elements

None

Occurrences

Zero or one

Attributes

You can specify the following attributes for this element:

Attribute Description

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

This attribute is optional.

its:dir 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 The href attribute specifies a web address for a web page that contains content or license information.

This attribute is optional.

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

Adding Features 74

Page 75: BlackBerry WebWorks 2.1-Development Guide

SOFTWARE.</license>

name element

Syntax

<name>string</name>

Description

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

If you do not specify a name element, the application is not valid. For BlackBerry 10 applications, 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.

Parent elements

<widget>

Child elements

None

Occurrences

One

Attributes

You can use the following attributes in this element:

Attribute Description

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

This attribute is optional.

Adding Features 75

Page 76: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

its:dir 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>

platform element

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

Parent elements

<widget>

Child elements

• <icon>• <preference>• <rim:invoke-target>• <rim:permissions>• <rim:splash>

Adding Features 76

Page 77: BlackBerry WebWorks 2.1-Development Guide

Occurrences

Zero or more

Features

To specify a particular platform that your application is targetting, use the following associated attribute. In all cases, the name value is case insensitive.

Attribute Description

name Specifies the platform name. In a BlackBerry WebWorks app, this attribute should always have a 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 77

Page 78: BlackBerry WebWorks 2.1-Development Guide

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 element

Syntax

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

Description

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

Parent elements

<widget>

Child elements

None

Occurrences

Zero or more

Features

To specify a particular feature for your application, use the following associated attributes. In all cases, the name value is case insensitive.

Adding Features 78

Page 79: BlackBerry WebWorks 2.1-Development Guide

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

AutoHideSplashScreen Hides the splash screen for your application. The value can be "true" or "false",

with "true" being the default. When false, the splash screen is displayed until splashscreen.hide() is invoked.

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

Adding Features 79

Page 80: BlackBerry WebWorks 2.1-Development Guide

Preference Description

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

HideKeyboardFormAccessoryBar When enabled, hides the row of buttons (Previous, Next, and Submit) that is 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".

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

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 80

Page 81: BlackBerry WebWorks 2.1-Development Guide

Preference Description

The value attribute must specify a value of "disable".

Example

<preference name="WebSecurity" value="disable" />

rim:invoke-target element

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

Parent elements

<platform>

Adding Features 81

Page 82: BlackBerry WebWorks 2.1-Development Guide

Child elements

See element structure below.

Occurrences

Zero or more

Element structure

All child elements of the rim:invoke-target element have the rim: namespace prefix by default. Therefore, you do not have to prepend any of the other child elements of the rim:invoke-target element with rim:.

Element Parent Description

rim:invoke-target platform Registers a bound and/or unbound invocation against an application type.

This is an optional element.

rim:type rim:invoke-target Describes the type of invocation of rim:target. The type can be one of the following:

• application• viewer

This element is required for the parent element.

rim:require-source-permissions

rim:invoke-target Lists the capabilities that the invoking application must support.

This is an optional element.

rim:filter rim:invoke-target Describes a set of instances in which the target may receive an unbound invocation.

This is an optional element.

rim:action rim:filter Contains a valid action for the target to perform on the data.

This element is required for the parent element.

Adding Features 82

Page 83: BlackBerry WebWorks 2.1-Development Guide

Element Parent Description

rim:mime-type rim:filter Contains a valid MIME type for the data (wildcard characters are allowed).

This element is required for the parent element.

rim:property rim:filter Contains a valid prefix for URIs or suffix for file extensions of the URI provided during invocation.

This is an optional element.

Element attributes

Attribute Defined in Description

rim:id rim:invoke-target 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.targetThis attribute is required.

rim:var rim:property Specifies extra properties that can be used to register an unbound invocation. The invocation framework supports invocation by URI or by file extensions. The value can be uris or exts.

This attribute is optional.

rim:value rim:property Specifies the property values to use when registering an unbound

Adding Features 83

Page 84: BlackBerry WebWorks 2.1-Development Guide

Attribute Defined in Description

invocation. This attribute is optional.

Examples of URI values include (but are not limited to):

• http://• https://• ftp://Examples of file extension values include (but are not limited to):

• html• htm• php• jsp• asp

Examples

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

Adding Features 84

Page 85: BlackBerry WebWorks 2.1-Development Guide

.

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

Adding Features 85

Page 86: BlackBerry WebWorks 2.1-Development Guide

</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; } } return queryParamResult;}

rim:permissions element

Syntax

<rim:permissions> <rim:permit> ...</rim:permit></rim:permissions>

Adding Features 86

Page 87: BlackBerry WebWorks 2.1-Development Guide

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

Parent elements

<platform>

Child elements

<rim:permit>

Occurrences

One

Example: Specifying permissions

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>

Adding Features 87

Page 88: BlackBerry WebWorks 2.1-Development Guide

rim:permit element

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

Parent elements

<rim:permissions>

Child elements

None

Occurrences

One or more

Attributes

You can specify the following attributes:

Attribute Description

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

Adding Features 88

Page 89: BlackBerry WebWorks 2.1-Development Guide

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.

Functionality or Capabilities

Permission value Description

Camera use_camera Allows this app to take pictures, record video, and use the camera's flash.

Device information read_device_identifying_information

Allows this app to access device identifiers such as serial number and PIN.

Location information access_location_services Allows this app to access the device’s current or saved locations. This permission replaces read_geolocation, and includes access to location information from GPS, Wi-Fi, and cell ID.

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.

Push _sys_use_consumer_push Allows this app to use push functionality.

Run in background run_when_backgrounded Allows this app to run JavaScript and networking in the background.

Adding Features 89

Page 90: BlackBerry WebWorks 2.1-Development Guide

Functionality or Capabilities

Permission value Description

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.

BBM Social Platform bbm_connect Allows this app to connect to BBM so that the user can chat or update their BBM profile without leaving the BBM connected app.

Email and PIN messages

access_pimdomain_messages Allows this app to access email and PIN messages, including viewing, creating, sending, and deleting messages.

Contacts access_pimdomain_contacts Allows this app to access contacts, including viewing, creating, and deleting contacts.

Calendar access_pimdomain_calendars Allows this app to access the calendar, including viewing, adding, and deleting appointments.

Notifications post_notifications Allows this app to post a notification to the notification area of the screen.

Example: Specifying permissions

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

Adding Features 90

Page 91: BlackBerry WebWorks 2.1-Development Guide

. <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:splash element

Syntax

<rim:splash src="file name" />

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:

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

Parent elements

<platform>

Child elements

None

Occurrences

Specify 0 or more <feature> elements withina <widget> element.

Adding Features 91

Page 92: BlackBerry WebWorks 2.1-Development Guide

Example: Specifying splash screen images for multiple screen sizes

<widget xmlns:rim="http://www.blackberry.com/ns/widgets">... <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><widget>

Using localized splash images

To use localized image files for the splash screen, the image files must be :

• Named the same as the non-localized 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/en-US", "/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 non-localized image files that you specified in the <rim:splash> element. You can store the non-localized 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 non-localized icon image located in the root.

Example: Localized files and folder structure

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.

locales/de/splash-1024x600.pnglocales/de/splash-600x1024.pnglocales/de/splash-1280x768.pnglocales/de/splash-768x1280.pnglocales/fr/splash-1280x768.png

Adding Features 92

Page 93: BlackBerry WebWorks 2.1-Development Guide

locales/fr/splash-768x1280.pngsplash-1024x600.pngsplash-600x1024.pngsplash-1280x768.pngsplash-768x1280.png

Creating headless WebWorks appsAs 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 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

Adding Features 93

Page 94: BlackBerry WebWorks 2.1-Development Guide

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 port-directed 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.

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:

Adding Features 94

Page 95: BlackBerry WebWorks 2.1-Development Guide

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:

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.

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.

Adding Features 95

Page 96: BlackBerry WebWorks 2.1-Development Guide

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.

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.

Adding Features 96

Page 97: BlackBerry WebWorks 2.1-Development Guide

3. In the Select panel, expand General, select Existing Projects into Workspace, and then click Next. The IDE displays the Import Projects panel.

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 97

Page 98: BlackBerry WebWorks 2.1-Development Guide

App integrationThe BlackBerry 10 OS provides the invocation framework to bring a powerful cross-application integration capability 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 provides the capability for your application to launch another application from within your app's UI. This capability provides for better multitasking and a smooth application flow, and allows the BlackBerry device user to continue with a task without losing focus. You can also integrate your application with core applications. For example, email, file manager, pictures, music, and BBM can be integrated and called by your application when needed.

Cards enhance the invocation framework's capabilities. Cards allow you to launch a particular screen of another application in the form of a card, instead of launching the full application. Cards also use fewer system resources and offer a great user experience.

Related resources

Web-based training

• Invocation Framework

Design guidelines

• Cards• Sharing and the Invocation

Framework

Sample apps

• Invoke Client• Invoke Target• Social Invocation

Invocation framework

The invocation framework in BlackBerry 10 OS allows one application to invoke another by sending it a message. When an application calls for an invocation on some content, the invocation framework responds with appropriate applications that can carry out a requested action on that particular content. For example, using the invocation framework for your app can allow the BlackBerry device user to perform a set of actions on a piece of content such as a .doc file. These actions will allow the user to share, open, or send the .doc file in an email using another application from within the UI of your app. In this example, your application is the client application in the invocation framework and the application that shares, opens, or sends the .doc file as an email is the target application.

Adding Features 98

Page 99: BlackBerry WebWorks 2.1-Development Guide

Depending on your application's functionality, the invocation framework can allow your application to become more discoverable if you register your app as a target application. This allows other applications to invoke your application without first knowing about your application.

An invocation request is the message structure that is passed between a client application and a target application. 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 application when the target is invoked. The framework takes care of launching the target application if it is not already running. An invocation request contains:

• Target: The unique ID of the target application• Action: The action that should be performed on the data• Data: The data that should be acted upon

Invocation targets

An application that is registered with the invocation framework is called a target application. Other applications can invoke a target application by using the invocation framework. Upon invocation, the user's context switches to the target application.

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 application developer and is guaranteed to be unique when the application 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 define various tasks which your application 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 applications of the BlackBerry 10 OS (for example, registering your app as a target would allow an image in the Pictures app to be shared with your app).

All 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

Adding Features 99

Page 100: BlackBerry WebWorks 2.1-Development Guide

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 the JSON format.

Sending invocationBound invocation

The following image show how a client application can use the bound invocation to invoke a target application of its choice. In this case, App 2 opens the document contained in the client application.

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

Adding Features 100

Page 101: BlackBerry WebWorks 2.1-Development Guide

Target discovery

After learning about how to send an invocation, you must be wondering how you can determine what targets are available on the device. This section deals with exactly that. You can hard code the target application 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 applications to declare the types of invocation they support. When a client application queries the invocation framework, the framework uses the target app's filter to describe the kind of target it is looking for and the data it has to offer.

The quality of the results is generally dependent on how specific the target query request is. A target query request should consist of the URI and the MIME type. If the MIME type is left out, the framework tries to determine the type using the URI.

A client application 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 which 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 application 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 application'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 process.

The following code demonstrates a target query request in which a client application 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>");}

Adding Features 101

Page 102: BlackBerry WebWorks 2.1-Development Guide

Unbound invocation

In this section, you will learn how the invocation framework can make invoking a target application easy, by removing the need to query. Instead of sending a target query request to determine the available targets, the client application 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, the framework searches for and invokes a suitable target application for you.

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

To find the best candidate, the framework first uses a brokering process. It applies a set of rules to determine which target applications support the client application'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 item, since only the data is sent. The framework determines the type of target and the action to be performed.

If you don't define the action parameter, the invocation framework tries to find an appropriate target application for the bb.action.VIEW action. If no suitable target application is found for bb.action.VIEW, the invocation framework falls back to determine an appropriate target application that supports bb.action.OPEN. If still no suitable target application is available for bb.action.OPEN, the invoke request is unsuccessful.

The following sample code shows how you can easily create an unbound invocation. The sample code invokes the most suitable target application to handle the image.png file, 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 applications. An invocation request describes the data that can be acted upon by the target application.

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

Adding Features 102

Page 103: BlackBerry WebWorks 2.1-Development Guide

request. When data is sent as part of the invocation message, it is placed in the data attribute. 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 application to handle the message.

blackberry.invoke.invoke({target: "com.example.image.view ",action: "bb.action.OPEN",type: "text/plain",data: "Hello World!",}, onSuccess, onError);

File handling

This section contains information on how invocation framework handles file transfers and the type of files supported.

File extensions

The invocation framework supports file handling based on the file extension. The file extensions can be defined as file:// within the scheme parameter when the data is referenced by the URI. The invocation framework also supports the declaration of the exts attribute within the target filters. If in an invocation request, the URI is suffixed with a file extension that matches any of the file extensions declared in the exts attribute, then a given target filter will match with that invocation request. When the exts attribute is defined, the target filter implicitly supports the uris="file://" for those declared extension cases.

The exts attribute is only applied if the accompanying uris contain a file:// based uri. Also, combining exts and specific MIME types in a target filter means that both must be specified by a client application for the target filter to successfully match with an invocation request. The best practice in most cases is to define the exts related target filters as a separate declaration, where uris is file:// and the MIME type is a wildcard character (*).

File transfer

Sending an invocation request with a file:// URI to pass files succeeds only if the target application can access the file. The platform supports the use of a shared area in the file system to share data between the client and target applications. However, to send sensitive data to a target application, a client application can use the invocation framework's file transfer handling feature. 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 by default it creates a read/write copy of the file in a private inbox for the target application. The client application can specify the file transfer mode attribute to override this behavior. Invocation requests support the following modes:

Adding Features 103

Page 104: BlackBerry WebWorks 2.1-Development Guide

File transfer mode Description

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

CopyReadOnly Create a read-only copy of the file in the target's private inbox.

CopyReadWrite Create a read/write copy of the file in the target's private inbox.

Link Create a hardlink to the file in the target application's private inbox. When Link is specified, the file must have read/write permissions. In addition, if the file has read/write permissions then 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 type

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.ms-excel, application/msword, application/vnd.ms-powerpoint

filelist/mixed Any

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 to list://. After you set the type and URI, you can assign the list of individual file URIs to the data section using the following JSON format:

[ { 'uri':<file-uri>, 'type':<mime-type>,

Adding Features 104

Page 105: BlackBerry WebWorks 2.1-Development Guide

'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 JSON formatted metadata.

No test metadata

Receiving invocation

You can configure your application to receive invocation request from other applications. To receive an invocation request, your application must support invocation targets. To support invocation targets, you must declare your targets in the config.xml file and handle invocation messages.

Target declaration

In order 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> </icon></invoke-target>

To let the platform know the type of the target, define the <invoke-target-type> element as shown in the example below.

Adding Features 105

Page 106: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

invoke-target id

Uniquely identifies the application as a target. This parameter can also be used by the client applications to perform Bound invocation.

type The type of the target. Applications and cards are supported as types of the target.

name The name of the target application.

image The icon for the target application.

The following sections explain how you can create different kinds of targets. Targets include applications and cards.

Receiving invocations

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>

Adding Features 106

Page 107: BlackBerry WebWorks 2.1-Development Guide

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 datafunction onInvoked(invokeRequest) {}

Handling launch through invocation

An important thing to consider when you write an application target is how an application is launched. Usually an application launches when the BlackBerry device user taps the app icon on the home screen. However, with the invocation framework the application can also be invoked. So how does an application know whether it was invoked or launched? Here's how your application 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);

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 application to be queried for by other apps and make your application 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:

Adding Features 107

Page 108: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

filter Describes the criteria for this application to be considered for unbound invocations or invocation queries.

action Describes the actions that can be performed on the content. It represents the action that the target supports for the types specified in the type attribute. Include one <action> 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. The type and the subtype can both be specified as a wildcard, within a target filter. For example, a filter can specify image/png, image/* or *.

Adding Features 108

Page 109: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

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 supports the delivery of the data. The URI value may contain the single wildcard character * to indicate that the filter supports any delivery mechanism. If the target application or a card supports the delivery of the data as part of the message body then it should include the data://local URI.

Adding Features 109

Page 110: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

exts Represents the list of file extensions supported by the target. The values specified in this attribute apply only to file:// URIs. When exts are specified in a target filter, they are generally specified in conjunction with MIME type=*. 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, therefore if your target supports a specific set of types, you must specify each of the types in the filter. In cases

Adding Features 110

Page 111: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

where your application 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 type=*.

When you declare a target filter, make sure that your filter description abides by the following 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, and has MIME types set as a wildcard character (*), and has the URI attribute set as data:// or file:// or left unstated, then your application cannot be deployed or installed on the device.

• For a target filter that utilizes the URI file:// and a MIME type wildcard character (*), to successfully register with the invocation framework, you must also specify a file extension value which 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 application uses a target filter declaration that is restricted, then on deployment, the result::failure 884 Restricted Invoke Filter detected error is displayed in the command line tool.

Here are some examples of target filters that successfully register 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 application to be deployed or installed on the device:

Adding Features 111

Page 112: BlackBerry WebWorks 2.1-Development Guide

• 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> <mime-type>*</mime-type> <property var="uris" value="file://"/> <property var="exts" value="jpg,png"/> </filter></invoke-target>

Target selection and brokering

In this section, you will learn how brokering and selection works, to help you determine the best way to configure your target filters.

When a client application 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 applications 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.

Adding Features 112

Page 113: BlackBerry WebWorks 2.1-Development Guide

If the target filter does not 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>, where host and port values are equal to the authority value. The scheme comparison is non case-sensitive while the authority and path sections are case-sensitive. These values are compared in such a way that the uri is considered a match only if any of the values specified in the target filter’s uris attribute is a prefix of the uri specified in the invocation request.

Likewise, 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:

• The URI and MIME type specified in the invocation request match with the target filter's uri and ext.• 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.• The absence of a declared ext in the target filter implies an ext match.• 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 for a MIME type match.• If the invocation request does not specify a uri while the target filter declared a matching MIME type but

either did not declare a uri, which implies that the data attribute is data://local, or explicitly declared the uri as uri=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, while a match without wildcard characters is considered the strongest match.

Adding Features 113

Page 114: BlackBerry WebWorks 2.1-Development Guide

• 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://scheme format.

• If more than one target filter has a matching ext, then the filter that the system 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 application to export its application screen to another application. Unlike an application, which 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 application and does not appear separately in Active Frames. An application can embed only one card at a time. However, one card can embed another card, which allows the application to create a stack of cards that appear as part of the client application. Although the card appears as part of the client application, it maintains its own process and security context. In the following sections, you will learn how to create and use cards in your application, as well as how to expose them to other apps.

Card styles

When an application 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 application: 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 application and the card, how peeking is handled, and determines the general task that a card performs. Each card style has associated visual style guidelines.

Picker Composer Previewer

Card transitions

A card transitions on or off the screen in a beautiful animation. The cards appears on the screen as either sliding in 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.

Adding Features 114

Page 115: BlackBerry WebWorks 2.1-Development Guide

Transition style of composers and pickers

Transition style of previewers

Adding Features 115

Page 116: BlackBerry WebWorks 2.1-Development Guide

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 application at the bottom of the

stack of cards.

Parent peek Root peek

Adding Features 116

Page 117: BlackBerry WebWorks 2.1-Development Guide

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

To verify a great user experience, here are some guidelines to consider if you want to use cards in your app:

Description Composer Previewer 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.

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

Card invocation

Cards enhance the invocation framework's capabilities by allowing applications to share the UI and the application logic with other applications. You send a request to invoke a card in the same way as an invocation request for an application, which means that everything that you learned about sending an invocation request,

Adding Features 117

Page 118: BlackBerry WebWorks 2.1-Development Guide

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.invokewebworks plugin add com.blackberry.invoke.card

Here's how you can use the invocation framework to import a card from another application:

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 platform verifies that the client application is not already parenting a card. Unlike an application, a card may continue to exist in multiple instances, but a parent application (or a card) can parent only one card at a time. This is important to consider, since multiple instances of a card may be running at the same time.

Cards support a "fire and forget" import model. However, for applications that require notifications and additional feedback, cards also provide peek notifications and response data.

Listen for peek events

Cards offer a parent card or an application the ability to receive notifications when a user peeks at another card. This is important if you want your application to display content differently during a peek event. Here is how you can enable your application 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);

Adding Features 118

Page 119: BlackBerry WebWorks 2.1-Development Guide

Listen for a card response message

A card can send a response message to the parent application when a card completes its task. For example, a picker card can return the data, that a user selects, to the client application. Here's how you can listen for card response messages:

function onCardClosedHandler(info) { console.log("Card was closed: " + info);}document.addEventListener('onChildCardClosed',onCardClosedHandler);

Typical card usage for previewers and many composers does not involve a response. Therefore, a best practice is to design your previewer and composer cards in such a way that any response is optional.

Close a card

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

blackberry.invoke.closeChildCard();

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

Creating your own cards

You just learned how you can integrate the functionality of other applications with yours by using cards. However, a great way to get your application noticed is to export your application's cards, so other applications can import them. Creating cards is similar to creating a small, focused application. One of the key differences, however, is that unlike an application, a card can have multiple instances running at the same time. The BlackBerry 10 OS creates a new instance for each client application. 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 application's functionality to other applications.

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 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 and access across different instances of your card. Any cards your application exports are packaged in the same .bar file as the application.

Register a card target

Since 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 exactly the same as registering application targets 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,

Adding Features 119

Page 120: BlackBerry WebWorks 2.1-Development Guide

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 applications, cards are packaged and identified as invocation targets in the config.xml file. Here's an example that shows you how to declare cards:

<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 application is notified. While the card closes itself, it can also send a response message to the parent application.

Prepare your card for pooling

You can create your cards in such a way that 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 the user is viewing one email message 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. Once 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 notification it should clear its current state and listen for future invocations. In addition, cards must be written to support multiple instances which run simultaneously within the same sandbox.

Second, if an application 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 application or card may be invoked as any of these targets.

Prepare your cards for resizing and rotation

A card’s orientation is aligned with the orientation of the parent application. If the parent application's orientation is fixed, any child cards in the stack also have a fixed orientation.

Adding Features 120

Page 121: BlackBerry WebWorks 2.1-Development Guide

Note:

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

Card security

Cards have their own identity and sandbox environment that is shared with all instances of the card. Like applications, 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.

Menu integration

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 OS device: action menu and context menu.

In this section, you will learn how to add menus to your app and how to use the invocation framework to display your application in the context menu of other apps. You will also learn about configuring 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.

Meanwhile, to learn more about the action and application 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 OS. It is presented when the user presses and momentarily holds a particular area of the application UI. The context menu is divided into two sections that offer actions related to the content selected by the user.

The upper half of the context menu is the application section, which contains all the actions that the application adds. For example, in the following image on the right, Add as friend, Call, Email, and Text actions are all application actions.

The lower half of the context menu is the platform section, which contains all the actions that the BlackBerry 10 OS adds automatically. In the following image on the right, Call, Email, Text, Share, Set as and Open in are platform actions.

Adding Features 121

Page 122: BlackBerry WebWorks 2.1-Development Guide

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 functionality of your application to the platform section of the context menu of other apps. Enabling your application to appear in the platform section allows it greater visibility among other applications and is good for the publicity of your app. You can add a specific functionality of your application 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.SETIt is important to choose the action that suits your application's needs. For example, if your application 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, 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 application:

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

Adding Features 122

Page 123: BlackBerry WebWorks 2.1-Development Guide

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

Target selection menu

Target selection menu displays when the user selects the share action on the context menu. The target selection menu contains two sections: suggestions and a list displaying all the available targets for sharing.

Adding Features 123

Page 124: BlackBerry WebWorks 2.1-Development Guide

Adding icons to the target selection menu

If your application is declaring itself as a target for core menu actions (OPEN, SHARE, SET), you must package your application with two images of size 81 x 81 pixels and 358 x 358 pixels respectively. These images should typically show your application's icon. The image of size 81 x 81 pixels is used in the list that displays all 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 BBM and Text Messages applications look in the list section:

Here's how the images for Email and Text Messages applications look in the suggestions section:

Note: As a best practice, remember to fill any transparent pixels in your image with color. This 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 application as shown in the code below.

...<icon> <image public="true"> icon_small.png</image> <image public="true"> icon_big.png</image></icon>...

Adding Features 124

Page 125: BlackBerry WebWorks 2.1-Development Guide

Invoking apps using active text

You can add custom active text elements that invoke your app by registering string patterns and application targets. A custom active text element for your app is specified using a Uniform Resource Identifier (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 technology, 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. This can be the scheme portion alone (for example, myuri:) or it can be 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>

</invoke-target>

Attribute Description

<invoke-target>

The invocation parameters of your app. For more information about <invoke-target>, see Target declaration.

<type> Can be APPLICATION or CARD.

Adding Features 125

Page 126: BlackBerry WebWorks 2.1-Development Guide

Attribute Description

<filter> Describes the criteria for this application 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.

<invoke-target-pattern> and <pattern-value>

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

Invoking core applications

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

Adobe Reader Maps

Adding Features 126

Page 127: BlackBerry WebWorks 2.1-Development Guide

BBM

Media Player

BlackBerry Browser

Miracast card

BlackBerry World

NFC

Bluetooth

Phone

Calendar Pictures

Camera

Picture editor

Clock

Remember

Adding Features 127

Page 128: BlackBerry WebWorks 2.1-Development Guide

Contacts Search

Device Monitor

Settings

Docs to Go Text Messages

Email

Twitter

Facebook Video editor

Foursquare Voice note

LinkedInYouTube

Adobe Reader

Opening a .pdf file

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

Adding Features 128

Page 129: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID com.rim.bb.app.adobeReader

Action bb.action.OPEN

URI file:///path/to/my/content.pdf

MIME type application/pdf

File extensions .pdf

Here are the invocation attributes you use to open a .pdf file in a previewer card:

Attribute Value

Target ID com.rim.bb.app.adobeReader.viewer

Action bb.action.VIEW

URI file:///path/to/my/content.pdf

MIME type application/pdf

File extensions .pdf

BBM

Sharing a file with BBM

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

Adding Features 129

Page 130: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.bbm.sharehandler

Action bb.action.SHARE

URI file:///path/to/my/content.doc

Opening the BBM application

Here are the invocation attributes you use to open the BBM application:

Attribute Value

Target ID sys.bbm

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

Target ID sys.bbm.imagehandler

Action bb.action.SET

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

Sharing text with BBM

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

Adding Features 130

Page 131: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.bbm.sharehandler

Action bb.action.SHARE

MIME type text/plain

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

Target ID sys.bbgroups.sharehandler

Action bb.action.SHARE

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

Target ID sys.bbm.sharehandler

Action bb.action.BBMCHAT

Adding Features 131

Page 132: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

URI pin:<pin>

Note:

This invocation action will either display 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 Value

Target ID sys.bbm.sharehandler

Action bb.action.INVITEBBM

URI pin:<pin>

Starting a BBM audio or a video chat

Here are the invocation attributes you use to start a BBM audio or a video chat with a contact:

Attribute Value

Target ID sys.service.videochat

Action bb.action.OPEN

Data dest=<BlackBerry ID or PIN of contact>&video=<0 or 1>

Adding Features 132

Page 133: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

The value 0 is specified for an audio call and 1 is specified for a video call. For example, [email protected]&video=1

Invoking your BBM Channel

Here are the invocation attributes you use to invoke your BBM Channel from within your app:

Attribute Value

Target ID sys.bbm.channels.card.previewer

Action bb.action.OPENBBMCHANNEL

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

Target ID sys.bbm.channels.sharehandler

Action bb.action.SHARE

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

Adding Features 133

Page 134: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.bbm.sharehandler

Action bb.action.BBMCONF

MIME type vnd.bb.bbm/contactlist

Data must be sent in JSON format as shown below:

"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 the 10.1 (and later) version 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.browserMIME type Any valid MIME type value

Action bb.action.OPENURI • http://

• https://• ftp://

Adding Features 134

Page 135: BlackBerry WebWorks 2.1-Development Guide

Opening local content

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

Attribute Value

Target ID sys.browser MIME type • text/html

• application/xhtml+xml• image/svg+xml

Action bb.action.OPENFile extensions • htm

• html• xhtml• svg

URI file://

BlackBerry World

Opening a specific page in BlackBerry World

Here are the invocation attributes you use to open a specific page in BlackBerry World:

Attribute Value

Target ID sys.appworld

Action bb.action.OPEN

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

Page URI

Home page appworld://

Adding Features 135

Page 136: BlackBerry WebWorks 2.1-Development Guide

Page URI

Content details for an ID (for example, works for games, apps, albums, tracks, movies, TV show series, or TV show season or episode)

appworld://content/<contentid>

Category listing for an ID appworld://category/<categoryid> Editorialized Merchandising Unit 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://<???>

Bluetooth

Sharing a local file

Here are the invocation attributes you use to invoke a Bluetooth card to share a local file:

Attribute Value

Target ID sys.btviewer

Action bb.action.SHARE

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

Adding Features 136

Page 137: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

MIME type Any valid MIME type value, such as audio/mp3, image/jpg, 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 you use to launch a calendar card to create an event:

Attribute Value

Target ID sys.pim.calendar.viewer.eventcreate

Action bb.action.CREATE

MIME type text/calendar

Description Data (optional)

Account ID of the event unsigned int accountId Folder ID of the event unsigned int folderId

List of participant email addresses "participants":["[email protected]","[email protected]"]

Adding Features 137

Page 138: BlackBerry WebWorks 2.1-Development Guide

Description Data (optional)

Subject of the event "subject":"<text>"Body of the event "body":"<text>"Start time of the event String startTimeLocation of the event QString locationDuration of the event int duration

Picking an existing event

Here are the invocation attributes you use to launch a calendar card to pick an existing event:

Attribute Value

Target ID sys.pim.calendar.viewer.nav

Action bb.calendar.PICK

MIME type text/calendar

Card response:

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 you use to launch a calendar card to edit an existing event:

Adding Features 138

Page 139: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pim.calendar.viewer.eventcreate

Action bb.calendar.EDIT

MIME type text/calendar

Description Data

Account ID of the existing event unsigned int accountIdFolder ID of the event (optional) unsigned int folderIdEvent ID unsigned int eventIDStart time of the event (optional) QString startTime

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

Viewing an .ics file

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

Attribute Value

Target ID sys.pim.calendar.viewer.ics

Action bb.action.OPEN

MIME type text/calendar

URI file:///path/to/my/file/filename.ics

Adding Features 139

Page 140: BlackBerry WebWorks 2.1-Development Guide

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

Account ID of the existing event unsigned int accountId

Opening the calendar app

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

Attribute Value

Action bb.calendar.OPENMIME type text/calendarData "data":"file:///path/to/file.txt"

Query name Query value Description

view • monthly• agenda• people• schedule• weekly

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

Adding Features 140

Page 141: BlackBerry WebWorks 2.1-Development Guide

Viewing an existing event

Here are the invocation attributes you use to launch a calendar card to view an existing event:

Attribute Value

Target ID sys.pim.calendar.viewer.ics

Action bb.calendar.OPEN

MIME type text/calendar

Description Data (optional)

Account ID of the existing event unsigned int accountIdEvent ID of the existing event unsigned int eventIdStart 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"

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

Attribute Value

Action bb.calendar.VIEWMIME type text/calendarData "data":"file:///path/to/file.txt"

Query name Query value Description

accountId <account-id> Account ID of the event.

Adding Features 141

Page 142: BlackBerry WebWorks 2.1-Development Guide

Query name Query value Description

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.

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

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.

Adding Features 142

Page 143: BlackBerry WebWorks 2.1-Development Guide

Reason Data Description

close Include an error message in the data attribute, if applicable.

This response is sent 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 Include a full path to the saved file.

This response is returned if a card is closed after a user takes a picture or records a video. The captured file is returned in the data field of the message.

Opening the Camera application

Here are the invocation attributes you use for invoking the Camera application:

Attribute Value

Target ID sys.camera.app

MIME type image/jpeg or video/mp4

Action bb.action.CAPTURE

Data photo, video, or full (full is the default if nothing is specified)

When the camera application 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 application at any time. For example, a user can choose between the photo capture mode, video capture mode, and the timeshift mode. Also, if an

Adding Features 143

Page 144: BlackBerry WebWorks 2.1-Development Guide

instance of the Camera application is already running, it is displayed instead of a new instance being launched. 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:

Attribute Value

Target ID bb.clock.launcher

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

Target ID sys.pim.contacts.app

Action bb.action.OPEN

Adding Features 144

Page 145: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

MIME type application/vnd.blackberry.contact.id

Data Contact ID integer.

Adding a new contact

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

Attribute Value

Target ID sys.pim.contacts.app

Action bb.action.ADDTOCONTACT

MIME type application/vnd.blackberry.string.phone, application/vnd.blackberry.string.email, application/vnd.blackberry.string.pin

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

Target ID sys.pim.contacts.card.viewer

Adding Features 145

Page 146: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Action bb.action.VIEW

URI 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):

Attribute Value

Target ID sys.pim.contacts.app

Action bb.action.OPEN

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

Target ID sys.pim.contacts.card.composer

Action bb.action.CREATE

Editing an existing contact

Here are the invocation attributes you use to edit an existing contact using a contact composer card:

Adding Features 146

Page 147: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pim.contacts.card.composer

Action bb.action.EDIT

MIME type application/vnd.blackberry.string.contact, application/contact

Data Contact ID integer

Here are the invocation attributes you use to view a contact using a contact previewer card:

Attribute Value

Target ID sys.pim.contacts.card.viewer

Action bb.action.VIEW

MIME type application/contact, application/vnd.blackberry.string.contact, application/vnd.blackberry.contact.id

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

Target ID sys.pim.contacts.setcontactpicture

Adding Features 147

Page 148: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Action bb.action.SET

URI file:// (e.g. “file:///path/to/photo.jpg”)

Device Monitor

Opening the Device Monitor

Here are the invocation attributes you use for the Device Monitor app:

Attribute Value

Target ID sys.SysMon.app

Action bb.action.OPEN

MIME type You should specify a wildcard character *

Here are the invocation attributes you use for the Device Monitor card:

Attribute Value

Target ID sys.SysMon.card

Action bb.action.VIEW

MIME type You should specify a wildcard character *

Here's a list of URIs you can use to invoke the Device Monitor card or the app:

Adding Features 148

Page 149: BlackBerry WebWorks 2.1-Development Guide

Setting URIs

CPU devicemonitor://cpu

Battery devicemonitor://batteryStorage devicemonitor://storage

Memory devicemonitor://memory

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:

Adding Features 149

Page 150: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.sheettogo.previewer

Action bb.action.VIEW

URI file:///path/to/my/content.xls

MIME type application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.template, application/vnd.ms-excel.sheet.macroEnabled.12, application/vnd.ms-excel.template.macroEnabled.12

File extensions .xls, .xlt, .xlsx, .xltx, .xlsm, .xltm

Here are the invocation attributes you use to open a spreadsheet file in the Docs to Go application:

Attribute Value

Target ID sys.dxtg.stg

Action bb.action.OPEN

URI file:///path/to/my/content.xls

MIME type application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.template

Adding Features 150

Page 151: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

, application/vnd.ms-excel.sheet.macroEnabled.12, application/vnd.ms-excel.template.macroEnabled.12

File extensions .xls, .xlt, .xlsx, .xltx, .xlsm, .xltm

Opening a presentation

Here are the invocation attributes you use to open a presentation in a previewer card:

Attribute Value

Target ID sys.slideshowtogo.previewer

Action bb.action.VIEW

URI file:///path/to/my/content.ppt

MIME type application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.presentationml.template, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.ms-powerpoint.presentation.macroEnabled.12, application/vnd.ms-powerpoint.template.macroEnabled.12, application/vnd.ms-powerpoint.slideshow.macroEnabled.12

Adding Features 151

Page 152: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

File extensions .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 application:

Attribute Value

Target ID sys.dxtg.stg

Action bb.action.OPEN

URI file:///path/to/my/content.ppt

MIME type application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.presentationml.template, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.ms-powerpoint.presentation.macroEnabled.12, application/vnd.ms-powerpoint.template.macroEnabled.12, application/vnd.ms-powerpoint.slideshow.macroEnabled.12

File extensions .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:

Adding Features 152

Page 153: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.wordtogo.previewer

Action bb.action.VIEW

URI file:///path/to/my/content.doc

MIME type application/msword, text/plain, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.wordprocessingml.template, application/vnd.ms-word.document.macroEnabled.12, application/vnd.ms-word.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 application:

Attribute Value

Target ID sys.dxtg.stg

Action bb.action.OPEN

URI file:///path/to/my/content.doc

MIME type application/msword, text/plain, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.wordprocessingml.templ

Adding Features 153

Page 154: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

ate, application/vnd.ms-word.document.macroEnabled.12, application/vnd.ms-word.template.macroEnabled.12

File extensions .doc, .dot, .txt, .docx, .dotx, .docm, .dotm

Email

Sharing a file

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

Attribute Value

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.SHARE

URI file:///path/to/file

MIME type Any valid MIME type value

Sharing an .ics file

Here are the invocation attributes you use to share an .ics file:

Attribute Value

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.SHARE

Adding Features 154

Page 155: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

URI file:///path/to/event.ics

MIME type text/calendar

Sharing text

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

Attribute Value

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.SHARE

MIME type text/plain

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

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.SHARE

URI list://

MIME type filelist/[subtype]

Adding Features 155

Page 156: BlackBerry WebWorks 2.1-Development Guide

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:

Attribute Value

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.OPEN, bb.action.SENDEMAIL

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:[email protected][email protected]

If you want to prepopulate the CC, BCC, subject, and the message body fields, use the following format:

mailto:[email protected][email protected]&[email protected]&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 Value

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.COMPOSE

Adding Features 156

Page 157: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

MIME type message/rfc822

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

{ "to" : ["[email protected]", "[email protected]"], "accountid" : 1234, "cc" : ["[email protected]", "[email protected]"], "bcc" : ["[email protected]", "[email protected]"], "subject" : "Some punctuation. Symbol in the $ubject!!", "body" : "HI! Here is some more stuff.\n\n14% of emails have #1 newline or 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 Value

Target ID sys.pim.uib.email.hybridcomposer

Action bb.action.REPLY, bb.action.REPLYALL, bb.action.FORWARD

MIME type 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:

Adding Features 157

Page 158: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pim.uib.email.previewer

Action bb.action.VIEW

MIME type message/rfc822

The URI points to the message that is viewed and is sent in the following format:

pim:message/rfc822:[accountID]:[messageID]

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 Value

Target ID Facebook

Action bb.action.SHARE

MIME type text/plainURI 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:

Adding Features 158

Page 159: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID Facebook

Action bb.action.SHARE

URI file:///path/to/content.pngFile 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, .vob, .wmv

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 Value

Target ID Facebook

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

Adding Features 159

Page 160: BlackBerry WebWorks 2.1-Development Guide

Entry Description

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",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 Value

Target ID com.foursquare.blackberry.sso.card

Action bb.action.VIEW

MIME type sso/foursquare

Data Client ID (for example, JDHEN48FRJ47FJFRI4FJFRJ4843JRF8484JFKDOEWYU37RUJ)

Adding Features 160

Page 161: BlackBerry WebWorks 2.1-Development Guide

Searching for a venue

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

Attribute Value

Target ID com.foursquare.blackberry.venuesearch.card

Action bb.action.VIEW

MIME type venuesearch/foursquare

URI "foursquare://venues/search?oauth_token=" + accessToken

Exploring a venue

Here are the invocation attributes you use to explore a venue:

Attribute Value

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

URI foursquare://venues/explore

Opening a venue card

Here are the invocation attributes you use to open a venue card:

Adding Features 161

Page 162: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

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

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

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

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

Adding Features 162

Page 163: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

URI foursquare://users/self/update

Opening friend requests

Here are the invocation attributes you use to open the friend requests:

Attribute Value

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

URI foursquare://users/requests

Opening friend suggestions

Here are the invocation attributes you use to open the friend suggestions:

Attribute Value

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

URI foursquare://users/suggest?type=friend

Opening page suggestions

Here are the invocation attributes you use to open page suggestions:

Adding Features 163

Page 164: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

URI foursquare://users/suggest?type=page

Adding friends

Here are the invocation attributes you use to add friends from Contacts, Twitter, Facebook, or Search:

Attribute Value

Target ID com.foursquare.blackberry.uri

Action bb.action.OPEN

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

Target ID LinkedIn

Action bb.action.SHARE

Adding Features 164

Page 165: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

MIME type text/plainURI 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

URI linkedin:contact:<public_URL_of_the_LinkedIn_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.OPENMIME 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.

Adding Features 165

Page 166: BlackBerry WebWorks 2.1-Development Guide

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.

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

Adding Features 166

Page 167: BlackBerry WebWorks 2.1-Development Guide

Attribute Values Description

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 application

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

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 }

Adding Features 167

Page 168: BlackBerry WebWorks 2.1-Development Guide

} ) });

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

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.

Adding Features 168

Page 169: BlackBerry WebWorks 2.1-Development Guide

Attribute Values Description

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.name 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.description or nav_end.properties.description

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

Adding Features 169

Page 170: BlackBerry WebWorks 2.1-Development Guide

Attribute Values Description

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_highways

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" }, "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",

Adding Features 170

Page 171: BlackBerry WebWorks 2.1-Development Guide

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

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

Adding Features 171

Page 172: BlackBerry WebWorks 2.1-Development Guide

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.VIEWURI • 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.

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

A Miracast card can be invoked 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.

Adding Features 172

Page 173: BlackBerry WebWorks 2.1-Development Guide

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 Value

Target ID sys.miracastviewer

Action bb.action.VIEW

MIME type application/vnd.rim.miracast.showon

Playing content on a Miracast device

In PlayOn mode, your application 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 Value

Target ID sys.miracastviewer

Action bb.action.VIEW

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 Value

Target ID sys.NFCViewer

Adding Features 173

Page 174: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Action bb.action.SHARE

URI Any valid URI value that is preceded by file:// (for example, file://, http://, 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 Value

Target ID sys.NFCViewer

Action bb.action.SHARE

URI list://

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

Adding Features 174

Page 175: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

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 Value

Target ID sys.NFCViewer

Action bb.action.SHARE

MIME type text/plain

Data Text is sent as a byte array. UTF-8 encoding is supported.

Sharing NDEF messages

Here are the invocation attributes you use to invoke an NFC card to share NFC Data Exchange Format (NDEF) messages:

Attribute Value

Target ID sys.NFCViewer

Action bb.action.SHARE

MIME type application/vnd.rim.nfc.ndef

Adding Features 175

Page 176: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Data NDEF message is sent in the form of a byte array. The following method is used to create the byte array message: nfc_get_ndef_message_bytes().

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 Value

Target ID sys.NFCViewer

Action bb.action.SHARE

MIME type text/URI-list

Data 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).

Sharing data as a URL

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

Attribute Value

Target ID sys.NFCViewer

Action bb.action.SHARE

Adding Features 176

Page 177: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

MIME type MIME type can be specified in the following format: application/myapp, text/vCard. 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 application and MIME types mentioned above.

Phone

Opening call logs

Here are the invocation attributes 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 bb.action.OPEN

MIME type application/vnd.blackberry.calllog.id

Dialing a number

Here are the invocation attributes you use to dial a number:

Attribute Value

MIME type application/vnd.blackberry.phone.startcall

Adding Features 177

Page 178: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Action bb.action.DIAL

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

Data Description

String number (required) The phone number that will be called.

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 is true.

Dialing an emergency number

Here are the invocation attributes you use to dial an emergency number:

Attribute Value

MIME type application/vnd.blackberry.phone.startcall

Action bb.action.EMERGENCY_CALL

Pictures

Opening images

Here are the invocation attributes you use to open images with the picture previewer:

Adding Features 178

Page 179: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pictures.card.previewer

Action bb.action.VIEW

MIME type All supported image files

URI file:///

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

Parameters 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 the upScale parameters. The size parameter allows you to specify the dimensions of the output image in pixels while the upScale parameter identifies whether the output image is scaled to that specified size or not. The upScale parameter is only valid

Adding Features 179

Page 180: BlackBerry WebWorks 2.1-Development Guide

if you first 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.

Output image size not specified

In this case, size and upScale parameters are not used. This 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 since true is the default value.

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. This also means that the user will not be able to change the aspect ratio of the output image as 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 automatically scaled 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 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 as 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 automatically downscaled 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 launch a Remember card to create a new entry:

Adding Features 180

Page 181: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pim.remember.composer

Action bb.action.ADD

URI remember://notebookentryYou can also add the following key-value pairs by adding a question mark (?) after the URI:

• title=<ENTRY TITLE>• 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 a URI to a new entry

Here are the invocation attributes that you use to launch a Remember card to add a file or URI to a new entry:

Attribute Value

Target ID sys.pim.remember.composer

Action bb.action.SHARE

URI file://list://http://https://

Adding Features 181

Page 182: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

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

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 key-value 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 launch a Remember card to edit an entry:

Adding Features 182

Page 183: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pim.remember.composer

Action bb.action.EDIT

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

Viewing an entry

Here are the invocation attributes that you use to launch a Remember card to view an entry:

Attribute Value

Target ID sys.pim.remember.previewer

Action bb.action.VIEW

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

Opening an entry

Here are the invocation attributes that you use to launch a Remember card to open an entry:

Attribute Value

Target ID sys.pim.remember

Action bb.action.OPEN

Adding Features 183

Page 184: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

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

Search

Searching using keywords

Here are the invocation attributes 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

To display your app in the Extended Search section of the Search application, here's how you can specify your app in the config.xml file:

<invoke-target id="com.xyz.test"><invoke-target-type>APPLICATION</invoke-target-type><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 application displays your app in the Extended Search section using your app’s name and icon. Your application recieves any search requests via invocation requests. The search string is delivered in the data attribute of the request and is in UTF-8 format.

Adding Features 184

Page 185: BlackBerry WebWorks 2.1-Development Guide

Settings

Opening the notification settings of an app

Here are the invocation attributes you use to open the notification settings card of an application:

Attribute Value

Target ID sys.settings.card

Action bb.action.OPEN

MIME type settings/view

URI "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 application ID: phone, bbm, bbmvideo, text, reminders, facebook, twitter, linkedin, foursquare.

Opening the Settings card

Here are the invocation attributes you use for the Settings card:

Attribute Value

Target ID sys.settings.card

Action bb.action.OPEN

MIME type settings/view

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

Adding Features 185

Page 186: BlackBerry WebWorks 2.1-Development Guide

Setting URIs

About screens settings://about settings://about/generalsettings://about/hardwaresettings://about/ossettings://about/networksettings://about/legalsettings://about/workspace

Accessibility settings://accessibilityAccounts settings://pim

settings://pim/defaultAccountssettings://pim/createAccount settings://pim/listAccountssettings://pim/createAccountType?type=<type> where type can be facebook, twitter, linkedin, evernote, or mail_contacts_calendarsettings://pim/showAccount?id=<id>settings://pim/deleteAccount?id=<id>settings://pim/EnrollmentProgress

Application Manager settings://appmgrApplication Permissions settings://permissionsBlackBerry Balance settings://balanceBlackBerry ID settings://bbidBlackBerry Link settings://linkBlackBerry Protect settings://protectBluetooth settings://bluetooth

Adding Features 186

Page 187: BlackBerry WebWorks 2.1-Development Guide

Setting URIs

Certificates settings://certificatesChild Protection settings://childprotectionDate and Time settings://datetimeDefault Applications settings://defaultappsDevelopment Mode settings://devmodeDevice Monitor settings://sysmonDiagnostics settings://diagnosticsDisplay settings://displayDisplay (Advanced screen) settings://display/advancedLanguage and Input settings://language

settings://language/inputsettings://language/keyboardsettings://language/spellchecksettings://language/assistance

Location settings://locationMobile Hotspot settings://mhsMobile Network settings://radioNetwork Connections settings://networkconnectionsNFC settings://nfcNotification settings://notificationPassword settings://passwordPayment Options settings://paymentScreen Reader settings://screenreaderSearch settings://searchSecurity settings://securitySharing settings://sharing

Adding Features 187

Page 188: BlackBerry WebWorks 2.1-Development Guide

Setting URIs

SIM Card settings://simSoftware Updates settings://softwareupdateSound settings://soundStorage and Access settings://storageTethering settings://tetheringUSB settings://usbVideo Chat settings://videochatVoice Control settings://voiceVPN settings://vpnWi-Fi settings://wifiWipe settings://wipe

Text Messages

Composing a text message

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

Attribute Value

Target ID sys.pim.text_messaging.smsuri

Action bb.action.COMPOSE

MIME type application/text_messaging

Data must be PPS-encoded and contain the following fields:

Adding Features 188

Page 189: BlackBerry WebWorks 2.1-Development Guide

Field Description

to This field represents the list of recipients in JSON format.

body This field represents the text contained in the body of the text message.

send This field should be set as a Boolean value. If the value is set to true, the message is sent right away. If the value is false, the composer remains on the screen.

The following examples show PPS-encoded data fields:

// Example 1body::Hello world!to:json:["2125551212","9785551234"]

// Example 2body::Hello world!send:b:trueto:json:["2125551212"]

Here are the invocation attributes that you use to launch the composer card for the Text Messages app with a recipient field set to a specified phone number:

Attribute Value

Target ID sys.pim.text_messaging.smsuri

MIME type application/vnd.blackberry.string.phone

Data Recipient’s phone number

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

Adding Features 189

Page 190: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.pim.text_messaging.smsuri

Action bb.action.SENDTEXT

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

Target ID sys.pim.text_messaging.sharemedia

Action bb.action.SHARE

URI list://

MIME type filelist/media

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

Attribute Value

Target ID sys.pim.text_messaging.smsuri

Action bb.action.SENDTEXT

URI tel:5198887465

Adding Features 190

Page 191: BlackBerry WebWorks 2.1-Development Guide

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

[ { "uri": "file:///path/to/file" }, { "uri": "file:///path/to/another_file" }, ...]

Twitter

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

Page 192: BlackBerry WebWorks 2.1-Development Guide

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 192

Page 193: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

URI twitter:connect:<twitter_profile_name>The profile name must not contain the @ 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 193

Page 194: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target ID sys.video_editor.card

Action bb.action.EDIT

URI videoeditor:///path/to/content.mp4MIME type video/mp4

When video editing is complete, the video editor returns the output path of the saved video file in the data property of the CardDoneMessage. The video editor sets the reason property to Canceled or Saved.

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 Value

Target ID sys.apps.audiorecorder

Action bb.action.CAPTURE

MIME type Any valid MIME type value

URI file://

File extensions .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.

Adding Features 194

Page 195: BlackBerry WebWorks 2.1-Development Guide

YouTube

Sharing a video with YouTube

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

Attribute Value

Target ID Youtube

Action bb.action.SHARE

URI file:///path/to/content.mp4File extensions .3gp, .

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

Invoking third-party applications

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. This will allow them to invoke your app from their app. For a user, this means better multitasking and a smooth application flow. To have your application's invocation attributes published here, use your BlackBerry ID to sign in to the BlackBerry Jam Zone for invocation.

You can also integrate your application 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.

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.

Adding Features 195

Page 196: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Target type application

Target ID com.digicasa.cashalyst.import

Action bb.action.OPEN, bb.action.VIEW

MIME type application/*, text/*

File extensions qfx, ofx

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

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 Value

Target type application

Target ID AnagrammatistEN591c82ab559936cc457d581de4df064

Adding Features 196

Page 197: BlackBerry WebWorks 2.1-Development Guide

Attribute Value

Action bb.action.SEARCH.EXTENDED

MIME type application/vnd.bb.search.criteria

Data description In general, the string (set of letters) is accepted.

Music & Radio

Ambience

Ambiant Sounds for BlackBerry

Create some ambience with images and sounds.

Attribute Value

Target type application

Target ID ambience

Action bb.action.OPEN

MIME type text/plain

Adding Features 197

Page 198: BlackBerry WebWorks 2.1-Development Guide

Photo & Video

Photo Effect

PhotoEffect

Create beautiful photo effects.

Attribute Value

Target type application

Target ID com.umang.PhotoEffect

Action bb.action.OPEN

MIME type image/*, image/png, image/jpg, image/jpeg

URIs file://File extensions png, jpg, jpeg

Data description 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 198

Page 199: BlackBerry WebWorks 2.1-Development Guide

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 Value

Target type card.composer

Target ID org.ekkescorner.charts.chartimages

Action bb.action.SHARE

MIME type image/jpeg

Data description 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.

Becoming a default app

You can enable your app to become the default app for certain types of content, like files (for example, .pdf, .doc, or .cal) 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 application for that type of content.

Registering your app

To register your application as a default application, you must specify bb.action.OPEN as the action and specify either a MIME type and a URI or a MIME type and a file extension in the config.xml file.

Adding Features 199

Page 200: BlackBerry WebWorks 2.1-Development Guide

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

BBM Social PlatformThe BlackBerry Messenger social platform provides APIs that allow you to leverage the social features and functionality of BBM in your app.

Adding Features 200

Page 201: BlackBerry WebWorks 2.1-Development Guide

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

Adding Features 201

Page 202: BlackBerry WebWorks 2.1-Development Guide

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

Page 203: BlackBerry WebWorks 2.1-Development Guide

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.

Testing your BBM connected app in the BlackBerry 10 Device 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 203

Page 204: BlackBerry WebWorks 2.1-Development Guide

Install JavaThe first thing you need to do is download and install the Java SE 6 update 37 or later (JDK or JRE, 32-bit or 64-bit).

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 204

Page 205: BlackBerry WebWorks 2.1-Development Guide

Set up the simulators to run BBM

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.

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.

Adding Features 205

Page 206: BlackBerry WebWorks 2.1-Development Guide

3. Click Connect. You can see activity in the BBM server simulator console when the connection is successful.

Now you're ready to connect your app to BBM!

Note: 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.

Adding Features 206

Page 207: BlackBerry WebWorks 2.1-Development Guide

Note: After you change the PIN, restart the simulator.6. On the Controller menu, click Connection > Connect.7. In the Auto Discover section, select the entry for the device simulator instance that you want to connect.8. In the IP Address drop-down list, select the IP Address of the corresponding simulator.9. 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 host computer as the device simulator.

12.Click Connect.

You'll see activity in the BBM server simulator console when the connection is successful.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 Set up the simulators to run BBM.

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 pre-production 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.

Adding Features 207

Page 208: BlackBerry WebWorks 2.1-Development Guide

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:

• 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 pre-production 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.

Adding Features 208

Page 209: BlackBerry WebWorks 2.1-Development Guide

Payment ServiceAfter 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.

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 define—all 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 209

Page 210: BlackBerry WebWorks 2.1-Development Guide

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 210

Page 211: BlackBerry WebWorks 2.1-Development Guide

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 211

Page 212: BlackBerry WebWorks 2.1-Development Guide

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 212

Page 213: BlackBerry WebWorks 2.1-Development Guide

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 213

Page 214: BlackBerry WebWorks 2.1-Development Guide

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, "extraParameters": {

Adding Features 214

Page 215: BlackBerry WebWorks 2.1-Development Guide

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

Page 216: BlackBerry WebWorks 2.1-Development Guide

} }

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 216

Page 217: BlackBerry WebWorks 2.1-Development Guide

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

Page 218: BlackBerry WebWorks 2.1-Development Guide

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

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

Adding Features 218

Page 219: BlackBerry WebWorks 2.1-Development Guide

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 219

Page 220: BlackBerry WebWorks 2.1-Development Guide

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 doesn’t 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 220

Page 221: BlackBerry WebWorks 2.1-Development Guide

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

Adding Features 221

Page 222: BlackBerry WebWorks 2.1-Development Guide

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

Adding Features 222

Page 223: BlackBerry WebWorks 2.1-Development Guide

Push ServiceThe Push Service provides an efficient way to send content to a device. It runs in the background and has minimal impact on battery life. For more information about the benefits of the Push Service, see What can the Push Service offer?

To use the Push Service, you need a Push Initiator to send data (up to 8KB of images, text, or audio) and a push-enabled app to receive the data.

The information below can help you develop a push-enabled app using BlackBerry WebWorks.

For information about developing a Push Initiator to use with your push-enabled app, see Push Service.

Architecture

The architecture diagram 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 push-enabled application.

Component Description

Push Initiator

The Push Initiator is the application that creates request messages (such as a push request, cancel request, or status-query request) and response messages (such as a result-notification response) using the server-side library and submits them to the push proxy gateway (PPG). The Push Initiator also uses the server-side library to process subscription-related requests that it receives from the push-enabled application on the BlackBerry device.

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

Adding Features 223

Page 224: BlackBerry WebWorks 2.1-Development Guide

Component Description

Initiator uses to interact with the PPG. The Push Initiator also uses the server-side library to process subscription-related requests that it receives from the push-enabled application on the device. 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 and status-query 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 outcome 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 JavaScript APIs that the push-enabled application uses to create a PushService object, create and destroy a channel, and receive push messages.

Push-enabled application

The push-enabled application runs on a device, and might send subscription-related requests to the Push Initiator. The push-enabled application uses the client-side library to create a PushService object, create and destroy a channel, and receive push messages.

Levels of service

When you use the Push Service, you can choose from two levels of service: Push Essentials and Push Plus. The majority of push-enabled apps in BlackBerry World use Push Essentials.

If you are pushing data through the BlackBerry Enterprise Service, you have access to features comparable to Push Plus.

Push Essentials

When you use the Push Essentials level of service, you can send content to a device, but you can't query the status of the content or receive acknowledgments after you send the content. However, you can set the expiry time for content delivery for up to 30 days.

Here's how content is sent to a client application on a BlackBerry device with the Push Essentials level of service.

Adding Features 224

Page 225: BlackBerry WebWorks 2.1-Development Guide

1. The content provider sends content in a push request.2. The PPG authenticates and acknowledges the push request.3. The PPG pushes the content to the specified device or devices.4. Each BlackBerry device acknowledges the push request to the PPG.

Push PlusPush Plus is a paid level of service. It offers the following additional functionality so that you can check the status and receive notifications about delivered content:

• Results notification lets you know when messages are delivered, if they couldn't be delivered, or if they expired waiting to be delivered.

• The PPG keeps track of the current status of a push message, and you can use a status query to check the status. The status of a push message can be pending, delivered, undeliverable, or expired.

• Push cancellation can withdraw messages if they haven't been delivered already.• You can set the expiry time for content delivery for up to 8 hours.

Here's how content is sent to a client application on a BlackBerry device with the Push Plus level of service.

Adding Features 225

Page 226: BlackBerry WebWorks 2.1-Development Guide

1. The content provider sends content in a push request, and can request to receive a result notification.2. The PPG authenticates and acknowledges the push request.3. The PPG pushes the content to the specified device or devices.4. Each BlackBerry device acknowledges the push request to the PPG.5. If the content provider requested to receive a result notification when it sent content in step 1, the

PPG sends a notification to the content provider indicating whether the push message was delivered, was undeliverable, or expired waiting to be delivered.

6. The content provider acknowledges the receipt of the result notification.7. Alternatively, if the content provider didn't request to receive a result notification, the content

provider can request the status of the content from the PPG. The status request can be for any or all of the devices that received the content.

8. If the content provider requests the status of the content, the PPG returns a single response that contains the current status for the specified devices.

Developing a push-enabled app

Before you develop your own push-enabled app, you may find it helpful to Explore the sample push-enabled app.

Requirements

To develop and test a push-enabled app, you need the following:

Adding Features 226

Page 227: BlackBerry WebWorks 2.1-Development Guide

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

BlackBerry device • BlackBerry 10 OS• Data plan with your wireless service provider that provides a connection

to the Wi-Fi network or mobile network

Add the Push Service plugins to your project

Before you can use the Push Service APIs with your application, you need to add the following plugins to your project:

• com.blackberry.push• com.blackberry.invoked

Adding a plugin copies the plugin to your project's plugins folder, and makes the APIs available to your application. It also adds the required <feature> element to your application's config.xml file. After you add a plugin, the contents of the plugin are packaged together with your other application resources the next time you build your application. To add the plugins:

1. Navigate to the directory of the app project.2. Add the com.blackberry.push plugin using the following command:

webworks plugin add com.blackberry.push 3. Add the com.blackberry.invoked plugin using the following command:

webworks plugin add com.blackberry.invoked

Adding Features 227

Page 228: BlackBerry WebWorks 2.1-Development Guide

Update your config.xml file

Before you can use the Push Service APIs with your application, you need to update your application's config.xml file with the following statements.

1. Add an entry for the invoke events that your application 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 invoke relates specifically to push messages. The event listener in the sample application 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.

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 application <!-- to be opened --> <rim:invoke-target id="sample.pushcapture.invoke.open"> <type>APPLICATION</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 invoke relates to an open invoke event. In the sample application, 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 application 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.

Explore the sample push-enabled app

You can download the Push Capture sample app from GitHub.

Adding Features 228

Page 229: BlackBerry WebWorks 2.1-Development Guide

You can use the sample app to learn how to develop your own push-enabled app. The sample app shows you how to use the Push Service APIs to connect with a Push Initiator, and receive push messages on a BlackBerry device.

The sample app accepts push messages with the following types of content. If you're using the Push Service SDK to develop a Push Initiator, the API automatically specifies the type of content in the header of the push message. Using the Push Service, a Push Initiator can send up to 8 KB of any type of content (images, text, or audio).

Type of content Content-type HTTP header

Text text/plain

HTML text/html

XML application/xml

Image image/jpeg, image/gif, image/png

To test the sample app on a device, you need to have a Push Initiator running. The Push Service SDK includes sample Push Initiators.If you implement a Push Initiator that doesn't use the Push Service SDK, or your Push Initiator only uses the low-level APIs without subscription support from the SDK, you can still use the sample app for testing purposes. You need to indicate that you are not going to subscribe with the Push Service SDK when you configure the sample app. For details, see Configure the sample app.

Download, build, and deploy the sample app

To download the sample app, visit the samples repository. The repository contains the source code and associated files for the app. The README.md file in the repository contains the instructions that you need to build and deploy the sample app on a BlackBerry device.

The repository contains the following folders:

Folder Description

Images This folder contains the images for the sample app.

Scripts This folder contains the JavaScript files for the sample app.

Styles This folder contains the CSS files for the sample app.

Configure the sample app

When you run the sample push-enabled app for the first time, you need to specify some configuration information, including the information from the confirmation email message that you received when you registered your Push Initiator to use the Push Service. When you develop your own app, you can hard code this

Adding Features 229

Page 230: BlackBerry WebWorks 2.1-Development Guide

information into your app instead of displaying it in a configuration screen and requiring the user to type the information.

1. Start the sample app.The configuration screen appears.

2. Click Public/BIS if you're using the Push Service without the BlackBerry Enterprise Service or

Enterprise/BDS if you're pushing data through the BlackBerry Enterprise Service.3. Clear the Subscribe with Push Service SDK check box if one of the following is true:

• Your Push Initiator doesn't use the Push Service SDK.• Your Push Initiator only uses the low-level APIs without subscription support from the Push Service SDK.• You’re using the low-level sample Push Initiator that comes with the Push Service SDK.

4. If the Subscribe with Push Service SDK check box is selected, in the Application ID field, perform one of the following actions:

• Type the application ID that is specified in the confirmation email message that you received from BlackBerry.

• If you're pushing data through the BlackBerry Enterprise Service, type a unique application ID of your choosing. If you clear the Subscribe with Push Service SDK check box, you can't type an application ID. In this case, the Push Service APIs create an application ID for you automatically.

Adding Features 230

Page 231: BlackBerry WebWorks 2.1-Development Guide

Note: The sample app uses the application ID when it creates the PushService object to perform push-related operations. To specify the application ID in your own app, you use the appId field of the options object that is passed into the call to the static PushService.create() function.

5. In the PPG URL field, type the PPG base URL specified in the confirmation email message. The sample app uses this URL to create a channel to the PPG. If you're using the push technology of the BlackBerry Enterprise Service, you don't need to type a URL.

Note: For an evaluation environment, the URL is http://cp<cpid>.pushapi.eval.blackberry.com, where <cpid> is your content provider ID. For a production environment, the URL is http://cp<cpid>.pushapi.na.blackberry.com.

6. If the Subscribe with Push Service SDK check box is selected, in the Push Initiator URL field, type https://<server_address>/high-level-sample, where <server_address> is the address of the server where the high-level sample Push Initiator is deployed. The Push Service SDK includes the high-level sample Push Initiator that is deployed on the Apache Tomcat server. The URL must be accessible from the Internet.

7. Click the Launch Application on New Push check box if you want to start the sample app if it isn't already running when a new push message arrives. Leave the check box cleared if you don't want to start the sample app when a new push message arrives. If the check box is cleared, and the app isn't running, it won't receive the push message.

8. Click Save.The sample app stores the configuration in the database, and calls the static PushService.create() function to attempt to create a PushService object. If the PushService.create() call is successful, the app calls launchApplicationOnPush() with true or false depending on the selection you made for the Launch Application on New Push option on the configuration screen. For details about these calls, see Creating a PushService object and Start the sample application in the background.

Register the sample app

After you configure the sample push-enabled app, you need to register the app to create a push channel to the PPG to receive 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 allowing the subscription. The sample app provides a Register dialog box where you can type any username and password.

To see the code that creates the channel and handles the subscription, see Creating a push channel.

1. Tap Register at the bottom of the device screen.

The Register screen appears.

2. If you chose to subscribe with the Push Service SDK, type any username and password in the Register screen.

Adding Features 231

Page 232: BlackBerry WebWorks 2.1-Development Guide

3. Tap Submit.

Creating a PushService object

The sample application calls the static PushService.create() function to create a PushService object to perform push-related operations. Once the PushService object is instantiated, the sample application can make calls to the object to receive and process push messages.

In your application, 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 application. For details about configuring the sample application, see Configure the sample application.

The invokeTargetID is a value that you generate. The value identifies the push-enabled application 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 application 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 application 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.

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 application using public push ops = { invokeTargetId : sample.pushcapture.invokeTargetIdPush, appId : sample.pushcapture.appid, ppgUrl : sample.pushcapture.ppgurl };} else { // Enterprise application using enterprise push . . .} blackberry.push.PushService.create(ops, sample.pushcapture.successCreatePushService, sample.pushcapture.failCreatePushService,

Adding Features 232

Page 233: BlackBerry WebWorks 2.1-Development Guide

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 application using public push . . .} else { // Enterprise application 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);

Call successCreatePushService()

The successCreatePushService() callback function stores the PushService object in a global variable. The application 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; . .};

Adding Features 233

Page 234: BlackBerry WebWorks 2.1-Development Guide

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 application, 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 application."); } else if (result == blackberry.push.PushService. INVALID_PROVIDER_APPLICATION_ID) { // This error only applies to consumer applications 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 application. It usually means a " + "programming error."); } else { alert("Error: Received error code (" + result + ") after " + "calling blackberry.push.PushService.create."); }};

Starting the sample application in the background

You can use the Push Service APIs to start running your application when a push message arrives, and to continue running it in the background. This saves valuable device resources because your application doesn’t have to be running all the time to receive push messages.

The sample application calls the launchApplicationOnPush() function with a value of true. This call registers the application 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 application so that it starts running in the background when a push message arrives, you can call launchApplicationOnPush() with a value of false. The push

Adding Features 234

Page 235: BlackBerry WebWorks 2.1-Development Guide

messages that arrive when the value is false are delivered only if your application 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 application, 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 application."); } 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."); } }};

Creating a push channel

The sample application creates a push channel to the PPG to receive push messages. The application 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.

Adding Features 235

Page 236: BlackBerry WebWorks 2.1-Development Guide

If you chose to subscribe with the Push Service SDK when you configured the sample application, the Push Initiator requires a username and password that it authenticates before allowing the subscription. The sample application provides a Register screen where the user can type any username and password. For your application, 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 application 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 application tries to create a channel.

Call createChannel()

The sample application 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 application 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 application. 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 application, 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 { . . . // Error handling } };

Adding Features 236

Page 237: BlackBerry WebWorks 2.1-Development Guide

Call subscribeToPushInitiator()

If the channel creation is successful, and you're subscribing with the Push Service SDK, the sample application 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 application 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 username = document.getElementById("reguserid").value.trim(); var password = document.getElementById("regpwd").value.trim(); var address = token; var osversion = blackberry.system.softwareVersion; var 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 237

Page 238: BlackBerry WebWorks 2.1-Development Guide

xmlHttp.send();};

Receiving a push message

The sample application 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 application 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 application handles a push invoke event. To see how the sample application handles an open invoke event, see Handling notifications in the BlackBerry Hub.

This is the event listener that the sample application registers.

// Add an event listener to handle incoming invokesdocument.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 application processes the PushPayload object by calling pushNotificationHandler(). In your application, 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") { . . . } };

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

Page 239: BlackBerry WebWorks 2.1-Development Guide

Acknowledging the receipt of a push message

The Push Initiator can send a confirmed push message with application-level reliability. The push-enabled application must acknowledge a confirmed push message. The push-enabled application 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 application 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 application checks the isAcknowledgeRequired field when it calls pushNotificationHandler(). The sample application acknowledges the receipt of the push message by accepting it by calling pushpayload.acknowledge(true).

// 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.if (pushpayload.isAcknowledgeRequired) { // In our sample, we always accept the push, but situations might // arise where an application 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 application to start running in the background when a push message arrives using the launchApplicationOnPush() function, your application continues to run after it processes the message. This can use up device resources, so it's a good practice to exit your application after it processes a push message. You have to be careful, however, not to exit your application if it was ever displayed full screen (in the foreground) because the user might still be using your application.

To exit after processing a push message, the sample application creates the hasBeenInForeground boolean variable to check whether the application was ever displayed full screen. The variable is set initially to false.

/** * Boolean indicating whether the application has ever been in the * foreground. This boolean is used to determine whether we are * dealing with the situation where the application is set to launch * on a new push, the application is currently not running, and a new * push comes in. The application 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 239

Page 240: BlackBerry WebWorks 2.1-Development Guide

* the application. This is to save battery life and performance on * the device by not having the application running in the background * after every push that comes in. */this.hasBeenInForeground = false;

The sample application checks the current window state when it starts to see if it starts full screen. If it does, the application sets the hasBeenInForeground variable to true. The application also listens for the resume event. If this event occurs, the application was displayed full screen by the user, and the hasBeenInForeground variable is set to true.

PushCapture.prototype.initPushService = function() { // Check if the application started up in the foreground. // We are trying to determine if the application was launched in // the background and so we would be able to process a push and // exit from the application. if (blackberry.app.windowState == "fullscreen") { sample.pushcapture.hasBeenInForeground = true; }

// We also use the resume event to help determine if the // application has ever been brought to the foreground // (from the background - hence it's being "resumed"). document.addEventListener("resume", sample.pushcapture.onResume);

. . .};

PushCapture.prototype.onResume = function() { sample.pushcapture.hasBeenInForeground = true;};

After the sample application processes the push message, it checks the hasBeenInForeground variable. If the variable is true, the application doesn't exit. If the variable is false, the application was never displayed full screen. The application started in the background when a push message arrived, and can exit after it processes the message.

// Exit the application after processing the push if the // application has not been brought to the foreground if (!sample.pushcapture.hasBeenInForeground) { setTimeout(function() { blackberry.app.exit(); }, 1000); }

Adding Features 240

Page 241: BlackBerry WebWorks 2.1-Development Guide

Handling notifications in the BlackBerry Hub

The sample application handles notifications of push messages in the BlackBerry Hub in the following ways:

• When a user taps on a notification in the BlackBerry Hub, the sample application receives an open invoke event, and displays the push message that corresponds to the notification.

• When the sample application receives a push message, it adds a notification to the BlackBerry Hub.• When a user taps on the push message in the sample application, the application removes the notification

from the BlackBerry Hub.• When a user deletes an individual push message in the sample application, the application removes the

notification for the push message from the BlackBerry Hub.• When a user taps Mark All Open or Delete All in the sample application, the application removes all the

notifications for the sample application from the BlackBerry Hub.

Display a push message for an open invoke event

The sample application 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 invokesdocument.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 application displays the push message that corresponds to the notification.

PushCapture.prototype.onInvoke = function (invokeRequest) { if (invokeRequest.action != null && invokeRequest.action == "bb.action.PUSH") { . . . } 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;

Adding Features 241

Page 242: BlackBerry WebWorks 2.1-Development Guide

sample.pushcapture.selectedPushSeqnum = payload; } else { // We are on the home screen, simply open the push. sample.pushcapture.openPush(payload); } } 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 application to the BlackBerry Hub, the sample application creates a Notification object.

// Add a notification to the BlackBerry Hub for this pushvar 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 application from the BlackBerry Hub, the sample application 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

Adding Features 242

Page 243: BlackBerry WebWorks 2.1-Development Guide

application, and answers Yes to the confirmation message. The sample application also deletes the push message from the application.

Notification.remove(sample.pushcapture.selectedPushSeqnum + sample.pushcapture.notificationSuffix);

Remove all notifications from the BlackBerry Hub

To remove all the notifications for the sample application from the BlackBerry Hub, the sample application calls Notification.remove() with the sequence number of each push message in the sample application. This code is called when the user taps either Mark All Open or Delete All in the sample application.

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 application 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 application, the Push Initiator requires a username and password that it authenticates before unsubscribing. The sample application provides an Unregister screen where the user can type any username and password. For your application, 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 application 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 application tries to destroy the channel.

Adding Features 243

Page 244: BlackBerry WebWorks 2.1-Development Guide

Call destroyChannel()

The sample application 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 application, 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.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 application 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 application 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();Adding Features 244

Page 245: BlackBerry WebWorks 2.1-Development Guide

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

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 application, you should authenticate all new users, and create a new channel to the PPG.

The sample application 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.

Adding Features 245

Page 246: BlackBerry WebWorks 2.1-Development Guide

• 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 application 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.

Push transport error

This error occurs when there's a problem with the mobile network, the user's wireless connection, or the low-level 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 application 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 application 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 application 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 application 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."; }

Adding Features 246

Page 247: BlackBerry WebWorks 2.1-Development Guide

Call onPushTransportReady()

To handle the push transport error and PPG server error, the sample application specifies an onPushTransportReady() callback in its call to the static PushService.create function so that the application 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);

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 application handles these errors by explicitly telling the user about the errors. In your application, 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.

What can the Push Service offer?

Increased efficiency

You can choose where to send content. Using the Push Service, you can send content to:

• Individual users (unicast)

Adding Features 247

Page 248: BlackBerry WebWorks 2.1-Development Guide

• 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. Additionally, with the Push Plus service level, your push solution can store push requests on a local database on the push server. If the Push Initiator receives a result notification, it can then perform status queries locally.

End-to-end message visibility

With the Push Plus service level, you can receive up to three status reports for your push request: a server-level acknowledgment, transport acknowledgment, and application-level acknowledgment. You can also query the status of a push request for a specific BlackBerry device.

Runs in the background

The Push Initiator sends content as bandwidth becomes available so that it doesn't interfere with other applications, such as phone calls.

Minimal battery drain

The Push Service minimizes the impact on device batteries because the push-enabled application listens in the background for the Push Initiator to send content to it. The application 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 these common tasks:

• Send, query, or cancel push messages• Specify listeners, acknowledgments and their notifications• Track completed push messages• Track the running count of push messages

Adding Features 248

Page 249: BlackBerry WebWorks 2.1-Development Guide

FrameworksFind out more about the community frameworks that you can use in your WebWorks apps.

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

Page 250: BlackBerry WebWorks 2.1-Development Guide

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 250

Page 251: BlackBerry WebWorks 2.1-Development Guide

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

Page 252: BlackBerry WebWorks 2.1-Development Guide

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

GitHub repositories

• blackberry/WebWorks-Samples - Sample BlackBerry WebWorks applications

Other resources

• BlackBerry World

Sencha Touch 2Sencha 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 252

Page 253: BlackBerry WebWorks 2.1-Development Guide

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

Page 254: BlackBerry WebWorks 2.1-Development Guide

Dojo Toolkit

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

Page 255: BlackBerry WebWorks 2.1-Development Guide

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 255

Page 256: BlackBerry WebWorks 2.1-Development Guide

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 device’s 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 256

Page 257: BlackBerry WebWorks 2.1-Development Guide

• Dynamic content loading: http://dojotoolkit.org/reference-guide/1.8/dojox/mobile/dynamic-content-loading.html

Enyo 2.0

OverviewEnyo 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 appOnyx 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 257

Page 258: BlackBerry WebWorks 2.1-Development Guide

Incorporating the Enyo core files and the necessary librariesThe 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• Layout library

Frameworks 258

Page 259: BlackBerry WebWorks 2.1-Development Guide

Building a BlackBerry WebWorks app packageA BlackBerry WebWorks app is packaged into a file with a .bar extension. The BlackBerry WebWorks Packager (bbwp) is a command-line tool that generates a file from a .zip file, and it is included with the BlackBerry WebWorks SDK. The .zip file is a BlackBerry WebWorks application archive file. It contains your app source files and a configuration file named config.xml (BlackBerry WebWorks configuration file).

Building a BlackBerry WebWorks app from your source files involves the following activities:

1. Creating a new BlackBerry WebWorks project. For more information, see Creating a WebWorks project.2. Placing your app source files in the /www folder of your new project.3. Generating an unsigned .bar file for testing. For more information, see Building your app for testing.4. 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.

bbUI toolkitThe 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.

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.

Frameworks 259

Page 260: BlackBerry WebWorks 2.1-Development Guide

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 260

Page 261: BlackBerry WebWorks 2.1-Development Guide

Building and TestingTest 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 targetsA 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.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 261

Page 262: BlackBerry WebWorks 2.1-Development Guide

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>

Viewing existing targets

To view a list of existing targets:

Building and Testing 262

Page 263: BlackBerry WebWorks 2.1-Development Guide

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. On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.2. Navigate to Settings > About.3. In the Category drop-down list, click Network.4. 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:

Previewing your app in a browserYou 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.

Building and Testing 263

Page 264: BlackBerry WebWorks 2.1-Development Guide

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 serve3. In your browser, navigate to the following url:

localhost:8000/blackberry10/www

Building your app for testingYou 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. If you intend to test your app on a device, but have not already created and installed a debug token, you can supply the keystore password, and the build script creates and installs the debug token on the device for you as well.

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.

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

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

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.4. Click Build.

Building and Testing 264

Page 265: BlackBerry WebWorks 2.1-Development Guide

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.

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

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:

Building and Testing 265

Page 266: BlackBerry WebWorks 2.1-Development Guide

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:

Parameters Description

--devicepass <password> The simulator password. If you omit this parameter, you will be prompted to supply the simulator password, if necessary.

Building and Testing 266

Page 267: BlackBerry WebWorks 2.1-Development Guide

Parameters Description

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

Deploy your app to a device

You can deploy your app to a device using the SDK web tool or the command line.

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. For more information, see Enable Development Mode on a device or simulator.

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

Deploy your project using the SDK web tool

To build your app in debug mode and deploy it to a device 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 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.

Building and Testing 267

Page 268: BlackBerry WebWorks 2.1-Development Guide

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 A note about using debug tokens.

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 A note about using debug tokens.

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]

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:

Building and Testing 268

Page 269: BlackBerry WebWorks 2.1-Development Guide

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.

A note about using debug tokens

Before you can deploy an unsigned app to the device, the device must have a valid debug token installed on it. The BlackBerry WebWorks SDK makes it simple to install a debug token on any target device; you only need to provide the keystore password when you deploy your app to a device. However, there are a few things you should know about working with debug tokens.

For the SDK to be able to create a debug token for you, you must first request your signing key and set up your computer for code signing. You can request your free code signing key by completing the form at https://www.blackberry.com/SignedKeys. For more information about setting up your computer for signing and setting the keystore password you use for creating your debug token, see Set up your computer for testing and signing.

Building and Testing 269

Page 270: BlackBerry WebWorks 2.1-Development Guide

Debug tokens are not specific to a single app; once you have a valid debug token installed on your BlackBerry 10 device, you can load any unsigned app onto the device for testing until the debug token expires.

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. Note that you are limited to a total of 100 device PINs across all of active debug tokens associated with the same keystore password. This 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.

Enable Development Mode on a device or simulator

To test your WebWorks apps on a BlackBerry 10 device or simulator, you must enable Development Mode. This mode allows you to remotely install and launch apps. You might need to re-enable Development Mode on your device regularly. For security reasons, Development Mode expires automatically in 10 days, and also becomes disabled if you reboot a device.

To enable Development Mode on your device:

1. On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.2. Navigate to Settings > Security and Privacy > Development Mode.3. Set the Development Mode toggle button to On.4. When you are prompted, enter the password for your device, and tap OK.

Debugging using Web InspectorWeb 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 smartphone or BlackBerry tablet (or a BlackBerry Smartphone Simulator or BlackBerry PlayBook Simulator) in conjunction with the Google Chrome desktop browser.

Getting Web Inspector up and running

Inspecting and debugging your webpage source code

Building and Testing 270

Page 271: BlackBerry WebWorks 2.1-Development Guide

Enabling Web Inspector

By default, Web Inspector functionality is disabled. How you enable Web Inspector depends on whether you are inspecting content in a BlackBerry WebWorks app or in the BlackBerry Browser:

• To inspect the content of BlackBerry WebWorks applications, you must enable Web Inspector for each application individually. In a BlackBerry WebWorks application, you enable the Web Inspector by specifying a command line flag when you package your app.

• To use Web Inspector in conjunction with the BlackBerry Browser, you must first enable it in the BlackBerry Browser options. Enabling Web Inspector in the browser options only allows you to inspect content that is displayed in the BlackBerry Browser.

Once Web Inspector is enabled, the browser or application displays the IP address and port number it will use to serve the content.

Enable Web Inspector for a BlackBerry WebWorks app

You can use Web Inspector to inspect web content displayed in a BlackBerry WebWorks app. In a BlackBerry WebWorks app, you enable Web Inspector when you package the app.

To enable Web Inspector, you use the -d option flag when you package your application file.

Note: Web Inspector should only be enabled during the testing phase of development. When the application is ready for release (that is, when you are signing it for distribution), you should repackage the application without Web Inspector enabled. (involving code signing). Leaving the debugging port open may allow unintentional access to your application.

1. Run the BlackBerry WebWorks Packager from a command prompt.2. At the command prompt, change to the installation folder for the BlackBerry WebWorks Packager.3. In the command to compile the application, include the -d option flag to enable Web Inspector. For

example:

bbwp "C:\myapp\myarchive.zip" -d -o "C:\myapp\output"

Windows example:

bbwp C:\myapp\myarchive.zip -d -o C:\myapp\output

Mac OS example:

./bbwp ~/myapp/myarchive.zip -d -o ~/myapp/output

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.

Building and Testing 271

Page 272: BlackBerry WebWorks 2.1-Development Guide

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, 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 or Safari 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• Verify that your computer is connected to your computer via a USB connection, or is communicating on the

same Wi-Fi network as the BlackBerry smartphone or BlackBerry tablet.

Note: Note that Web Inspector only provides a USB IP address (required if you intend to use Web Inspector over a USB connection) if your device is already connected via a USB connection when Web Inspector is enabled.

• Verify that your computer has the Google Chrome or Safari desktop browser installed.• Verify that development mode is enabled on your device.

Once you have enabled Web Inspector in your BlackBerry WebWorks app or in the BlackBerry Browser, you can remotely connect to your BlackBerry smartphone or BlackBerry tablet to inspect and modify the content.

1. On your computer, open Google Chrome or Safari.2. In the address bar, type the IP address of the BlackBerry smartphone or BlackBerry tablet, 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. For example:

http://<IP_address>:<port_number>

Building and Testing 272

Page 273: BlackBerry WebWorks 2.1-Development Guide

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 on any of the available links to view the content in Web Inspector.

Finding the IP address used to connect to the BlackBerry device

• If you are running a BlackBerry WebWorks app, the app displays the IP address when it is launched. To view the IP address, close the app, then restart it.

Web Inspector panelsWeb 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 that is located 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.

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.

Building and Testing 273

Page 274: BlackBerry WebWorks 2.1-Development Guide

Panel Icon Description

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 274

Page 275: BlackBerry WebWorks 2.1-Development Guide

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.

Building and Testing 275

Page 276: BlackBerry WebWorks 2.1-Development Guide

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

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.

Building and Testing 276

Page 277: BlackBerry WebWorks 2.1-Development Guide

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.

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.

Building and Testing 277

Page 278: BlackBerry WebWorks 2.1-Development Guide

• 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.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 278

Page 279: BlackBerry WebWorks 2.1-Development Guide

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.

Building and Testing 279

Page 280: BlackBerry WebWorks 2.1-Development Guide

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.

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 280

Page 281: BlackBerry WebWorks 2.1-Development Guide

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.

Building and Testing 281

Page 282: BlackBerry WebWorks 2.1-Development Guide

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

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

Page 283: BlackBerry WebWorks 2.1-Development Guide

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.

Building and Testing 283

Page 284: BlackBerry WebWorks 2.1-Development Guide

2. In the status bar at the bottom of the Timeline panel, click

to begin recording browser engine activity.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 284

Page 285: BlackBerry WebWorks 2.1-Development Guide

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 285

Page 286: BlackBerry WebWorks 2.1-Development Guide

Building and Testing 286

Page 287: BlackBerry WebWorks 2.1-Development Guide

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 287

Page 288: BlackBerry WebWorks 2.1-Development Guide

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 288

Page 289: BlackBerry WebWorks 2.1-Development Guide

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 289

Page 290: BlackBerry WebWorks 2.1-Development Guide

).• 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.

Building and Testing 290

Page 291: BlackBerry WebWorks 2.1-Development Guide

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.

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.

Building and Testing 291

Page 292: BlackBerry WebWorks 2.1-Development Guide

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 292

Page 293: BlackBerry WebWorks 2.1-Development Guide

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.

Building and Testing 293

Page 294: BlackBerry WebWorks 2.1-Development Guide

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).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 spaceIf 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 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 BlackBerry 10 device.

Building and Testing 294

Page 295: BlackBerry WebWorks 2.1-Development Guide

• 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: Only BlackBerry Enterprise Service 10 version 10.1.3 or later supports the Development Mode Access to Work Space IT policy.

• If the Development Mode Access to Work Space 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 Development Mode Access to Work Space rule is disabled, your app is removed and isn’t 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.• 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 appWhen 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 for testing.

Before you begin:

• Set up your computer for signing. For more information, see Set up your computer for testing and signing.

Building and Testing 295

Page 296: BlackBerry WebWorks 2.1-Development Guide

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 0.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 0.3

Check the table below for parameter details:

Parameters Description

--release Indicates that the app is built in release mode.

-k, --keystorepass <keystore_pw> The keystore password, which is used to sign your app. You define this password when you configure your computer to sign applications.

This parameter is required.

Building and Testing 296

Page 297: BlackBerry WebWorks 2.1-Development Guide

Parameters Description

-b, --buildId <version_num> The build version number of your application. Typically, this number should be incremented from the previous signed version.

This argument is optional.

-d, --web-inspector When included, indicates that Web Inspector is enabled in the packaged app.

This argument is optional.

-p, --params <JSON-file> 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" }}

When you execute the build command and include the --params params.json, the proxy settings specified in the file are passed to the blackberry-signer 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.

Building and Testing 297

Page 298: BlackBerry WebWorks 2.1-Development Guide

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 0.3

Check the table below for parameter details:

Parameters Description

--release Indicates that the app is built in release mode.

-k, --keystorepass <keystore_pw> The keystore password, which is used to sign your app. You define this password when you configure your computer to sign applications.

This parameter is required.

-b, --buildId <version_num> The build version number of your application. Typically, this number should be incremented from the previous signed version.

This argument is optional.

-d, --web-inspector When included, enables Web Inspector in the packaged app.

Building and Testing 298

Page 299: BlackBerry WebWorks 2.1-Development Guide

Parameters Description

This argument is optional.

-p, --params <JSON-file> A JSON file containing additional parameters to pass to downstream tools.

This argument is optional.

Distributing your appThe 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 storefrontThis 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 Set up your computer for testing and signing.

Building and Testing 299

Page 300: BlackBerry WebWorks 2.1-Development Guide

Building and Testing 300

Page 301: BlackBerry WebWorks 2.1-Development Guide

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

HTML best practicesIn 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 301

Page 302: BlackBerry WebWorks 2.1-Development Guide

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: initial-scale=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 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 302

Page 303: BlackBerry WebWorks 2.1-Development Guide

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 resourcesindex.htmlcss/app.cssjs/app.js

# offline.html displays if the user is offlineFALLBACK:/ /offline.html

# All other resources require an online connectionNETWORK:*

# Additional cached resourcesCACHE: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 303

Page 304: BlackBerry WebWorks 2.1-Development Guide

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, user-scalable=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 304

Page 305: BlackBerry WebWorks 2.1-Development Guide

• 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 browser’s 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.

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 305

Page 306: BlackBerry WebWorks 2.1-Development Guide

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

Page 307: BlackBerry WebWorks 2.1-Development Guide

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 307

Page 308: BlackBerry WebWorks 2.1-Development Guide

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

Page 309: BlackBerry WebWorks 2.1-Development Guide

So, the idea is to write more specific style rules so that the browser spends less time looking to match your style.

#main-navigation { } /* ID (Fastest) */body.home #page-wrap { } /* ID */.main-navigation { } /* Class */ul li a.current { } /* Class *ul { } /* Tag */ul li a { } /* Tag */* { } /* Universal (Slowest) */#content [title='home'] /* 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.

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 309

Page 310: BlackBerry WebWorks 2.1-Development Guide

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 <img id="logo" src="logo.jpg" alt="Company logo" height="100" width="100" />

Inline CSS <img id="logo" src="logo.jpg" style="width: 100px; height: 100px;">

Best Practices 310

Page 311: BlackBerry WebWorks 2.1-Development Guide

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 311

Page 312: BlackBerry WebWorks 2.1-Development Guide

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 312

Page 313: BlackBerry WebWorks 2.1-Development Guide

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 practicesIn 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 objectvar obj = new Object();obj.debug = false;obj.lang = "en";

//create an arrayvar 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 objectvar obj = {debug: false, lang: "en"};

//create an arrayvar 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 313

Page 314: BlackBerry WebWorks 2.1-Development Guide

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 inefficient—since it persists in memory much longer than necessary—and at risk for future namespace collisions.

//define global variablesvar lang = "en";var debug = true;

//define global functionfunction 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 314

Page 315: BlackBerry WebWorks 2.1-Development Guide

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 315

Page 316: BlackBerry WebWorks 2.1-Development Guide

Slower: Concatenating strings with + operator

str += "x" + "y";

When you concatenate strings by using the concatenation (+) operator, the following occurs:

1. A temporary string is created in memory,2. The concatenated value ("xy" in the example below) is assigned to the temporary string.3. The temporary string is concatenated with the variable's current value.4. 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 316

Page 317: BlackBerry WebWorks 2.1-Development Guide

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 317

Page 318: BlackBerry WebWorks 2.1-Development Guide

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 318

Page 319: BlackBerry WebWorks 2.1-Development Guide

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 319

Page 320: BlackBerry WebWorks 2.1-Development Guide

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 (table-layout:fixed).

JavaScript tips

• Cache computed styles.

Best Practices 320

Page 321: BlackBerry WebWorks 2.1-Development Guide

• For static styles, change the class names not the styles. For dynamic styles, edit the cssText property.

// bad - changing the stle - accessing DOM multiple timesvar myElement = document.getElementById('mydiv');myElement.style.borderLeft = '2px';myElement.style.borderRight = '3px';myElement.style.padding = '5px';

// good - use cssText and modify DOM oncevar 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 reflowsvar 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 copyvar 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.

// slowervar subElem = document.createElement('div'), elem = document.getElementById('animated');elem.appendChild(subElem);elem.style.width = '320px'; // fastervar subElem = document.createElement('div'), elem = document.getElementById('animated');elem.style.display = 'none'; // will not be repaintedelem.appendChild(subElem);elem.style.width = '320px';elem.style.display = 'block';

Best Practices 321

Page 322: BlackBerry WebWorks 2.1-Development Guide

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

// slowervar 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} // fastervar 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 322

Page 323: BlackBerry WebWorks 2.1-Development Guide

Legal notice©2014 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 at www.blackberry.com/go/docs 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 third-party 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 323

Page 324: BlackBerry WebWorks 2.1-Development Guide

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 324

Page 325: BlackBerry WebWorks 2.1-Development Guide

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.

Certain features outlined in this documentation require a minimum version of BlackBerry® Enterprise Server, BlackBerry® Desktop Software, and/or BlackBerry® Device Software.

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 Limited2200 University Avenue EastWaterloo, OntarioCanada N2K 0A7

BlackBerry UK Limited200 Bath RoadSlough, Berkshire SL1 3XEUnited Kingdom

Published in Canada

Legal notice 325

Page 326: BlackBerry WebWorks 2.1-Development Guide

Legal notice 326