Академический Документы
Профессиональный Документы
Культура Документы
Published: 2015-03-13
SWD-20150313105458214
Contents
Getting Started ........................................................................................................................................... 5
What's a BlackBerry WebWorks app?..............................................................................................................5
Components of the BlackBerry 10 WebWorks SDK..........................................................................................7
Setting up your system................................................................................................................................. 12
Creating a WebWorks project........................................................................................................................21
Creating your first app.................................................................................................................................. 24
Porting and Upgrading............................................................................................................................... 27
Upgrading from WebWorks 1.0.....................................................................................................................27
Updating your WebWorks project................................................................................................................. 34
Porting from Cordova................................................................................................................................... 35
Porting to other platforms.............................................................................................................................37
Porting AIR apps to WebWorks..................................................................................................................... 38
Adding Features........................................................................................................................................ 43
Adding and removing plugins....................................................................................................................... 43
Using custom plugins................................................................................................................................... 48
Modifying your app configuration..................................................................................................................56
Creating headless WebWorks apps............................................................................................................. 108
App integration.......................................................................................................................................... 114
BBM Social Platform.................................................................................................................................. 225
Payment Service........................................................................................................................................ 232
Push Service.............................................................................................................................................. 247
Frameworks............................................................................................................................................. 267
jQuery ....................................................................................................................................................... 267
Sencha Touch 2......................................................................................................................................... 270
Dojo Toolkit................................................................................................................................................272
Enyo 2.0.................................................................................................................................................... 275
Construct 2................................................................................................................................................ 277
bbUI toolkit................................................................................................................................................ 281
Building and Testing................................................................................................................................ 283
Setting up test targets................................................................................................................................ 283
Previewing your app in a browser................................................................................................................286
Building your app in debug mode............................................................................................................... 286
Deploying your app to a simulator...............................................................................................................287
Deploying your app to a device................................................................................................................... 289
Getting Started
Learn what HTML5 and the Cordova for BlackBerry platform have to offer, and build your first app.
In this section, you can find resources to help you get started developing applications for the BlackBerry
WebWorks platform.
Portability
Because you create them using common web standards, BlackBerry WebWorks apps are not platformdependent. When you port to other mobile platforms, such as iOS or Android, you can reuse many of your
existing web assets.
By aligning with Apache Cordova for BlackBerry WebWorks 2.0, your WebWorks apps will now have an even
greater level of compatibility. Cordova provides a common development layer, and makes adapting the output
Getting Started
to multiple mobile platforms much simpler. You create an app using the languages you know, and Cordova
handles the bindings to the native layer of the various platforms.
You can also take advantage of popular mobile web frameworks, such as Sencha Touch, jQuery Mobile, Dojo,
and others. These frameworks provide a wide range of useful APIs that can greatly simplify cross-browser web
development. Many of these frameworks also provide a BlackBerry theme to help you achieve the same look
and feel as apps written in C/C++. See Frameworks on page 267 for more information.
Integration
BlackBerry WebWorks APIs let you integrate your app with BlackBerry hardware, core apps, and services.
Standard HTML5 provides access to some BlackBerry device features, such as geolocation information and
device orientation, but the BlackBerry WebWorks APIs allow you to access BlackBerry specific data. For
example, you can check the battery power level, find out whether the device is holstered, or get brightness
information from the light sensor.
BlackBerry WebWorks APIs let you integrate with many of the core BlackBerry applications. For example, you
can integrate your app with BBM, Calendar, or Contacts.
You can invoke a single screen (called a card) from another app while in your app. This lets users interact with
another application to perform a specific task, such as picking a contact, composing an email, or previewing
an image, without leaving your app.
You can use BlackBerry WebWorks APIs to access:
App Integration: Launch another application in your app's UI.
Payment Service: Offer digital goods for sale in your app.
Push Service: Enable direct, near real-time content delivery to your application users.
For more information, see Adding Features on page 43.
Ease of access
An app packaged with BlackBerry WebWorks can use server data if it needs to. Load times can be reduced
because most of the logic and presentation layer of the app are already on the device. If you can make your
application's resources local to the BlackBerry device, users will be able to access your content even when
they don't have an Internet connection.
When you package your web app as a BlackBerry WebWorks app, you can publish it to BlackBerry World,
where users can find and buy it. No registration fees or submission fees are required to become a BlackBerry
World vendor. To learn more about publishing your app, see BlackBerry World on the BlackBerry Developer
website.
Getting Started
create an app
specify configuration settings
add plugins
build and deploy your app for testing
build and sign your app for production
By default, the UI displays only the projects you created with the web tool in your current browser. If you have a
project that was created outside the web tool or in a different browser, you can import it at any time. For more
information about importing projects, see Importing a WebWorks 2.0 project into the SDK web tool on page
23.
Note: To use the The BlackBerry 10 WebWorks SDK web tool, your browser must accept cookies. All
WebWorks project content that appears in the tool is stored in browser cookies. Deleting these cookies
removes the project data from the web tool, but leaves the project folders intact. No project information is lost,
but you have to import your projects to work with them in the web tool.
Getting Started
Command
Description
create-headless
target
help
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
serve
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.
Name
Description
com.blackberry.app
Application
com.blackberry.connection
Connection
com.blackberry.display
Display
com.blackberry.identity
Identity
com.blackberry.ui.input
Input
com.blackberry.invoke
Invoke
com.blackberry.invoke.card Card
com.blackberry.invoked
Invoked
Getting Started
Plugin ID
Name
Description
com.blackberry.io
IO
com.blackberry.io.filetransfe
r
com.blackberry.notification
Notification
Payment
com.blackberry.pim.calenda Calendar
r
com.blackberry.pim.contact Contacts
s
com.blackberry.push
PushPayload
PushService
Required permission:
access_pimdomain_contacts
Required permissions:
sys_use_consumer_push
run_when_backgrounded
com.blackberry.screenshot
Screenshot
com.blackberry.sensors
Sensors
com.blackberry.system
System
com.blackberry.ui.cover
Window Covers
Getting Started
10
Plugin ID
Name
Description
com.blackberry.ui.dialog
Dialog
com.blackberry.ui.toast
Toast
Name
Description
org.apache.cordova.camera Camera
org.apache.cordova.contact Contacts
s
org.apache.cordova.device
Device
org.apache.cordova.dialogs
Notification (Dialogs)
org.apache.cordova.file
File System
org.apache.cordova.filetransfer
File Transfer
org.apache.cordova.geoloca Geolocation
tion
Getting Started
11
Plugin ID
Name
Description
org.apache.cordova.inappbr InAppBrowser
owser
org.apache.cordova.media
Media
org.apache.cordova.mediacapture
Media Capture
org.apache.cordova.splashs Splashscreen
creen
System requirements
Before downloading and using the BlackBerry 10 WebWorks SDK, make sure that your system meets the
following requirements:
Runtime environment
Processor
Virtual environment
Storage space
RAM
2 GB RAM or more
Monitor
Getting Started
12
OS
Supported browsers
The BlackBerry 10 WebWorks SDK web tool has been tested against the following browsers:
Google Chrome
Mozilla Firefox
Safari (version 6 or later)
Internet Explorer (version 8 or later)
Cookie settings
To use the The BlackBerry 10 WebWorks SDK web tool, your browser must accept cookies. All WebWorks
project content that appears in the tool is stored in browser cookies. Deleting these cookies removes the
project data from the web tool, but leaves the project folders intact. No project information is lost, but you have
to import your projects to work with them in the web tool. For more information about importing projects, see
Importing a WebWorks 2.0 project into the SDK web tool on page 23.
13
Note: The BlackBerry ID token is used to create the debug token that allows you to install and test an
unsigned app on a BlackBerry 10 device. If you don't have a BlackBerry ID token, you cannot test your app
on a device.
14
Getting Started
15
Parameters
Description
-genkeypair
-storepass <bbidtoken_pw>
-dname "cn=<company_name>"
16
17
Description
-proxyhost <host>
The network server that provides the proxy service. The value can be
an IP address or a fully qualified domain name.
-proxyport <port>
The port number on your proxy server through which blackberrysigner or blackberry-debugtokenrequest should
communicate with the Signing Authority Service.
-proxyusername
<user name>
-proxypassword
<password>
Getting Started
18
option
Description
-bbidtoken
<bbid_token_file>
-storepass <keystore_pw>
The keystore password. You define this password when you request
your BlackBerry ID token.
<BAR_filename>
For example:
blackberry-signer -proxyhost 192.168.1.1 -proxyport 80 -bbidtoken
bbidtoken.csk
storepass MySecretPassword1 MyApp.bar
Getting Started
19
option
Description
-storepass <keystore_pw>
-devicepin<device PIN>
20
Getting Started
21
Description
<path>
<app-id>
<app-name>
Once your project is created, you may want to edit the configuration information, for example, to specify a
particular orientation or background color. For more information, see Modifying your app configuration on page
56.
Getting Started
22
Folder
Description
project_root/
This folder is the root folder, which you specify when you create your project.
This folder contains the master config.xml file.
www/
This folder contains all your project resources, including the index.html file,
which is the starting page for your app. It also contains subfolders for various
resources, including CSS and JavaScript files, as well as any other resources you
might add.
merges/
platforms/
The SDK uses this folder to maintain platform-specific versions of your project.
A blackberry10 folder is automatically created in this folder, and you can add
folders for additional platforms, such as Android or iOS.
When you build your app for a specific platform, the contents of the www/ folder
are copied to the appropriate platform-specific folder.
plugins/
This folder contains any plugins you add to your project. By default, this folder is
empty.
For more information on plugins, see Adding and removing plugins on page 43.
.cordova/
Getting Started
23
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click the arrow icon beside the Projects heading.
3. In the Project Path field, enter the complete path to the project.
4. Click Open.
24
Getting Started
25
Getting Started
26
27
Step 3. Replace the template resources in your new project with your existing resources
Delete the template project resources in your new BlackBerry WebWorks 2.0 project folders and paste your
application resources in their place. All your HTML files should be placed in the www folder; your CSS,
JavaScript, and image files can be placed in the appropriate subfolders of the www folder.
Note: You can choose to copy over your existing config.xml file, or build a new one based on the template
config.xml. However, in either case, you should be aware that the structure of the config.xml file has changed
slightly for BlackBerry WebWorks 2.0 and later. As a result, you may need to make some manual modifications
to your config.xml file. For more information on changes to the config.xml file, see Changes to the config.xml
file on page 31.
28
what the changes are and how to make your WebWorks 1.0 app compatible with the latest version of
WebWorks.
com.blackberry.app
29
<feature
id="blackberry.bbm.platform" />
com.blackberry.bbm.platform
<feature
id="blackberry.connection" />
com.blackberry.connection
com.blackberry.identity
<feature
id="blackberry.identity.phone" />
com.blackberry.user.identity
com.blackberry.invoke
<feature
id="blackberry.invoke.card" />
com.blackberry.invoke.card
com.blackberry.invoked
com.blackberry.io
<feature
id="blackberry.io.filetransfer" />
com.blackberry.payment
<feature
id="blackberry.pim.calendar" />
com.blackberry.pim.calendar
<feature
id="blackberry.pim.contacts" />
com.blackberry.pim.contacts
com.blackberry.push
com.blackberry.sensors
com.blackberry.system
<feature
id="blackberry.system.event" />
<feature
id="blackberry.ui.contextmenu" />
com.blackberry.ui.contextmenu
30
com.blackberry.ui.cover
com.blackberry.ui.dialog
com.blackberry.ui.toast
31
In BlackBerry WebWorks 1.0, you would define these configuration parameters by adding the following
elements to your config.xml file:
<feature id="blackberry.app">
<param name="orientation" value="portrait" />
</feature>
As of BlackBerry WebWorks 2.0, you must define these parameters using <preference> elements, which
are children of the top-level <widget> element. For example, to set the orientation as in the example above,
your config.xml file should now contain the following code:
<widget>
.
.
.
<preference name="orientation" value="portrait" />
</widget>
If you choose, you can set all preferences directly in the BlackBerry 10 WebWorks SDK web tool.
For more information on how to add the <preference> element to the config.xml file manually, see
<preference> on page 84.
Coding differences
If you have previously created a BlackBerry 10 WebWorks 1.0 app, it needs only a few small coding changes to
make it compatible with BlackBerry WebWorks 2.0 or later.
32
.
.
}
In BlackBerry WebWorks 2.0 or later, your projects need to listen for the deviceready event instead. You
should replace all instances of webworksready with deviceready. For example:
document.addEventListener('deviceready', function(e) {
.
.
.
}
33
8. Click Link Signing Keys. The developer certificate (the author.12 file) is created in the same location as
your signing key.
34
If updating your project breaks your project, submit a bug report using the Developer Issue Tracker.
35
36
Description
<id>
<path>
<uri>
37
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.
38
If your app is deployed within the work perimeter, then a WebWorks solution is the only viable alternative,
since Android apps are not permitted within the work perimeter.
Porting your AIR app to HTML5 actually provides a couple of additional built-in benefits:
HTML5 apps offer greater cross-platform compatibility than AIR apps. Most mobile platforms support
HTML5 apps to varying degrees, while AIR apps are only supported by Android devices, and on BlackBerry
devices as Android apps.
HTML5 apps are more future-proof than AIR apps. HTML5 is quickly emerging as the future of web
development.
There are several steps involved in porting your AIR app to WebWorks. Here's a summary of the process:
1.
2.
3.
4.
5.
6.
7.
39
40
When you are ready to create your own custom plugin, start with the BlackBerry template for Cordova
plugins.
41
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. Select Simulator.
5. Enter the device password used by your simulator.
6. Click Build & Install.
The tool packages your app into a .bar file, installs it on your simulator, and opens it.
When you are satisfied with the app and are ready to sign and distribute it, see Building and signing your
completed app on page 316.
42
Adding Features
Learn how to add plugins to your app and implement unique BlackBerry features.
In this section, you'll learn how to add plugins to your app and implement unique BlackBerry features.
43
Description
<id>
<path>
<uri>
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>
Adding Features
44
Name
Description
com.blackberry.app
Application
com.blackberry.connection
Connection
com.blackberry.display
Display
com.blackberry.identity
Identity
com.blackberry.ui.input
Input
com.blackberry.invoke
Invoke
com.blackberry.invoke.card Card
Adding Features
45
Plugin ID
Name
Description
com.blackberry.invoked
Invoked
com.blackberry.io
IO
com.blackberry.io.filetransfe
r
com.blackberry.notification
Notification
Payment
com.blackberry.pim.calenda Calendar
r
com.blackberry.pim.contact Contacts
s
com.blackberry.push
PushPayload
PushService
Required permission:
access_pimdomain_contacts
Required permissions:
sys_use_consumer_push
run_when_backgrounded
com.blackberry.screenshot
Screenshot
com.blackberry.sensors
Sensors
com.blackberry.system
System
Adding Features
46
Plugin ID
Name
Description
com.blackberry.ui.cover
Window Covers
com.blackberry.ui.dialog
Dialog
com.blackberry.ui.toast
Toast
Name
Description
org.apache.cordova.camera Camera
org.apache.cordova.contact Contacts
s
org.apache.cordova.device
Device
org.apache.cordova.dialogs
Notification (Dialogs)
org.apache.cordova.file
File System
org.apache.cordova.filetransfer
File Transfer
Adding Features
47
Plugin ID
Name
Description
org.apache.cordova.geoloca Geolocation
tion
org.apache.cordova.inappbr InAppBrowser
owser
org.apache.cordova.media
Media
org.apache.cordova.mediacapture
Media
org.apache.cordova.splashs Splashscreen
creen
48
Adding Features
49
Below is the JavaScript sample code showing the use of the cordova.exec function. We attach the plugin to
window, specifically to the echo function:
window.echo = function(str, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "Echo", "echo", [str]);
};
Let's take a detailed look at the last three arguments to the exec function. Here, the exec function is calling
the "Echo" service, requesting the "echo" action, and passing the array containing the "str" argument. The
string str represents the string that is to be echoed and is the first parameter into the window.echo
function. Note that the success callback passed into the exec function is simply a reference to the callback
function that window.echo takes (it's the second parameter).
We do a bit more for the error callback. If the native side fires off the error callback, we simply invoke the
success callback and pass into it a default string to echo back and indicate that an error has occured (using
the string 'Nothing to echo.').
For example, you can use this plugin as follows:
window.echo("echome", function(echoValue) {
alert(echoValue == "echome"); // should alert true, if there is no
error
});
We can now use what we learned about the cordova.exec function and create an Echo plugin for the
BlackBerry 10 platform.
Creating the JavaScript part of your plugin
The JavaScript portion of your plugin must contain a client.js and an index.js file:
client.js This is considered the client side and contains the API that a Cordova application can call. The
API in client.js makes calls to index.js. The API in client.js also connects callback functions to the events
that fire the callbacks.
index.js This is considered the server side. Cordova loads index.js and makes it accessible through the
cordova.exec bridge. The client.js file makes calls to the API in the index.js file, which in turn makes
calls to JNEXT to communicate with the native side.
var service = "org.apache.cordova.blackberry.echo",
exec = cordova.require("cordova/exec");
module.exports = {
echo: function (data, success, fail) {
exec(success, fail, service, "echo", { data: data });
}
};
Adding Features
50
51
}
};
JNEXT.registerEvents(self);
self.m_id = "";
};
self.getInstance = function () {
if (!hasInstance) {
self.init();
hasInstance = true;
}
return self;
};
2. When your application calls the echo function in client.js, that call in turn calls the echo function in
index.js, where the PluginResult object sends a response (data) back to client.js. Since the args
argument passed into the functions was converted by JSON.stringfy() and encoded as a
URIcomponent, you must decode the data before you send it with the response:
data = JSON.parse(decodeURIComponent(args.data));
Now we are ready to send the data back. Here's how it turns out when you put it all together:
module.exports = {
echo: function (success, fail, args, env) {
};
Adding Features
52
Adding Features
53
InvokeMethod(): The InvokeMethod() function is called when JavaScript invokes a method of this
particular object. The only argument this function takes is a string passed from JavaScript that
InvokeMethod() parses in order to determine which method of the native object should be executed.
Now we implement these functions in echo_js.cpp. For the Echo example, we implement the
InvokeMethod() function as follows:
string Echo::InvokeMethod(const string& command) {
//parse command and args from string
int index = command.find_first_of(" ");
string strCommand = command.substr(0, index);
string strValue = command.substr(index + 1, command.length());
Your native plugin must also implement the onGetObjList() and onCreateObject() callback
functions:
extern char* onGetObjList(void);
The onGetObjList() function returns a comma-separated list of classes supported by JNEXT. JNEXT
uses this function to determine the set of classes that it can instantiate. In our Echo plugin, we have the
following in echo_js.cpp:
char* onGetObjList() {
static char name[] = "Echo";
return name;
}
extern JSExt* onCreateObject(const string& strClassName, const string&
strObjId);
The onCreateObject() function takes two parameters. The first parameter is the name of the class
requested to be created from the JavaScript side. Valid names are those that are returned in
onGetObjList(). The second parameter is the unique object ID for the class. This method returns a
pointer to the created plugin object. In our Echo plugin, we have the following in echo_js.cpp:
JSExt* onCreateObject(const string& className, const string& id) {
if (className == "Echo") {
return new Echo(id);
}
return NULL;
}
Adding Features
54
Adding Features
55
Community plugins
BlackBerry WebWorks is an open source project. Members of the open source community can create their
own plugins to extend the functionality of the SDK and can make those plugins available to the wider
community. These plugins provide access to native libraries that are not otherwise available through the
WebWorks or Cordova APIs, or through standard HTML5 functions.
Feel free to use any of the available community plugins in your WebWorks app, or contribute your own custom
plugin to the community.
Description
App ID
App Name
Adding Features
56
Preference
Description
Icon
Project Location
App Description
Author
Author Email
Author URL
License
Main URL
The start page that the BlackBerry WebWorks app displays when it
runs.
Orientation
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.
Adding Features
57
Preference
Description
Access List
Permissions
Adding Features
58
Adding Features
59
Here's how you can ensure that your file system requests are permitted:
<access origin="file:///" subdomains="true" />
60
plugin does not automatically add the permission. Instead, you must add the permission yourself, either using
the BlackBerry 10 WebWorks SDK web tool, or by manually adding them to the config.xml file.
61
plugin that accesses the device's microphone to record audio, you must add the record_audio permission. For
a complete list of native app permissions, see App permissions in the BlackBerry 10 Native SDK
documentation.
Functionality or
capability
Camera
Device information
Location information
Shared files
Push
Run in background
Permission value
Description
use_camera
access_shared
_sys_use_consumer_push
run_when_backgrounded
Adding Features
62
Functionality or
capability
Permission value
Description
processing in the background.
Running the app in the background
can negatively impact the battery life
of the device.
Contacts
Calendar
Notifications
bbm_connect
access_pimdomain_messages
access_pimdomain_contacts
access_pimdomain_calendars
post_notifications
63
Adding Features
64
3. Within the <platform> element for BlackBerry 10, add a <preference> element. For example:
<platform name="blackberry10">
<preference name="SpatialNavigation" value="enable" />
</platform>
Defining the navigation path for spatial navigation
Spatial navigation allows the user to navigate from one focusable element to another. A focusable element is
an element that the user can select and can interact with. For example, an input field must receive focus to
allow the user to type input. When a link receives focus, the link is highlighted, and the user can follow the link
by pressing the Enter key.
Spatial navigation doesn't require that you add any plugins to your project. You can use standard HTML and
CSS to define which elements can receive focus, and how the user can navigate through those elements:
In the HTML source, you can set the tabindex attribute for an element. This attribute allows you to define
a value to an element that defines the element's position in the navigation path.
Using the CSS navigation properties, nav-left, nav-right, nav-up, and nav-down, you can define
which element receives focus based on the direction that the user swipes on the trackpad. The elements
that you specify as the targets of these properties become part of the navigation path, even if you haven't
set the tabindex attribute for those elements. These CSS navigation properties provide greater control
over the navigation path than the tabindex attribute.
If you don't set the tabindex attribute or CSS navigation properties, WebWorks provides a default navigation
path. In this case, the following elements receive focus in the order they appear:
<a>
<button>
<iframe>
<input>
<select>
<textarea>
Best practices
Define the trackpad navigation path logically. Carefully consider how the user is likely to move around your
app as you define a navigation path. Make sure that the focus doesn't jump around unexpectedly.
65
Description
nav-down
nav-left
nav-right
nav-up
66
nav-up:
#link1;
In this example, the CSS navigation properties define which elements receive focus based on the direction the
user swipes the trackpad. Let's assume Link 2 has focus. When the user swipes up or to the right, Link 3
receives focus. When the user swipes down or to the left, Link 1 receives focus.
Best practices
Avoid unnecessary customization of the navigation keys. Although the Menu and Back keys can be
customized, be cautious about deviating from their typical behavior. Users expect the navigation keys to
work the same way in every app and context.
Handling menubutton and backbutton input events
Note: The menubutton and backbutton events are part of the com.blackberry.app plugin. To access these
events, you need to add the com.blackberry.app plugin to your project using either the SDK web tool or the
webworks plugin add command.
1. To attach an event listener that listens for the Menu or Back key to be pressed, use
document.addEventListener. You must add the listener after the deviceready event fires. For
example:
document.addEventListener("deviceready", function () {
document.addEventListener('menubutton', onMenuButton);
document.addEventListener('backbutton', onBackButton);
});
Adding Features
67
2. To specify the app behavior when each key event fires, add the callback functions. For example:
function onMenuButton() {
console.log("The Menu button was pressed");
}
function onBackButton() {
console.log("The Back button was pressed");
}
68
<name>Sample application</name>
<description>
A sample application to demonstrate some features.
</description>
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>access_location_services</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
<icon src="icons/icon-150.png"/>
<rim:splash src="splash-1280x768.png"/>
<rim:splash src="splash-768x1280.png"/>
<content src="index.html"/>
<preference name="orientation" value="portrait" />
<preference name="backgroundColor" value="0xFFFF0000" />
<access uri="http://www.somedomain.com" subdomains="true" />
<license href="http://www.example.com/"/>
</widget>
Elements in config.xml
The following table describes each element that can be used in the configuration document. It also specifies
how many times you can use each element in your config.xml file for a particular platform.
Element
Description
Occurrences
<access>
zero or more
<author>
one
<content>
one
<description>
zero or more
<icon>
zero or more
Adding Features
69
Element
Description
Occurrences
<license>
one or none
<name>
one or more
<platform>
<preference>
zero or more
<rim:action>
one or more
<rim:filter>
zero or more
<rim:invoke-target>
zero or more
<rim:mime-type>
one or more
<rim:permissions>
one
<rim:permit>
one or more
<rim:property>
zero or more
<rim:splash>
<rim:type>
one
<widget>
one
<access>
Syntax:
<access origin="string" subdomains=["true" | "false"] />
Adding Features
70
Description:
The <access> element specifies that a BlackBerry WebWorks app can access external network resources. By
default, if you do not specify an <access> element, an app has access to local resources only, which includes
all resources packaged in the apps .bar file.
If you specify more than one <access> element, the most specific definition is used. For example, if you use
http://somedomain.com and http://specific.somedomain.com, the <access> element that
uses the first definition (and any features defined under it) is ignored.
As a best practice, you should protect your communication channel by using HTTPS when you expose
sensitive APIs to the domain. For information about best practices on securing your app, see Accessing
external resources on page 59.
Occurrences:
Zero or more.
Parent elements:
<widget>
Child elements:
None.
Content:
None.
Attributes:
You can define the following attributes for this element:
Attribute
Description
origin
Optional. The origin attribute defines the web address for the access request.
You can specify a wildcard (*) for the origin attribute to whitelist any domain,
but only for domains that do not access content through XMLHttpRequest. If
the domain accesses data through XMLHttpRequest, you must explicitly
specify the domain for the origin attribute.
Adding Features
71
Attribute
Description
uri
Deprecated. The uri attribute defines the web address for the access request.
This attribute is only supported for backwards compatability. Going forward, you
should use the origin attribute.
subdomains
Example:
The following example shows how to whitelist an external resource, in this case, the domain somedomain, as
well as any subdomains.
<access origin="https://somedomain.com" subdomains="true"/>
<author>
Syntax:
<author href="string"
rim:copyright="string"
email="string"
rim:copyright="string"
xml:lang="string">
string
</author>
Description:
The <author> element pecifies the name (typically the company or developer name) you used to register
your signing account.
You can access this element by using the blackberry.app.author property that is provided in the
BlackBerry WebWorks API.
Occurrences:
One.
Adding Features
72
Parent elements:
<widget>
Child elements:
None.
Content:
A string value representing the name of the developer or organization that you registered your signing account
with.
Attributes:
You can define the following attributes for this element:
Attribute
Description
href
Optional. The href attribute specifies a web address that is associated with the
author (for example, the web page of the author).
You can access this attribute by using the blackberry.app.authorURL
property that is provided in the BlackBerry WebWorks API.
rim:copyright
Optional. The email attribute specifies the email address that is associated with
the author.
You can access this attribute by using the blackberry.app.authorEmail
property that is provided in the BlackBerry WebWorks API.
xml:lang
Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
Adding Features
73
Attribute
Description
its:dir
Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.
Example:
<author href="http://www.example.com/"
rim:copyright="Copyright 1998-2012 My Corp">My Corp</author>
<content>
Syntax:
<content src="string"
rim:allowInvokeParams=["true" | "false"]
type="string"
charset="string" />
Description:
The <content> element specifies the start page that the BlackBerry WebWorks application displays when it
runs. The start page can contain the web address of a file that is located outside of the application archive.
Occurrences:
One.
Parent elements:
<widget>
Child elements:
None.
Content:
None.
Adding Features
74
Attributes:
You can define the following attributes for this element:
Attribute
Description
src
Required. The src attribute specifies the source HTML file in the
application archive.
rim:allowInvokeParams
type
Optional. The type attribute specifies the MIME type of the file that is
specified in the src attribute.
charset
Optional. The charset attribute specifies the character set that is used
by the file that is specified in the src attribute.
Example:
The following example shows how to specify a start page called startpage.html.
<content src="startpage.html" />
<description>
Syntax:
<description>string</description>
Description:
The <description> element specifies a human-readable description for a BlackBerry WebWorks app.
You can access this element by using the blackberry.app.description property that is provided in the
BlackBerry WebWorks API.
Adding Features
75
Occurrences:
One.
Parent elements:
<widget>
Child elements:
None.
Content:
A string value representing a human-readable description of the app.
Attributes:
You can define the following attributes for this element:
Attribute
Description
xml:lang
Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
its:dir
Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.
Example:
<description>
This application displays "Hello World" on the screen.
</description>
<icon>
Syntax:
<icon src="string" />
Adding Features
76
Description:
The <icon> element specifies a custom icon for a BlackBerry WebWorks app. The icon that you specify in the
src attribute is used to identify your app on the Home screen of the BlackBerry device.
The icon must meet the requirements for custom or default icons. Your icon image should be 24-bit PNG
format with an alpha channel. For information about designing icons for BlackBerry 10, see the UI Guidelines.
This element is optional. If you do not specify an icon for your app, the BlackBerry 10 WebWorks SDK uses the
default application icon.
Occurrences:
Zero or more.
Parent elements:
<platform>
Note: Although it is permitted to include the <icon> element as a child of <widget>, for future crossplatform compatibility, you should add all <icon> elements as children of a <platform> element.
Child elements:
None.
Content:
None.
Attributes:
You can define the following attributes for this element:
Attribute
Description
src
rim:hover
A Boolean value that specifies whether the icon is used as a hover icon. The first
hover icon in the configuration document is used as the hover icon for the
application.
Adding Features
77
Attribute
Description
By default, if you do not specify a value for the rim:hover attribute, the value is
set to false.
This attribute is optional.
Examples:
Targeting multiple screen sizes
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. For example:
<platform name="blackberry10">
<icon src="icon-86.png" />
<icon src="icon-150.png" />
</platform>
Using localized icons
You can also use localized icons for BlackBerry 10 applications. To use localized icons, the image files must
be:
Named the same as the nonlocalized image file name that you specified in the <icon> element.
Stored in the appropriate locale subfolder that corresponds with the localized language.
When you use localized images, the files must be stored in individual locale folders (for example, "/locales/enUS", "/locales/fr") which are direct descendants of the root locales folder. The locales folder must be
located in the root of your application folder so that the BlackBerry WebWorks Packager can build your
application. The locale strings specified in the folder name must use the naming conventions that are specified
in the Internet Engineering Task Force (IEFT) Best Current Practice (BCP) 47 specification. For example, you
can use the Language-Region naming convention as in the following examples: en-US (United States English),
de-DE (German for Germany), and fr-CA (Canadian French).
The file names for the localized images must be named exactly as the nonlocalized image files that you
specified in the icon element. You can store the nonlocalized images in subfolders but the locale folder must
use the same subfolder structure for the localized images. When the BlackBerry 10 OS is set to one of the
locales (for example, German or French) and localized images are present for that locale, the BlackBerry 10
OS selects the images from the respective locale subfolder. If no localized images are available for the
specified locale, the BlackBerry 10 OS selects the nonlocalized icon image located in the root.
For example, assume that our WebWorks project includes the following files:
locales/de/icon-86.png
locales/de/icon-150.png
Adding Features
78
locales/fr/icon-86.png
icon-86.png
icon-150.png
In our config.xml file, we include the following entries:
<platform name="blackberry10">
<icon src="icon-86.png" />
<icon src="icon-150.png" />
</platform>
In this example, if the French locale is set on the device, even if the optimum icon resolution is 150x150, the
BlackBerry 10 OS uses the locales/fr/icon-86.png file because it's the only icon image available for
this locale.
<license>
Syntax:
<license>string</license>
Description:
The <license> element specifies the end-user license agreement or a copyright statement for a BlackBerry
WebWorks app. This element is optional. If you specify this element, you can implement a feature to prompt
BlackBerry device users to accept or decline the license agreement when they run the application for the first
time. After users agree to the license agreement, the prompt does not appear when they run the application
again.
The contents of the license agreement are also available on the About screen for the app.
Occurrences:
Zero or one.
Parent elements:
<widget>
Child elements:
None.
Content:
A string value representing an end-user license agreement or a copyright statement.
Adding Features
79
Attributes:
You can define the following attributes for this element:
Attribute
Description
xml:lang
Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
its:dir
Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.
href
Optional. The href attribute specifies a web address for a web page that
contains content or license information.
Example:
<license>
Example license
Copyright 2012 My Corp.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, INSULT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</license>
<name>
Syntax:
<name>string</name>
Description:
The <name> element specifies a human-readable name for a BlackBerry WebWorks app that you can use, for
example, in an application menu.
Adding Features
80
If you do not specify a name element, the app is not valid. For BlackBerry 10 apps, the name must be 25
characters or less.
You can also specify a name by using the blackberry.app.name property that is provided in the
BlackBerry WebWorks API.
Occurrences:
One.
Parent elements:
<widget>
Child elements:
None.
Content:
A string value representing a human-readable name for the WebWorks app.
Attributes:
You can define the following attributes for this element:
Attribute
Description
xml:lang
Optional. The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
its:dir
Optional. The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from right to left.
For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.
Example:
<name>Hello World! application</name>
Adding Features
81
<platform>
Syntax:
<platform name="blackberry10">
<rim:permissions>
<rim:permit> ...</rim:permit>
</rim:permissions>
</platform>
Description:
The <platform> element contains platform-specific application information. For example, using the
<platform> element, you can specify a platform-specific splash screen image for your cross-platform app,
and specify app permissions or preferences that are specific to the BlackBerry 10 OS. Invocation settings,
which are also specific to BlackBerry 10, must also be defined within a <platform> element.
If you are developing a cross-platform app, you should have one <platform> element for each platform you
are targeting with your app.
Occurrences:
Zero or more.
Parent elements:
<widget>
Child elements:
Name
Occurrences
<icon>
zero or more
<preference>
zero or more
<rim:invoke-target>
zero or more
<rim:permissions>
zero or more
<rim:splash>
one or none
Adding Features
82
Content:
None.
Attributes:
You can define the following attributes for this element:
Attribute
Description
name
Required. Specifies the platform name. The value for name is case insensitive.
In a BlackBerry WebWorks app, you should have an instance of <platform>
with a name value of blackberry10.
Other supported values include:
ios
android
firefoxos
tizen
wp8
windows8
Examples:
Registering bound and unbound invocations of a BlackBerry app
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</platform>
</widget>
Adding Features
83
Syntax:
<preference name="string" value="string" />
Description:
The <preference> element defines a preference for the blackberry.app plugin (for example, screen
orientation).
Occurrences:
Zero or more.
Parent elements:
<platform>
<widget>
Child elements:
None.
Content:
None.
Attributes:
You can define the following attributes for this element:
Adding Features
84
Attribute
Description
name
Required. Specifies the name of the preference that you are defining. For a
complete list of preferences that you can specify for name, see the Preferences
table below.
value
Required. Specifies the value of the preference that you are defining. For a
complete list of valid values for each preference, see the Preferences table below.
Preferences:
The following table lists the preferences that you can specify using the name attribute, with their associated
values. In all cases, the name value is case insensitive.
Preference
Description
Orientation
AutoHideSplashScre
Hides the splash screen for your application. The value can be "true" or
en
"false", with "true" being the default. When false, the splash screen is
displayed until splashscreen.hide() is invoked.
Adding Features
85
Preference
Description
Example
<preference name="AutoHideSplashScreen"
value="false" />
BackgroundColor
Specifies the background color for your application. The value must specify a
color value in the ARGB pixel format using 8 hexadecimal digits.
Example
<preference name="BackgroundColor"
value="0xffff0000" />
ChildBrowser
Disables child browser windows. By default, when the content tries to open a
resource in a new window or tab (by using window.open(), or by specifying
_blank as the target of an anchor), the WebWorks app opens a secondary
browser window to display the resource. This feature is enabled by default.
The value must specify a value of "disable".
Example
<preference name="ChildBrowser" value="disable" />
DiskCache
Enables WebView caching, which prevents the app from issuing multiple network
requests for the same resource.
The value can be either "disable" or "enable". The default value is
"disable".
Example
<preference name="DiskCache" value="enable" />
HideKeyboardFormAc
When enabled, hides the row of buttons (Previous, Next, and Submit) that is
cessoryBar
displayed by default when an <input> element on the current page of the app
gets focus.
The value can be either "disable" or "enable". The default value is
"disable".
Adding Features
86
Preference
Description
Example
<preference name="HideKeyboardFormAccessoryBar"
value="enable" />
PopupBlocker
Enables the popup blocker, which prevents your app from displaying popups. By
default, WebWorks apps display popups in a child browser window.
The value attribute must specify a value of "enable".
Example
<preference name="PopupBlocker" value="enable" />
SpatialNavigation
WebSecurity
Disables web security. Disabling web security allows you to access remote
content from unknown sources. Before packaging your app for distribution, you
should remove this setting unless it is explicitly required.
This feature is intended primarily as a development convenience. In production,
all URIs should generally be known and should be whitelisted using the
<access> element.
Adding Features
87
Preference
Description
The value attribute must specify a value of "disable".
Example
<preference name="WebSecurity" value="disable" />
<rim:action>
Syntax:
<action>string</action>
Description:
The <action> element specifies the actions that are associated with the invocation target. Actions are strings
that identify the operations that your application is registered to handle. Actions can be discoverable actions or
menu actions. Menu actions always have a label and icon associated with them, while discoverable actions do
not.
Occurrences:
One or more.
Parent elements:
<filter>
Child elements:
None.
Content:
A string value representing the actions that are available to query.
The following predefined, discoverable actions are examples of actions that are available. These actions do not
have graphics or labels represented on the user interface but can be queried.
bb.action.VIEW
Describes the request to open a card or viewer based on the given MIME type, URI, or file extension. This
action should be used in cases where you register a card or viewer as a default handler.
Adding Features
88
bb.action.NOTIFY
Describes the act of notification which can be associated with different types, such as the BlackBerry
Push Service.
The following fixed menu actions are examples of actions that are available. These actions are represented in
the OS using graphics or labels and can differ based on the locale and region settings.
bb.action.OPEN
Describes the request to open associated content in a different application. You can use this action in
cases where you want a full-context switch from one application to another. Use this action in scenarios
where a full application is registering as a default handler.
bb.action.SET
Describes the request to set the associated content in a given context. For example, wallpaper, images of
contacts, BlackBerry Messenger SDK avatars, ring-tones, and so on.
bb.action.SHARE
Describes the request to share associated content. For example, you can share an image to a Bluetooth
target, which would transfer the image to another device via Bluetooth.
Attributes:
None.
Example:
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</platform>
<rim:filter>
Syntax:
<rim:filter>
<rim:action>string</rim:action>
<rim:mime-type>mime_type</rim:mime-type>
Adding Features
89
Description
The <rim:filter> element specifies the target filter. For each target, filters must be declared to describe
the kinds of unbound invocation they support. Each filter defines the associated action performed for MIME
types that match the filter. Clients perform unbound invocation by sending the invocation without specifying a
target. Unbound invocations should generally provide an action, but must provide either a MIME type, URI, or
both.
Occurrences:
Zero or more.
Parent elements
<rim:invoke-target>
Child elements:
Name
Occurrences
<rim:action>
zero or more
<rim:mime-type>
one or none
<rim:property>
one
Content:
None.
Attributes:
None.
Example
Registering bound and unbound invocations
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
Adding Features
90
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<rim:type>APPLICATION</type>
<rim:filter>
<rim:action>bb.action.OPEN</rim:action>
<rim:action>bb.action.SET</rim:action>
<rim:mime-type>text/*</rim:mime-type>
<rim:property var="exts" value="bmp,css,html,js" />
<rim:property var="uris" value="data://local,file://" />
</rim:filter>
</rim:invoke-target>
</platform>
</widget>
<rim:invoke-target>
Syntax:
<rim:invoke-target id="string">
<type>[ APPLICATION | VIEWER ]</type>
<filter>
<action>string</action>
<mime-type>mime_type</mime-type>
<property var=["exts" | "uris"] value="string" />
</filter>
</rim:invoke-target>
Description:
You can use the <rim:invoke-target> element to register your BlackBerry WebWorks application as a
handler for invocation events. In BlackBerry 10 OS, the invocation framework provides the ability by which a
client process can send a message to a target process so it can perform a certain action.
If you register your application with the invocation framework, your application can be invoked through:
Bound invocation: The target is invoked by using an identifier.
Unbound invocation: The target is invoked without specifying a target.
Bound and unbound invocation: The target is invoked by using an identifier and other attributes.
All invocations must specify an action that the target must perform as well as data to be acted upon. The data
can be specified by using a combination of MIME types, URIs, and file extensions.
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:invoke-target> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Adding Features
91
Occurrences:
Zero or more.
Parent elements:
<platform>
Child elements:
Name
Occurrences
<rim:filter>
zero or more
<rim:type>
one
Content:
None.
Attributes:
You can define the following attributes for this element:
Attribute
Description
rim:id
Required. Specifies a globally unique name. This name is verified when you sign
the application. It's recommended that you use the reverse-DNS naming
convention.
Example: com.ea.needforspeed.target
Example:
Registering bound and unbound invocations
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
Adding Features
92
<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</platform>
</widget>
Registering multiple filters against an invocation
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>application/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>audio/*</mime-type>
<mime-type>image/*</mime-type>
<mime-type>message/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
<filter>
<action>bb.action.VIEW</action>
<mime-type>text/*</mime-type>
</filter>
<filter>
<action>bb.action.SET</action>
<mime-type>image/*</mime-type>
<property var="exts" value="bmp,png,jpg,gif" />
</filter>
</rim:invoke-target>
</plaftorm>
</widget>
Registering multiple targets against an invocation type
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
Adding Features
93
<filter>
<action>bb.action.OPEN</action>
<mime-type>image/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
</rim:invoke-target>
<rim:invoke-target id="com.domain.subdomain.appname.view">
<type>VIEWER</type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>image/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
</rim:invoke-target>
</platform>
</widget>
Code sample: Parsing invoke parameters
When you set the <content> element's rim:allowInvokeParams attribute to a value of true, the start
up parameters for the application are available to the start page as a query string. You can parse the query
string using JavaScript.
function parseQueryString() {
// Create result container
var queryParamResult;
// Start at 1 to skip the leading '?'
var query = window.location.search.substring(1);
// Split the string on key-value pairs
var params = query.split('&');
// Loop through the pairs
for ( var i = 0 ; i < params.length ; i++ ) {
// Locate the '='
var position = params[i].indexOf('=');
if ( position > 0 ) {
// Text before the '=' is the key
var key = params[i].substring( 0, position );
// Text after the '=' is the value
var value = params[i].substring( position + 1 );
Adding Features
94
return queryParamResult;
<rim:mime-type>
Syntax:
<rim:mime-type>mime_type</rim:mime-type>
Description:
The <rim:mime-type> element defines a valid MIME type for the data.
Occurrences:
One or more.
Parent elements:
<rim:filter>
Child elements:
None.
Content:
A string value representing the MIME type for a file. The grammar for the MIME type must support the following
specifications:
RFC 2045 (content-types)
RFC 4288 (IANA registration)
Attributes:
None.
Example:
<rim:filter>
<rim:action>bb.action.VIEW</rim:action>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
</rim:filter>
Adding Features
95
<rim:permissions>
Syntax:
<rim:permissions>
<rim:permit>permission_string</rim:permit>
</rim:permissions>
Description:
The <rim:permissions> element is a container element for the <rim:permit> element, which specifies
the permissions for various features in a BlackBerry WebWorks application.
See the <rim:permit> element for information about permission features.
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:permissions> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Occurrences:
One or none.
Parent elements:
<platform>
Child elements:
<rim:permit>
Content:
None.
Attributes:
None.
Adding Features
96
Example:
The following sample demonstrates how to set the permissions for reading and writing files, reading GPS
location information, and accessing camera data.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<platform name="blackberry10">
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
</platform>
<widget>
<rim:permit>
Syntax:
<rim:permissions>
<rim:permit>permission_string</rim:permit>
</rim:permissions>
Description:
The <rim:permit> element specifies permission access to various features in a BlackBerry WebWorks
application (for example, accessing the GPS location or the camera).
Note:
You must include the following namespace declaration in the top-level <widget> element to use the
<rim:permit> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Occurrences:
One or more.
Parent elements:
<rim:permissions>
Child elements:
None.
Adding Features
97
Content:
A string value representing a valid permission value. See the list of Permissions below for more information.
Attributes:
You can define the following attributes for this element:
Attribute
Description
system
Permissions:
The following table identifies the available permissions for WebWorks plugins, which are required to access
specific native functionality or capabilities.
Note: This list of permissions represents only those permissions that may be required when adding the
WebWorks or Cordova plugins that are installed with the BlackBerry 10 WebWorks SDK. Custom plugins may
require permissions that are not listed here. For example, to use a custom plugin that accesses the device's
microphone to record audio, you must add the record_audio permission. For a complete list of native app
permissions, see App permissions in the BlackBerry 10 Native SDK documentation.
Permission value
Description
access_operational_data_domain
access_startup_data_domain
Functionality or
Capability
Adding Features
98
Functionality or
Capability
Permission value
Description
are data lock aware. For more
information about data lock, see
Creating apps that are data lock
aware.
Calendar
Camera
Contacts
Device information
Location information
bbm_connect
access_pimdomain_calendars
use_camera
access_pimdomain_contacts
read_device_identifying_inform
ation
access_pimdomain_messages
access_location_services
Adding Features
99
Functionality or
Capability
Notifications
Push
Run headless
Permission value
Description
post_notifications
_sys_use_consumer_push
_sys_run_headless
Run in background
run_when_backgrounded
Shared files
access_shared
Adding Features
100
Example:
The following example demonstrates how to set the permissions for reading and writing files, recording audio,
accessing camera data, and push.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>record_audio</rim:permit>
<rim:permit>use_camera</rim:permit>
<rim:permit system="true">_sys_use_consumer_push</rim:permit>
</rim:permissions>
<widget>
<rim:property>
Syntax:
<rim:property var=["exts" | "uris"] value="string" />
Description:
The <rim:property> element defines the types of URIs or files that the app supports. The URI schemes or
file extensions that you specify are used to register an unbound invocation.
Occurrences:
Zero or more.
Parent elements:
<rim:filter>
Child elements:
None.
Content:
None.
Attributes:
You can define the following attributes for this element:
Adding Features
101
Attribute
Description
var
Required. Specifies how the app is invoked. The invocation framework supports
invocation by URI or by file extensions. The value can be uris or exts.
value
Example:
<rim:filter>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
<rim:property var="uris" value="file://,pdf://" />
<rim:property var="exts" value="pdf" />
</rim:filter>
<rim:splash>
Syntax:
<rim:splash src="string" />
Description:
The <rim:splash> element specifies the image to display on the screen while the BlackBerry 10 device
loads your application. This element is optional.
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. Your splash screen image should fit
the entire screen size so that it fills the screen. For information about BlackBerry 10 screen sizes, see the
BlackBerry UI Guidelines.
The image for your splash screen can be any of the following file formats: .png, .jpg, .jpeg, .gif, or .bmp.
Note:
Adding Features
102
You must include the following namespace declaration in the parent <widget> element to use the
<rim:splash> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Occurrences:
Zero or more.
Parent elements:
<platform>
Child elements:
None.
Content:
None.
Attributes:
You can define the following attribute for this element:
Attribute
Description
src
Required. Specifies the path for an image file in the application archive.
Examples:
Targeting multiple screen sizes
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. For example:
<platform name="blackberry10">
<rim:splash src="splash-1024x600.png"
<rim:splash src="splash-600x1024.png"
<rim:splash src="splash-1280x768.png"
<rim:splash src="splash-768x1280.png"
</platform>
/>
/>
/>
/>
Adding Features
103
You can also use localized splash screens for BlackBerry 10 applications. To use localized image files for the
splash screen, the image files must be:
Named the same as the nonlocalized image file that you specified in the <rim:splash> element.
Stored in the appropriate locale subfolder that corresponds with the localized language.
When you use localized images, the files must be stored in individual locale folders (for example, "/locales/enUS", "/locales/fr") which are direct descendants of the root locales folder. The locales folder must be
located in the root of your application folder so that the BlackBerry WebWorks Packager can build your
application. The locale strings specified in the folder name must use the naming conventions that are specified
in the Internet Engineering Task Force (IEFT) Best Current Practice (BCP) 47 specification. For example, you
can use the Language-Region naming convention as in the following examples: en-US (United States English),
de-DE (German for Germany), and fr-CA (Canadian French).
The file names for the localized images must be named exactly as the nonlocalized image files that you
specified in the <rim:splash> element. You can store the nonlocalized images in subfolders but the locale
folder must use the same subfolder structure for the localized images. When the BlackBerry 10 OS is set to one
of the locales (for example, German or French) and localized images are present for that locale, the BlackBerry
10 OS selects the images from the respective locale subfolder. If no localized images are available for the
specified locale, the BlackBerry 10 OS selects the nonlocalized icon image located in the root.
For example, assume that our WebWorks project includes the following files:
locales/de/splash-1024x600.png
locales/de/splash-600x1024.png
locales/de/splash-1280x768.png
locales/de/splash-768x1280.png
locales/fr/splash-1280x768.png
locales/fr/splash-768x1280.png
splash-1024x600.png
splash-600x1024.png
splash-1280x768.png
splash-768x1280.png
In this example, if the French locale is specified on the device, even if the optimum resolution is 1024x600, the
BlackBerry 10 OS uses the locales/fr/splash-1280x768.png file because it's the only landscape
image available for this locale.
<rim:type>
Syntax:
<rim:type>[ application | viewer ]</rim:type>
Description:
The <rim:type> element defines the type of the target.
Adding Features
104
Occurrences:
One.
Parent elements:
<rim:invoke-target>
Child elements:
None.
Content:
A string value specifying the target type. You can define the target as one of the following types:
application
The target is an application and is started only when required.
viewer
The target reference always spawns a new window and window reparenting is required.
Attributes:
None.
Example:
<rim:invoke-target id="com.mycompany.pdf.viewer">
<rim:type>viewer</rim:type>
<rim:filter>
<rim:action>bb.action.VIEW</rim:action>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
</rim:filter>
</rim:invoke-target>
<rim:invoke-target id="com.mycompany.pdf.app">
<rim:type>application</rim:type>
<rim:filter>
<rim:action>bb.action.EDIT</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
<rim:mime-type>application/x-pdf</rim:mime-type>
<rim:property var="uris" value="file://,pdf://" />
<rim:property var="exts" value="pdf" />
</rim:filter>
<rim:filter>
<rim:action>bb.action.VIEW</rim:action>
<rim:mime-type>application/pdf</rim:mime-type>
Adding Features
105
<rim:mime-type>application/x-pdf</rim:mime-type>
</rim:filter>
</rim:invoke-target>
<widget>
Syntax:
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="string"
id="string"
xml:lang="string"
rim:header="string"
rim:userAgent="string">
</widget>
Description:
The <widget> element is the root element of the config.xml file. The config.xml file must contain a single
instance of <widget>.
Occurrences:
One.
Parent elements:
None.
Child elements:
Name
Occurrences
<access>
zero or more
<author>
one
<content>
one
<description>
zero or more
Adding Features
106
Name
Occurrences
<license>
one or none
<name>
one
<platform>
zero or more
<preference>
zero or more
Content:
None.
Attributes:
You can define the following attributes for this element:
Attribute
Description
xmlns
Required. Defines the namespace for the BlackBerry WebWorks app. The value
must be xmlns="http://www.w3.org/ns/widgets". If this namespace is
missing, the app archive is not valid.
xmlns:rim
Required. Defines the namespace for the BlackBerry WebWorks extensions (that
is, those elements with the rim: prefix). The value must be
xmlns:rim="http://www.blackberry.com/ns/widgets".
version
Required. Specifies a valid version for the app, in one of the following formats:
x.x.x
x.x.x.x
If you specify a version number that is not valid, the app archive is not valid.
rim:header
Optional. Specifies an HTTP header value that precedes every request for data
that the app sends. This attribute allows you to distinguish between requests sent
from your BlackBerry WebWorks app and requests coming from the BlackBerry
Browser. The attribute value can be any string.
Adding Features
107
Attribute
Description
rim:userAgent
Optional. Specifies the value for the user agent. The value that you specify is sent
as the value of the User-Agent header, which is included with every HTTP
request. You can use this string to identify requests coming from your app. The
attribute value can be any string.
id
xml:lang
Optional. Specifies the language that is used in the element. For more
information about this attribute, visit www.w3.org/TR/html401/struct/
dirlang.html.
Example:
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="2.0.0.0"
id="sampleapp"
rim:header="RIM-Widget:rim/widget"
rim:userAgent="BlackBerry10/MyWebWorksApp">
</widget>
108
plugins and modify configuration settings as necessary. Once you have created the headless WebWorks
project, the process to develop this component is the same as for any WebWorks app.
headless service: This component is a native app developed in C/C++ that is designed to run in the
background on the device. It has no UI, and the user can't invoke or interact with it in any way. Typically,
the headless service starts as a result of a defined trigger, performs some function (for example, generating
a notification), and then stops, until it is triggered again. By using the _sys_headless_nostop
permission, you can also create a headless service that runs continuously.
Although the two components are packaged together, they are designed to operate independently on the
device. That is, the headless component doesn't require the web component of the app to be running in order
to respond to a trigger.
The following diagram provides an overview of the headless app process:
For a thorough discussion of headless apps, see Headless apps in the BlackBerry 10 Native SDK
documentation.
To understand how headless apps work, let's look at the template that is provided when you create a headless
app using the BlackBerry 10 WebWorks SDK. When you create a headless app in WebWorks using the
create-headless command, you receive a fully functional app that you can immediately build and deploy
to a device or simulator. By deafult, the headless component of the app is configured with the
bb.action.system.STARTED trigger, which triggers it to run as soon as it is installed on the device. Once
triggered, the headless component immediately sends a notification to the BlackBerry Hub, which the user
can click to invoke the web component of the app. The web component provides a button that resets the
headless component of the app, causing it to send another notification.
The headless service supports various triggers; a trigger can be the receipt of pushed content or a portdirected SMS message, a change in location information, or some other event. For a full list of triggers, see
Triggers in the BlackBerry 10 Native SDK documentation. The behavior of the headless component upon being
triggered similarly depends on the requirements of your app.
109
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.
Folder structure
A WebWorks 2.0 project with a headless service has the following differences in the project folder structure:
Adding Features
110
Folder
Description
www/assets
The www folder includes an assets subfolder. The assets folder contains the
compiled binary of the headless service component of your app.
HeadlessService
The HeadlessService folder contains the complete C/C++ project for the
headless portion of the app. You can import the project into the Momentics IDE
for BlackBerry to modify the default headless app and add custom functionality.
For information on how to import the headless project, see Import your headless
project into the Momentics IDE on page 112.
Defining triggers
For information on defining triggers for your headless service, see the Triggers section in the BlackBerry 10
Native SDK documentation.
While the syntax and structure are identical, remember that in a headless WebWorks app, the triggers are
specified within the <config-file> element of the config.xml file, not in a bar-descriptor.xml file.
Adding Features
111
Adding Features
112
4. In the Import Projects panel, next to the Select root directory field, click the Browse button and
navigate to your project's HeadlessService folder.
5. In the Projects list, make sure that the HeadlessService project is selected.
6. Make sure that the Copy projects into workspace check box is not selected.
7. Click Finish to import the selected project into the IDE.
Adding Features
113
App integration
The BlackBerry 10 OS provides the invocation framework to bring powerful cross-app integration to the
platform. You can use the invocation framework and cards to greatly enhance the user experience and
functionality of your app.
The invocation framework facilitates inter-app communication. The framework allows your app to start other
apps from within its UI, preserving user focus and ensuring optimal multitasking and app flow. You can also
integrate your app with apps that are included in the BlackBerry 10 OS (also known as core apps). For
example, you can integrate with apps such as File Manager, Pictures, Music, and BBM, and you can invoke
these apps when you need them.
Cards enhance the invocation framework's capabilities. Cards allow you to open a particular screen of another
app as a card, instead of opening the full app. Cards use fewer system resources and offer a great user
experience.
The invocation framework also includes other features that make your app easier to use and more tightly
integrated with other apps on the device. You can add your app as an entry to different menus (such as the
context menu and target selection menu), allow your app to be invoked using active text, and enable your app
to be the default app for certain types of content.
Invocation framework
The invocation framework in the BlackBerry 10 OS allows one app to invoke another by sending it a message.
When an app calls for an invocation on some content, the invocation framework responds with appropriate
apps that can carry out a requested action on that particular content. For example, using the invocation
framework, your app can allow the user to perform a set of actions on a piece of content such as a .doc file.
These actions allow the user to share, open, or send the .doc file in an email using another app from within the
UI of your app. In this example, your app is the client app in the invocation framework and the app that shares,
opens, or sends the .doc file as an email is the target app.
Depending on your app's functionality, the invocation framework can allow your app to become more
discoverable if you register your app as a target. Registering allows other apps to invoke your app and use its
features.
An invocation request is the message structure that is passed between a client app and a target app. An
invocation message represents either a request for the target to perform a task or a notification about an event
that has occurred. An invocation request is passed to a target app when the target is invoked. The framework
takes care of opening the target app if it is not already running.
An invocation request contains the following information:
The unique ID of the target app
The action that should be performed
The data that should be acted upon
Adding Features
114
Invocation target
An app that is registered with the invocation framework is called a target app. Other apps can invoke a target
app by using the invocation framework. Upon invocation, the user's context switches to the target app. The
client app (the app from which the invocation request is sent) moves to the background while the user works in
the target app.
The target ID in an invocation message tells the invocation framework where to send the invocation message. A
target ID is assigned by the target app developer and is guaranteed to be unique when the app is signed. To
help select a unique value, the target ID uses a reverse DNS style structure (for example, com.acme.myapp).
Invocation action
The action attribute in an invocation request describes the task that can be performed on the content. Every
action is uniquely identified by a name. Action names end with a verb in uppercase letters. To help identify the
ownership and uniqueness of each action, the action attributes in an invocation request use a reverse DNS
style structure (for example, com.acme.action.VIEW).
The invocation framework supports a set of actions that your app can request the platform to perform (for
example, viewing an image). You can also use actions to register your app as a target in the core apps of the
BlackBerry 10 OS (for example, registering your app as a target could allow an image in the Pictures app to be
shared with your app).
All of the actions available on the BlackBerry 10 OS begin with bb.action and are appended by a verb in
uppercase letters. Before you add a custom action, check to see if there is already a suitable action provided
by the platform. For a complete list of available platform actions, see Invoking core applications.
Invocation data
The data in an invocation message is provided as a URI and a MIME type. The URI identifies the location of the
data resource and the MIME type describes the data. For common MIME types, the platform can deduce the
MIME type from the URI, even if you do not specify the MIME type when you specify a URI. For example, it can
deduce the MIME type from a file extension in the URI.
For small amounts of data, you can include the data directly in the invocation message using the data
attribute. The URI is assumed to be data://local and can therefore be left out of the message. When you
send data directly in the invocation message, you must provide a MIME type because the platform can only
deduce the MIME type if a URI is present in the message. The total size of the message cannot exceed 16 KB.
A custom MIME type that describes data should begin with the application/vnd. prefix. It should be
followed by sufficient context so that the MIME type is properly distinguished from other types. If the data has
multiple encodings represented in the MIME type, make sure that the data is the last element defined in the
type (for example, application/vnd.mycompany.mydata).
You can also specify additional, optional data by using the metadata attribute in an invocation message. Data
is sent in JSON format.
Adding Features
115
Sending invocation
An invocation message contains a target, an action, and data. To learn more about these parameters, see
Invocation framework. You can configure your app to invoke target apps by using bound or unbound
invocations.
Bound invocation
Bound invocation occurs when a client app explicitly identifies the target app to handle the invocation. The
following image shows how a client app can use bound invocation to invoke a specific target app. In this case,
Target app opens the document contained in the client app.
Before you can send an invocation request, you must add the com.blackberry.invoke plugin to your app.
To add the plugin, on the command line, navigate to your project folder and run the following command:
webworks plugin add com.blackberry.invoke
Here's an example that shows how to send an invocation request:
blackberry.invoke.invoke({
target: "com.example.image.view",
action: "bb.action.OPEN",
type: "image/png",
uri: "file:///path/to/image.png"
}, onSuccess, onError);
Once the invocation request is sent, the invocation response is handled by the invocation framework itself.
However, you must create JavaScript functions to handle the success or error events. Here's a sample that
shows you how to do that:
function onSuccess() {
console.log("<p>Invocation successful</p>");
}
function onError(error) {
console.log("<p>Invocation error: " + error + "</p>");
}
Target discovery
You can hard code the target app that you want to send an invocation message to, or you can query the
invocation framework to find out what targets are installed on the BlackBerry device. The invocation framework
uses a target filter to allow the target apps to declare the types of invocation they support. When a client app
queries the invocation framework, the framework uses the target app's filter to describe the kind of target it is
and the data it can accept.
Adding Features
116
The quality of the results depends on how specific the target query request is. A target query request should
consist of the URI and MIME type. If the MIME type is omitted, the framework tries to determine the type using
the URI.
A client app can include the action to be performed on the data in its target query request. If the action is not
specified in the target query request, the query result will contain a list of all the actions that can be performed
on the specified data by the available targets.
The invocation framework returns a query result that includes the targets grouped by the action that these
targets support. For each target, the query result provides the target ID, the target type (an app or a card), and
other information about the target, such as icons and labels, that can be used to display the target in the client
app's screen.
To determine what targets are suitable candidates, the invocation framework applies a set of brokering rules.
For more information, see Target selection and brokering.
The following code sample demonstrates a target query request in which a client app searches for targets that
support the bb.action.OPEN action on image/png images, which are sent as a file:// URI:
var request = {
"action": "bb.action.OPEN",
"type": "image/png",
"uri": "file://path/to/image.png",
"target_type": ["APPLICATION", "VIEWER"],
"action_type": "ALL"
};
blackberry.invoke.query(request, onSuccess, onError);
Here's how you can handle the results:
function onSuccess(response) {
console.log("<p>Invocation query response: " + response + "</p>");
var data = JSON.stringify(response);
//can now parse the data variable for invocation targets
// that matched the query criteria
}
function onError(error) {
console.log("<p>Invocation query error: " + error + "</p>");
}
Unbound invocation
The invocation framework can make invoking a target app easy by removing the need to query. Instead of
sending a target query request to determine the available targets, the client app can simply send an invocation
request to the framework without specifying a target. This kind of invocation is called unbound invocation. If
you send an unbound invocation request, the framework searches for and invokes a suitable target app for
you.
Adding Features
117
The following image shows how a client app lets the invocation framework return the most suitable target app
for a particular action. In this case, Target app is the most suitable app to open the document contained in the
client app.
To find the best target app, the framework first uses a brokering process. It applies a set of rules to determine
which target apps support the client app's invocation request. If there is more than one suitable target
available, the framework applies a set of selection rules to choose the most appropriate target. For more
information, see Target selection and brokering.
You can also send an invocation request without specifying an action. In this type of request, only the data is
sent. The framework determines the type of target and the action to be performed.
If you don't specify an action, the invocation framework tries to find an appropriate target app for the
bb.action.VIEW action. If no suitable target app is found for bb.action.VIEW, the invocation framework
falls back to determine an appropriate target app that supports bb.action.OPEN. If still no suitable target
app is available for bb.action.OPEN, the invoke request is unsuccessful.
The following code sample shows how you can create an unbound invocation request. The code invokes the
most suitable target app to handle the image.png file, which is specified by the URI.
blackberry.invoke.invoke({
uri: "file:///path/to/image.png"
}, onSuccess, onError);
Data transfer
This section explains how the invocation framework sends data, to help you understand how to optimize your
invocation requests and send multiple files between client and target apps. Although apps can use many
different URI schemes to transfer data, the invocation framework provides support for in-band transfer and file
transfer.
In-band transfer
Most often, an invocation request carries only a small amount of data (less than 16 KB). In some cases, this
small amount of data can be encoded directly into a URI. It is also possible to send it as part of the invocation
request. When data is sent as part of the invocation message, it is placed in the data attribute. This type of
transfer is called an in-band transfer.
During an in-band transfer, the URI value should be set to data://local, which points to the data attribute.
When the data is sent in-band, the MIME type must describe the type of the data, to allow both the invocation
framework and the target app to handle the message.
blackberry.invoke.invoke({
target: "com.example.image.view ",
action: "bb.action.OPEN",
Adding Features
118
type: "text/plain",
data: "Hello World!",
}, onSuccess, onError);
File transfer
This section contains information on how the invocation framework handles file transfers and the types of files
that are supported.
File extensions
The invocation framework supports file handling based on the file extension. The file extensions can be defined
as file:// in the scheme attribute when the data is referenced by the URI. The invocation framework also
supports the declaration of an extensions attribute in the target filters. In an invocation request, if the URI is
suffixed with a file extension that matches any of the file extensions declared in the extensions attribute, then a
given target filter will match with that invocation request. When the extensions attribute is defined, the target
filter implicitly supports the file:// URI for those declared extension cases.
The extensions attribute is applied only if the accompanying URIs contain a file://-based URI. Also,
combining the extensions attribute and specific MIME types in a target filter means that both must be specified
by a client app for the target filter to successfully match with an invocation request. The best practice in most
cases is to define the extensions-related target filters as a separate declaration, where the URI attribute is
file:// and the MIME type is a wildcard character (*).
Description
Preserve
Adding Features
119
Description
CopyReadOnly
CopyReadWrite
Link
filelist/audio
audio/mp4, audio/mpeg
filelist/video
video/mpeg, video/mp4
filelist/image
filelist/media
filelist/document
filelist/mixed
Any
Adding Features
120
When sending multiple files, you can set the URI attribute to describe the common file path that is associated
with each file. Usually, this file path is the common root directory, if one exists. If no common root directory
exists, set the URI attribute to list://. After you set the type and URI, you can assign the list of individual file
URIs to the data attribute using the following JSON format:
[
'uri':<file-uri>,
'type':<mime-type>,
'data':<metadata>
Attribute
Format
Description
Mandatory?
Example
uri
File URI
Yes
file://path/to/
file
type
MIME
No
image/jpeg
data
JSON
Additional
metadata in JSON
format
No
test metadata
Receiving invocation
You can configure your app to receive invocation requests from other apps. To receive an invocation request,
your app must support invocation targets. To support invocation targets, you must declare your targets in the
config.xml file and handle invocation messages.
Target declaration
To be invoked, an application identifies itself by declaring itself as a target in its config.xml file. To declare a
target, add the following elements to the config.xml file for each target that the application exposes.
<invoke-target id="com.example.image.view">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>My App Name</invoke-target-name>
<icon>
<image>icon.png</image>
Adding Features
121
</icon>
</invoke-target>
Attribute
Element
Description
ID
<invokeThis attribute
target id> uniquely
identifies the
app as a
target. This
attribute can
also be used
by the client
apps to
perform
bound
invocation.
Type
<invoketargettype>
This attribute
specifies the
type of the
target. Apps
and cards are
supported as
types of the
target.
Name
<invoketargetname>
This attribute
specifies the
name of the
target app.
Icon
<icon>
This attribute
specifies the
icon for the
target app.
Receiving invocations
Adding Features
122
Declaring your application as a target is essential for receiving an invocation request, but to be invoked you
need to add code in your application to receive invocation messages. Before you can receive invocation
messages, you must specify your app in the config.xml file as shown below:
<rim:invoke-target id="com.bb.test.invokable">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>text/plain</mime-type>
</filter>
</rim:invoke-target>
The following code describes how to configure your application to listen for invocation messages:
// Add an event listener for when
// the application gets invoked:
document.addEventListener('invoked',onInvoked);
// The following function parses the incoming data
function onInvoked(invokeRequest) {
}
Handling launch through invocation
An important thing to consider when you write an application target is how an app is launched. Usually an app
launches when the BlackBerry device user taps the app icon on the home screen. However, with the
invocation framework the app can also be invoked. So how does an app know whether it was invoked or
launched? Here's how your app can listen for the invocation events:
function onInvoked(info) {
if(info.source) {
console.log("Source: " + info.source);
}
if(info.target) {
console.log("Target(me): " + info.target);
}
if(info.action) {
console.log("Action: " + info.action);
}
if(info.data) {
console.log("Data: " + info.data);
//the data comes in as a base64 string you can convert it using
atob(...)
//note that atob will fail if you are being passed unicode strings
console.log("Data: " + atob(info.data));
}
}
document.addEventListener('invoked',onInvoked);
Adding Features
123
You can also specify any particular behavior that you'd like your app to exhibit when it is invoked (for example,
screen orientation) by setting app preferences. For more information, see Configuring your app preferences.
Target filters
One of the key features of the invocation framework is the ability to discover target applications or cards on a
BlackBerry device. Targets are discovered based on the filters they declare in their config.xml file, which
describe the kinds of invocation request that a target supports. Target filters allow your app to be queried for by
other apps and make your app a candidate for unbound invocation requests.
Target filters are declared as part of the <invoke-target> element in the config.xml file and consist of the
following attributes:
Attribute
Description
filter
Describes the
criteria for this
app to be
considered for
unbound
invocations or
invocation
queries. This
attribute is the
containing
element for the
other attributes
that are listed
here.
action
Describes the
actions that can
be performed on
the content. This
attribute
represents the
action that the
target supports
for the types
specified in the
mime-type
attribute.
Include one
<action>
Adding Features
124
Attribute
Description
element for each
supported
action.
mime-type
Describes the
type of content.
This attribute
represents the
different types
for which the
specified actions
are supported.
You can specify
both the type
and subtype by
using wildcards
in a target filter.
For example, a
filter can specify
image/png,
image/*, or *.
Include one
<mime-type>
element for each
supported MIME
type.
uris
Describes the
supported URI
pattern that
must prefix the
URI that is
provided in the
invocation
request. This
attribute
represents the
URI prefixes that
describe how
the target
Adding Features
125
Attribute
Description
supports the
delivery of the
data. The URI
value may
contain the
single wildcard
character * to
indicate that the
filter
supports any del
ivery
mechanism.
If the target app
or a card
supports the
delivery of the
data as part of
the message
body, then it
should include
the data://
local URI.
exts
Represents the
list of file
extensions
supported by the
target. The
values specified
in this attribute
apply only to
file:// URIs.
When
extensions are
specified in a
target filter, they
are generally
specified in
conjunction with
a MIME type of
*.
Adding Features
126
Attribute
Description
A best practice
is to be as
specific as
possible when
specifying the
filter criteria, to
increase the
chances of
being selected
to handle the
invocation
request.
Wildcard
characters (*)
are considered a
relatively weak
match when
performing
selection, so if
your target
supports a
specific set of
types, you must
specify each of
the types in the
filter. In cases
where your app
supports both
specific MIME
types and
extensions, you
should split the
registration into
two separate
filters. One filter
registers for the
specific types
and one filter
registers for the
extensions
against the
MIME type of *.
Adding Features
127
When you declare a target filter, make sure that your filter description follows these rules:
The URI value cannot be set as a wildcard character (*). That is, you cannot declare <property var=
"uris" value="*"/> in your config.xml file.
If the target filter contains actions such as bb.action.VIEW or bb.action.OPEN, has MIME types set
as a wildcard character (*), and has the URI attribute set as data:// or file:// or left unstated, then
your app cannot be deployed or installed on the device.
For a target filter that uses the URI file:// and a MIME type wildcard character (*), to successfully
register with the invocation framework, you must also specify a file extension value that is not a wildcard
character (*).
If you declare a file extension value in the target filter, the file extension value is considered during the
brokering and selection process if it is used with a file:// URI.
If your app uses a target filter declaration that is invalid, then when your app is deployed, you will receive the
result::failure 884 Restricted Invoke Filter detected error.
Here are some examples of target filters that register successfully with the invocation framework:
actions=bb.action.OPEN;types=*;uris=http://;
actions=bb.action.OPEN,bb.action.VIEW;types=*;uris=file://;exts=jpg,gif,tif
;
actions=bb.action.VIEW;types=*;uris=data://;exts=jpg,gif,tif;
The following target filters do not follow the rules specified above and will not allow the app to be deployed or
installed on the device:
actions=bb.action.OPEN,bb.action.VIEW,bb.action.SET;types=*;uris=file://;
actions=bb.action.OPEN;types=*;uris=data://;
actions=bb.action.VIEW;types=*;uris=*;
actions=bb.action.VIEW;types=*;
actions=bb.action.OPEN,bb.action.VIEW;types=*;uris=file://;exts=*;
The following example describes an invoke target that has two filters. The first filter describes the support for
bb.action.OPEN and bb.action.VIEW actions on .png and .jpeg image files that are delivered in a file or
in the message body. The second filter describes the support for bb.action.OPEN and bb.action.VIEW
actions on any URI file with .jpg or .png extensions.
<invoke-target id="com.example.image.view">
<entry-point-id></entry-point-id>
<invoke-target-type>application</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.OPEN</action>
<mime-type>image/png</mime-type>
<mime-type>image/jpeg</mime-type>
<property var="uris" value="file://,data://local"/>
</filter>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.OPEN</action>
Adding Features
128
<mime-type>*</mime-type>
<property var="uris" value="file://"/>
<property var="exts" value="jpg,png"/>
</filter>
</invoke-target>
Target selection and brokering
When a client app queries the invocation framework for a suitable target or when it sends an unbound
invocation request, the invocation framework determines the set of suitable targets by comparing the
invocation request to all of the installed target filters defined for the apps on the BlackBerry device. This
process is called invocation brokering. Brokering uses a set of rules to determine how to match the invocation
request to each filter. Specifically, a filter is considered a match only if both the action rules and the data rules
are satisfied.
129
The URI and MIME type specified in the invocation request match with the target filter's uri and exts.
The wildcard character (*) is considered and is used for MIME type matching.
If the MIME type is specified, then the type is not inferred from the uri.
If the target filter doesn't specify any exts values, then the filter matches any extension.
The absence of the uri in either the invocation request or the target filter implies that the data attribute is
data://local.
If the invocation request does not specify a MIME type and a target filter declaration has matching URIs and
file extensions, then the invocation framework considers that target filter a MIME type match.
If the invocation request does not specify a uri and the target filter declares a matching MIME type but
either does not declare a uri, which implies that the data attribute is data://local, or explicitly
declares the uri as data://local, then the target filter is considered a MIME type match.
Unbound selection
When an unbound invocation has multiple targets that are suitable, the invocation framework chooses
a best fit target to invoke by using the brokering rules. Here are the rules that the selection process follows:
The filter that has the strongest URI match based on its length is selected.
When target filters are compared, only the scheme attribute is used for the URIs that are declared in the
config.xml file.
If more than one target filter has the longest matching URI, then the target filter with the strongest MIME
type match is selected. The type with the wildcard character (*) is considered the weakest match, the
subtype with the wildcard character type/* is considered weak, and a match without wildcard characters
is considered the strongest match.
If more than one target filter has the strongest MIME type match, then the target filter with an exts match
is selected if the uri attribute is defined in file:// format.
If more than one target filter has a matching ext, then the filter that the invocation framework marks as
default for that set of target filter criteria is selected.
If no target filter is identified as default, then the oldest target filter is selected as the best possible match.
Cards
A card allows an app to export a screen to another app. Unlike an app that may offer a full and rich set of
features, a card typically provides the ability to perform specific tasks such as picking a contact, composing an
email, or previewing an image. To a user, a card appears as part of the client app and does not appear as a
separate Active Frame.
Your app can export (or expose) a card, which makes it available for other apps to use. Your app can also
import cards that other apps expose, which lets your app use the feature or functionality of those cards.
An app can expose only one card at a time. However, one card can expose another card, which allows the app
to create a stack of cards that appear as part of the client app. Although the card appears as part of the client
app, it maintains its own process and security context. In the following sections, you will learn how to create
and use cards in your app, as well as how to expose them to other apps.
Adding Features
130
Card styles
When an app imports a card, the BlackBerry 10 OS controls the visual transition on and off the screen, but it
also controls the peek behavior that allows the user to look at the card under the card that's currently
displayed. The BlackBerry 10 OS manages the transition and the peek behavior based on the card's style.
Composers, pickers, and previewers
You can use three different styles of card in your app: composers for creating and editing content, pickers for
choosing existing content, and previewers for viewing existing content. The style of card you use determines
how the BlackBerry 10 OS transitions between the app and the card, how peeking is handled, and the general
task that a card performs. Each card style has associated visual style guidelines.
The following image shows picker, composer, and previewer cards:
Card transitions
A card transitions on or off the screen in a beautiful animation. The cards appears on the screen as sliding in
either from the bottom or from the right side. Previewers slide in from the right side, while composers and
pickers slide in from the bottom of the screen.
The following image shows the transition style of composers and pickers:
Adding Features
131
Adding Features
132
Peeking
Peeking is the ability for a user to see under a card by using a gesture. There are two ways in which a user can
peek under the card:
Parent peek: The user slides a finger right to reveal the screen that lies immediately under the card.
Root peek: The user slides a finger right on the action bar to reveal the app at the bottom of the stack of
cards.
The following image shows the parent and root peek:
Not all card styles support both peek types. Composer and picker cards support only parent peek, and
previewer cards support both types.
UI consideration for cards
For a great user experience, here are some guidelines to consider if you want to use cards in your app:
Adding Features
133
Description
Composers
Previewers
Pickers
Yes
No
Yes
No
Yes
Yes
Yes
Yes
No
To learn what the action bar, context menu, and buttons are, see The basics in the UI Guidelines for
BlackBerry 10.
Note: When you create a card, you must add support for both landscape and portrait orientation so that the
card follows the orientation of your app.
Invoking cards
Cards enhance the invocation framework's capabilities by allowing apps to share the UI and the app logic with
other apps. You send a request to invoke a card in the same way as an invocation request for an app, which
means that everything that you learned about sending an invocation request, applies to cards as well. Before
your app can invoke cards, you must add the invocation plugins to your app. To add the plugins, on the
command line, navigate to your project folder and run the following commands:
webworks plugin add com.blackberry.invoke
webworks plugin add com.blackberry.invoke.card
Here's how you can use the invocation framework to import a card from another app:
blackberry.invoke.invoke({
target: "com.acme.myapp",
action: "bb.action.VIEW",
type: "image/png",
uri : "file://path/to/image.png"
}, onInvokeSuccess, onInvokeError);
Before a new card is invoked and allowed to be stacked, the BlackBerry 10 OS verifies that the client app is not
already parenting a card. Unlike an app, a card may continue to exist in multiple instances, but a parent app
(or card) can parent only one card at a time. This is important because multiple instances of a card may be
running at the same time.
Cards support a "fire and forget" import model. However, for apps that require notifications and additional
feedback, cards also provide peek notifications and response data.
Adding Features
134
Close a card
An app can request to close a card that it imported. As a result, the card is transitioned off of the screen. When
a user closes the card, both the app and the card are notified. However, if the card is closed by the app itself,
the card cannot provide a response. Also, when an app closes a card, it closes the entire stack of cards
(including children of the card) above it.
Here's how your app can request to close a child card:
blackberry.invoke.closeChildCard();
Adding Features
135
To learn more about APIs that support card invocation and read code samples, see card.
136
the user is viewing one email after another, instead of exporting a new card for every email, the BlackBerry 10
OS may pool the existing email previewer card and use it again.
When you're creating a card, you must consider several things before you handle pooling events, such as
which resources your cards should clean up or keep when they're pooled.
First, consider adding support for purging the state of the card. While pooled cards are not terminated, they
may be suspended to keep them from processing while pooled. When your card is pooled, it should release
resources such as files or database connections until it is resumed again. When a card receives a
cardPooled() signal, it should clear its current state and listen for future invocations. In addition, cards
must be written to support multiple instances which run simultaneously in the same sandbox.
Second, if an app with cards defines several card targets, then when it's retrieved from the pool, the card may
be invoked to service any of the declared targets. In other words, if a .bar file bundles a composer, previewer,
and picker under a single entry point, then when it's retrieved from the pool, the app or card may be invoked as
any of these targets.
Card security
Cards have their own identity and sandbox environment that is shared with all instances of the card. Like apps,
cards are processed in their own context and with their own permissions. It is important to pay attention to the
capabilities and the data that you want to expose using your card.
To learn more about APIs that support card invocation and read code samples, see card.
Adobe Reader
Maps
Adding Features
137
BBM
Media Player
BlackBerry Browser
Miracast card
BlackBerry World
NFC
Phone
Bluetooth
Calendar
Pictures
Camera
Picture editor
Remember
Clock
Contacts
Search
Adding Features
138
Settings
Device Monitor
Docs to Go
Text Messages
Twitter
Video editor
Foursquare
Voice note
YouTube
Adobe Reader
Opening a .pdf file
Here are the invocation attributes you use to open a .pdf file in the Adobe Reader app:
Adding Features
139
Attribute
Target ID
Action
URI
MIME type
File extensions
Value
com.rim.bb.app.adobeReader
bb.action.OPEN
file:///path/to/my/content.pdf
application/pdf
.pdf
Here are the invocation attributes you use to open a .pdf file in a previewer card:
Attribute
Target ID
Action
URI
MIME type
File extensions
Value
com.rim.bb.app.adobeReader.viewer
bb.action.VIEW
file:///path/to/my/content.pdf
application/pdf
.pdf
BBM
Sharing a file with BBM
Here are the invocation attributes you use to share a file with BBM:
Adding Features
140
Attribute
Target ID
Action
URI
Value
sys.bbm.sharehandler
bb.action.SHARE
file:///path/to/my/content.doc
Value
sys.bbm
bb.action.OPEN
Value
sys.bbm.imagehandler
bb.action.SET
file:///path/to/my/content.jpg
141
Attribute
Target ID
Action
MIME type
Data
Value
sys.bbm.sharehandler
bb.action.SHARE
text/plain
Text string to be shared
Value
sys.bbgroups.sharehandler
bb.action.SHARE
file:///path/to/my/content.txt or
file:///path/to/my/image.png
Value
sys.bbm.sharehandler
bb.action.BBMCHAT
Adding Features
142
Attribute
URI
Value
pin:<pin>
Note: This invocation action displays either an Invite to BBM screen or the BBM chat composer screen
depending on whether the specified PIN is already a BBM contact.
Value
sys.bbm.sharehandler
bb.action.INVITEBBM
pin:<pin>
Value
sys.service.videochat
bb.action.OPEN
dest=<BlackBerry ID or PIN of
contact>&video=<0 or 1>
The value 0 is specified for an audio call and 1 is
specified for a video call (for example,
dest=user01@example.com&video=1).
Adding Features
143
Value
sys.bbm.channels.card.previewer
bb.action.OPENBBMCHANNEL
bbmc:<my BBM channel PIN>
Value
sys.bbm.channels.sharehandler
bb.action.SHARE
file:///path/to/my/content.doc,
file:///path/to/my/image.jpg
Value
sys.bbm.sharehandler
bb.action.BBMCONF
Adding Features
144
Attribute
MIME type
Value
vnd.bb.bbm/contactlist
BlackBerry Browser
Opening a URL
Here are the invocation attributes you use to open a URL:
Attribute
Value
Target ID
sys.browser
Action
bb.action.OPEN
MIME type
URI
http://
https://
ftp://
Adding Features
145
Attribute
Value
Target ID
sys.browser
MIME type
text/html
application/xhtml+xml
image/svg+xml
Action
bb.action.OPEN
File extensions
URI
file://
htm
html
xhtml
svg
BlackBerry World
Opening a specific page in BlackBerry World
Here are the invocation attributes that you use to open a specific page in the BlackBerry World storefront:
Attribute
Target ID
Action
Value
sys.appworld
bb.action.OPEN
Here's a list of URIs that you use to open various other pages in BlackBerry World:
Page
URI
Home page
appworld://
appworld://content/<contentid>
Adding Features
146
Page
URI
appworld://category/<categoryid>
appworld://emu/<emuid>
appworld://search/<searchterm>
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
appworld://<???>
Value
sys.enterpriseappworld
bb.action.OPEN
Here's a list of URIs that you use to open various other pages in BlackBerry World for Work:
Page
URI
Home page
entappworld://
My World
entappworld://myworld
Adding Features
147
Page
URI
App details
entappworld://package/<packageid>
entappworld://<???>
Bluetooth
Sharing a local file
Here are the invocation attributes you use to invoke a Bluetooth card to share a local file:
Attribute
Target ID
Action
Value
sys.btviewer
bb.action.SHARE
URI
MIME type
"uri": "file:///path/to/file"
},
...
Calendar
Creating an event
Here are the invocation attributes that you use to open a calendar card to create an event:
Adding Features
148
Attribute
Target ID
Action
MIME type
Value
sys.pim.calendar.viewer.eventcreate
bb.action.CREATE
text/calendar
Description
Data
"participants":
["email1@xyz.com","email2@xyz.com"]
"subject":"<text>"
"body":"<text>"
String startTime
QString location
int duration
Value
sys.pim.calendar.viewer.nav
bb.calendar.PICK
text/calendar
Adding Features
149
Data
Description
Done
Value
sys.pim.calendar.viewer.eventcreate
bb.calendar.EDIT
text/calendar
Description
Data
Event ID
QString startTime
Note: The start time lets you differentiate between any two or more recurring events that have the same
eventID.
Adding Features
150
Attribute
Target ID
Action
MIME type
URI
Value
sys.pim.calendar.viewer.ics
bb.action.OPEN
text/calendar
file:///path/to/my/file/filename.ics
If you want to open the .ics file for a specific account, you can set an account ID in the data attribute of the
invocation request.
Description
Data
Value
Action
bb.calendar.OPEN
MIME type
text/calendar
Data
"data":"file:///path/to/file.txt"
Adding Features
151
Query name
Query value
Description
view
calendars
<account-id><folderId>
<account-id>-<syncId>
date
monthly
agenda
people
schedule
weekly
Value
sys.pim.calendar.viewer.ics
bb.calendar.OPEN
text/calendar
Description
Data
Adding Features
152
Description
Data
Type
"event"
Here are the invocation attributes that you use to open the calendar app to view an existing event:
Attribute
Value
Action
bb.calendar.VIEW
MIME type
text/calendar
Data
"data":"file:///path/to/file.txt"
Query name
Query value
Description
accountId
<account-id>
eventId
<event-id>
date
Type
"event"
To learn more about invoking calendar cards and read code samples, see the API documentation on calendar
event composer and calendar event picker cards.
Adding Features
153
Camera
Opening the Camera card
Here are the invocation attributes you use for opening the camera card:
Attribute
Value
Target ID
sys.camera.card
Action
bb.action.CAPTURE
Data
Data
Description
done
Not applicable
close
save
Adding Features
154
Reason
Data
Description
picture or records a video. The
captured file is returned in the data
field of the message.
Value
sys.camera.app
image/jpeg or video/mp4
bb.action.CAPTURE
photo, video, or full (full is the default if
nothing is specified)
When the Camera app is opened, it is not locked to any particular mode, regardless of the data parameter's
description. The user can change the mode of the Camera app at any time. For example, a user can choose
between the photo capture mode, video capture mode, and the timeshift mode. Also, if an instance of the
Camera app is already running, it is displayed instead of a new instance being started. Similarly, the instances
that are running don't change the mode specified in the data parameter.
Clock
Opening the clock application
Here are the invocation attributes you use to open the clock app:
Adding Features
155
Attribute
Target ID
Action
Value
bb.clock.launcher
bb.action.VIEW
MIME type
text/plain
Data
Description
alarmClockPane
worldClockTab
stopwatchTab
timerTab
Contacts
Viewing a contact
Here are the invocation attributes you use to launch the contacts app to view a contact:
Attribute
Target ID
Action
MIME type
Data
Value
sys.pim.contacts.app
bb.action.OPEN
application/vnd.blackberry.contact.id
Contact ID integer.
156
Attribute
Target ID
Action
MIME type
Data
Value
sys.pim.contacts.app
bb.action.ADDTOCONTACT
application/
vnd.blackberry.string.phone,
application/
vnd.blackberry.string.email,
application/vnd.blackberry.string.pin
Depending on the MIME type, you could use the
phone number string, email address string, or the PIN
string.
Value
sys.pim.contacts.card.viewer
bb.action.VIEW
file:// (for example, file:///
path/to/file.vcf)
Here are the invocation attributes you use to launch the contacts app to open a vCard contact attachment (.vcf
file):
Adding Features
157
Attribute
Target ID
Action
URI
Value
sys.pim.contacts.app
bb.action.OPEN
file:// (for example, file:///
path/to/file.vcf)
Value
sys.pim.contacts.card.composer
bb.action.CREATE
Value
sys.pim.contacts.card.composer
bb.action.EDIT
application/
vnd.blackberry.string.contact,
application/contact
Adding Features
158
Attribute
Value
Data
Contact ID integer
Here are the invocation attributes you use to view a contact using a contact previewer card:
Attribute
Target ID
Action
MIME type
Data
Value
sys.pim.contacts.card.viewer
bb.action.VIEW
application/contact, application/
vnd.blackberry.string.contact,
application/vnd.blackberry.contact.id
Contact ID integer.
Value
sys.pim.contacts.setcontactpicture
bb.action.SET
file:// (e.g. file:///path/to/
photo.jpg)
Adding Features
159
Device Monitor
Opening the Device Monitor
Here are the invocation attributes you use for the Device Monitor app:
Attribute
Target ID
Action
MIME type
Value
sys.SysMon.app
bb.action.OPEN
You should specify a wildcard character *
Here are the invocation attributes you use for the Device Monitor card:
Attribute
Target ID
Action
MIME type
Value
sys.SysMon.card
bb.action.VIEW
You should specify a wildcard character *
Here's a list of URIs you can use to invoke the Device Monitor card or the app:
Setting
CPU
Battery
Storage
Memory
URIs
devicemonitor://cpu
devicemonitor://battery
devicemonitor://storage
devicemonitor://memory
Adding Features
160
Here's an example to show how you can invoke the Device Monitor app:
<invoke-target id="sys.SysMon.app">
<entry-point-id>sysmon_app</entry-point-id>
<invoke-target-type>APPLICATION</invoke-target-type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>*</mime-type>
<property var="uris" value="devicemonitor://"/>
</filter>
</invoke-target>
Here's an example to show how you can invoke the Device Monitor card:
<invoke-target id="sys.SysMon.card">
<entry-point-id>sysmon_app</entry-point-id>
<invoke-target-type>card.previewer</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>*</mime-type>
<property var="uris" value="devicemonitor://"/>
</filter>
</invoke-target>
Docs to Go
Opening a spreadsheet
Here are the invocation attributes you use to open a spreadsheet in a previewer card:
Attribute
Target ID
Action
URI
MIME type
Value
sys.sheettogo.previewer
bb.action.VIEW
file:///path/to/my/content.xls
application/vnd.ms-excel,
application/vnd.openxmlformats-
Adding Features
161
Attribute
Value
officedocument.spreadsheetml.sheet,
application/vnd.openxmlformatsofficedocument.spreadsheetml.template
, application/vnd.msexcel.sheet.macroEnabled.12,
application/vnd.msexcel.template.macroEnabled.12
File extensions
Here are the invocation attributes you use to open a spreadsheet file in the Docs to Go app:
Attribute
Target ID
Action
URI
MIME type
File extensions
Value
sys.dxtg.stg
bb.action.OPEN
file:///path/to/my/content.xls
application/vnd.ms-excel,
application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet,
application/vnd.openxmlformatsofficedocument.spreadsheetml.template
, application/vnd.msexcel.sheet.macroEnabled.12,
application/vnd.msexcel.template.macroEnabled.12
.xls, .xlt, .xlsx, .xltx, .xlsm, .xlt
m
Adding Features
162
Opening a presentation
Here are the invocation attributes you use to open a presentation in a previewer card:
Attribute
Target ID
Action
URI
MIME type
File extensions
Value
sys.slideshowtogo.previewer
bb.action.VIEW
file:///path/to/my/content.ppt
application/vnd.ms-powerpoint,
application/vnd.openxmlformatsofficedocument.presentationml.present
ation, application/
vnd.openxmlformatsofficedocument.presentationml.templat
e, application/vnd.openxmlformatsofficedocument.presentationml.slidesh
ow, application/vnd.mspowerpoint.presentation.macroEnabled.
12, application/vnd.mspowerpoint.template.macroEnabled.12,
application/vnd.mspowerpoint.slideshow.macroEnabled.12
.ppt, .pot, .pps, .pptx, .potx, .ppsx
, .pptm, .potm, .ppsm
Here are the invocation attributes you use to open a presentation file in the Docs to Go app:
Attribute
Target ID
Action
Value
sys.dxtg.stg
bb.action.OPEN
Adding Features
163
Attribute
URI
MIME type
File extensions
Value
file:///path/to/my/content.ppt
application/vnd.ms-powerpoint,
application/vnd.openxmlformatsofficedocument.presentationml.present
ation, application/
vnd.openxmlformatsofficedocument.presentationml.templat
e, application/vnd.openxmlformatsofficedocument.presentationml.slidesh
ow, application/vnd.mspowerpoint.presentation.macroEnabled.
12, application/vnd.mspowerpoint.template.macroEnabled.12,
application/vnd.mspowerpoint.slideshow.macroEnabled.12
.ppt, .pot, .pps, .pptx, .potx, .ppsx
, .pptm, .potm, .ppsm
Opening a document
Here are the invocation attributes you use to open a document in a previewer card:
Attribute
Target ID
Action
URI
MIME type
Value
sys.wordtogo.previewer
bb.action.VIEW
file:///path/to/my/content.doc
application/msword, text/plain,
application/vnd.openxmlformatsofficedocument.wordprocessingml.docum
Adding Features
164
Attribute
Value
ent, application/vnd.openxmlformatsofficedocument.wordprocessingml.templ
ate, application/vnd.msword.document.macroEnabled.12,
application/vnd.msword.template.macroEnabled.12
File extensions
Here are the invocation attributes you use to open a document file in the Docs to Go app:
Attribute
Target ID
Action
URI
MIME type
File extensions
Value
sys.dxtg.stg
bb.action.OPEN
file:///path/to/my/content.doc
application/msword, text/plain,
application/vnd.openxmlformatsofficedocument.wordprocessingml.docum
ent, application/vnd.openxmlformatsofficedocument.wordprocessingml.templ
ate, application/vnd.msword.document.macroEnabled.12,
application/vnd.msword.template.macroEnabled.12
.doc, .dot, .txt, .docx, .dotx, .docm
, .dotm
Adding Features
165
Email
Sharing a file
Here are the invocation attributes you use to share a file:
Attribute
Target ID
Action
URI
MIME type
Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE
file:///path/to/file
Any valid MIME type value
Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE
file:///path/to/event.ics
text/calendar
Sharing text
Here are the invocation attributes you use to share text through an email composer:
Adding Features
166
Attribute
Target ID
Action
Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE
MIME type
Data
text/plain
Text to share as a QByteArray
Value
sys.pim.uib.email.hybridcomposer
bb.action.SHARE
URI
list://
MIME type
filelist/[subtype]
"uri": "file:///path/to/file"
},
...
167
Attribute
Target ID
Action
Value
sys.pim.uib.email.hybridcomposer
bb.action.OPEN, bb.action.SENDEMAIL
Value
sys.pim.uib.email.hybridcomposer
bb.action.COMPOSE
message/rfc822
or
Adding Features
168
stuff* @ home.\n",
"attachment" : ["file:///path/to/my/item.txt"]
}
The accountid field in the code above represents the account ID that is used as a default value for the
composer card.
MIME type
Value
sys.pim.uib.email.hybridcomposer
bb.action.REPLY, bb.action.REPLYALL,
bb.action.FORWARD
message/rfc822
The URI points to the message that is being replied to or being forwarded and is sent in the following format:
pim:message/rfc822:[accountID]:[messageID]
Value
sys.pim.uib.email.previewer
bb.action.VIEW
message/rfc822
The URI points to the message that is viewed and is sent in the following format:
pim:message/rfc822:[accountID]:[messageID]
Adding Features
169
Facebook
All the invocation attributes related to the Facebook app require a Facebook account to be set up on the
device.
Value
Facebook
bb.action.SHARE
MIME type
text/plain
URI
data://
Data
Value
Facebook
bb.action.SHARE
URI
file:///path/to/content.png
File extensions
Adding Features
170
Attribute
Value
MIME type
Value
Facebook
bb.action.SHARE
URI
http://, https://
Entry
Description
object_type
object_id
Here's an example that shows how you can open a business profile page:
blackberry.invoke.invoke( {
target: "com.rim.bb.app.facebook",
action: "bb.action.OPEN",
Adding Features
171
metadata: JSON.stringify
({object_type : 'page' , object_id : '328506290597521'})
}, onSuccess, onError );
Foursquare
Opening a single sign-on card
Here are the invocation attributes you use to open a single sign-on card:
Attribute
Target ID
Action
MIME type
Data
Value
com.foursquare.blackberry.sso.card
bb.action.VIEW
sso/foursquare
Client ID (for example,
JDHEN48FRJ47FJFRI4FJFRJ4843JRF8484JFK
DOEWYU37RUJ)
Action
MIME type
URI
Value
com.foursquare.blackberry.venuesearch
.card
bb.action.VIEW
venuesearch/foursquare
"foursquare://venues/search?
oauth_token=" + accessToken
Adding Features
172
Exploring a venue
Here are the invocation attributes you use to explore a venue:
Attribute
Target ID
Action
URI
Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://venues/explore
Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://venues/<VENUE ID> (for
example, foursquare://venues/
4ef0e7cf7beb5932d5bdeb4e)
Value
com.foursquare.blackberry.uri
Adding Features
173
Attribute
Action
URI
Value
bb.action.OPEN
foursquare://checkins/<check-in ID> (for
example, foursquare://checkins/
50a08609e4b04c46ea54446d)
Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/self/update
Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/requests
Adding Features
174
Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/suggest?
type=friend
Value
com.foursquare.blackberry.uri
bb.action.OPEN
foursquare://users/suggest?type=page
Adding friends
Here are the invocation attributes you use to add friends from Contacts, Twitter, Facebook, or Search:
Attribute
Target ID
Action
Value
com.foursquare.blackberry.uri
bb.action.OPEN
Adding Features
175
Attribute
URI
Value
foursquare://users/addfriends?
from=phonebook
LinkedIn
All the invocation attributes related to the LinkedIn app require a LinkedIn account to be set up on the device.
Value
LinkedIn
bb.action.SHARE
MIME type
text/plain
URI
data://
Data
Value
Target ID
com.linkedin.urihandler
Action
bb.action.VIEW
Adding Features
176
Attribute
Value
URI
linkedin:contact:<public_URL_of_the_L
inkedIn_profile_page>
The public URL can be in the following format:
ca.linkedin.com/...
Maps
You can invoke BlackBerry Maps by using the Invoke API with the following invocation attributes:
Attribute
Value
Action
bb.action.OPEN
MIME type
application/vnd.rim.map.action-v1
The MIME type above defines all the actions that BlackBerry Maps handles. For example, setting the map
center or starting navigation mode. The data passed in the invocation request is in JSON format.
Values
Description
center
JSON object
center.latitude
[-90.0,90.0]
center.longitude
[-180.0,180.0]
Adding Features
177
Attribute
Values
Description
center.heading
[0,359]
center.altitude
placemark
JSON object
placemark.latitude
[-90.0,90.0]
placemark.longitude
[-180.0,180.0]
placemark.name
String
Location name
placemark.description
String
Location description
placemark.geocode
true or false
geolocation
true or false
178
Launching the Maps app and getting the current device location
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"geolocation": true
}
)
}
);
Launching the Maps app and centering the map at a particular location
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"center": {
"latitude": 43.4667,
"longitude": -80.5167,
"altitude": 2000
}
}
)
}
);
179
Values
Description
view_mode
nav
nav_start or nav_end
JSON object
nav_start.properties or
nav_end.properties
JSON object
nav_start.properties.nam
e or
nav_end.properties.name
String
nav_start.properties.des
cription or
nav_end.properties.descr
iption
String
nav_start.latitude or
nav_end.latitude
[-90.0,90.0]
Adding Features
180
Attribute
Values
Description
nav_start.properties or
nav_end.properties.
nav_start.longitude or
nav_end.longitude
[-180.0,180.0]
nav_options
JSON object
nav_options.nav_mode
fastest or shortest
nav_options.avoid_highwa
ys
true or false
nav_options.avoid_tolls
true or false
181
}
);
"latitude": 43.7,
"longitude": -79.4
Adding Features
182
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
Action
bb.action.VIEW
URI
file://
http://
Description
contentTitle
imageUri
Adding Features
183
The invocation attributes you use to open audio or video files with the Media Player application require the
same set of attributes as the ones you use for the Media Player cards, except for the target ID:
Attribute
Value
Target ID
sys.mediaplayer.previewer.app
Miracast card
You can invoke a Miracast card to discover and establish a connection to a nearby Miracast device. You can
invoke the Miracast card in two modes: play on and show on.
Value
sys.miracastviewer
bb.action.VIEW
application/vnd.rim.miracast.showon
Value
sys.miracastviewer
bb.action.VIEW
Adding Features
184
Attribute
Value
MIME type
application/vnd.rim.miracast.playon
NFC
Sharing a single local file or a URI
Here are the invocation attributes you use to invoke an NFC card to share a single local file or a URI:
Attribute
Target ID
Action
Value
sys.NFCViewer
bb.action.SHARE
URI
MIME type
Value
sys.NFCViewer
bb.action.SHARE
list://
Adding Features
185
Attribute
Value
MIME type
Data
}]
"uri":<file-uri>,
"type":<mime-type>,
"data":<metadata>
In the above code, the uri is the local path to the file,
type is the MIME type for the specified file, and
data is the associated metadata for the specified file
(for example, thumbnail).
Sharing text
Here are the invocation attributes you use to invoke an NFC card to share text:
Attribute
Target ID
Action
MIME type
Data
Value
sys.NFCViewer
bb.action.SHARE
text/plain
Text is sent as a byte array. UTF-8 encoding is
supported.
Adding Features
186
Value
sys.NFCViewer
bb.action.SHARE
application/vnd.rim.nfc.ndef
An NDEF message is sent in the form of a byte array.
The nfc_get_ndef_message_bytes() function
is used to create the byte array message.
Sharing URLs
Here are the invocation attributes you use to invoke an NFC card to share URLs, including remote files (for
example, http://aa.mp3):
Attribute
Target ID
Action
MIME type
Data
Value
sys.NFCViewer
bb.action.SHARE
text/URI-list
Data is sent as a URI to the remote file or link and
must be URI encoded (for example, http://
somesite/multi%20word%name.doc).
Adding Features
187
Value
sys.NFCViewer
bb.action.SHARE
MIME type
Data
Phone
Opening call logs
Here are the invocation attributes that you use to open the call log. If you don't specify the call log in the MIME
type, the full call log list is displayed.
Attribute
Value
Data
Action
MIME type
bb.action.OPEN
application/vnd.blackberry.calllog.id
188
Attribute
Action
MIME type
Value
bb.action.DIAL
application/
vnd.blackberry.phone.dialpad
Here are the data attributes that you use to populate the dial pad with a number before showing it:
Data
Description
Line ID to use
int contact_id
Dialing a number
Here are the invocation attributes that you use to dial a number:
Attribute
Action
MIME type
Value
bb.action.DIAL
application/
vnd.blackberry.phone.startcall
Here are the data attributes that you use to dial a number:
Data
Description
Adding Features
189
Data
Description
Line ID to use
int contact_id
Boolean apply_smart_dialing
Value
bb.action.EMERGENCY_CALL
application/
vnd.blackberry.phone.startcall
Pictures
Opening images
Here are the invocation attributes you use to open images with the picture previewer:
Attribute
Target ID
Action
Value
sys.pictures.card.previewer
bb.action.VIEW
MIME type
URI
file:///
Adding Features
190
Picture editor
Invoking the picture editor card
Here are the invocation attributes you use to invoke the picture editor card:
Attribute
Value
Target ID
sys.pictureeditor.cardeditor
Action
bb.action.EDIT
URI
file:///path/to/content.jpg
Value
Example
size
WIDTHxHEIGHT
800x600
upScale
true or false
QString upScale=
"false";
You can configure the size of the output image by using the size and upScale parameters. The size
parameter allows you to specify the dimensions of the output image in pixels and the upScale parameter
identifies whether the output image is scaled to that specified size or not. The upScale parameter is valid only
if you define a size for your output image. In addition, true is the default value for the upScale parameter.
Depending on how you use these two parameters, you will have one of the three outcomes mentioned below.
191
In this case, the size of the output image is exactly the same as specified by the size parameter. On opening,
the picture editor's Transform tab opens by default for this case. The output image is cropped to the same
aspect ratio as the size. The user can't change the aspect ratio of the output image because the buttons to
change the aspect ratios are disabled in the picture editor.
When saving the output image, if the size of the edited image is different from the specified size, the output
image is scaled automatically to the specified size. This use case is demonstrated in the Contacts app of the
BlackBerry 10 OS.
Remember
Creating a new entry
Here are the invocation attributes that you use to open a Remember card to create a new entry:
Attribute
Target ID
Action
URI
Value
sys.pim.remember.composer
bb.action.ADD
remember://notebookentry
You can also add the following key-value pairs by
adding a question mark (?) after the URI:
title=<ENTRY TITLE>
Adding Features
192
Attribute
Value
description=<ENTRY DESCRIPTION>
duedate=<# SECONDS SINCE EPOCH>
status=NotActionable, Completed,
NotCompleted
notebookid=<ACCOUNT KEY>:<NOTEBOOK
KEY>
tags=<COMMA-SEPARATED TAG LIST>
For the URI attribute, make sure that the entire URI is percent-encoded.
Value
sys.pim.remember.composer
bb.action.SHARE
file://
list://
http://
https://
Metadata
Adding Features
193
Attribute
Value
For http:// and https:// URIs, you can provide
a JSON map containing key-value pairs for the
subject and description of the URI. For example:
{
"description": "Webpage
description"
}
Data
MIME type
Editing an entry
Here are the invocation attributes that you use to open a Remember card to edit an entry:
Attribute
Target ID
Action
Value
sys.pim.remember.composer
bb.action.EDIT
Adding Features
194
Attribute
URI
Value
pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>
Viewing an entry
Here are the invocation attributes that you use to open a Remember card to view an entry:
Attribute
Target ID
Action
URI
Value
sys.pim.remember.previewer
bb.action.VIEW
pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>
Opening an entry
Here are the invocation attributes that you use to open a Remember card to open an entry:
Attribute
Target ID
Action
URI
Value
sys.pim.remember
bb.action.OPEN
pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>
Adding Features
195
Search
Searching using keywords
Here are the invocation attributes that you use to search with keywords:
Attribute
Value
Target ID
sys.search
Action
bb.action.OPEN
MIME type
URI
search://?term=<keywords>, where
keywords are free-form text
196
<filter>
<action>bb.action.SEARCH.EXTENDED</action>
<mime-type>application/vnd.bb.search.criteria</mime-type>
</filter>
</invoke-target>
When your app is registered, the Search app displays your app in the Extend Search section using your apps
name and icon. Your app receives any search requests as invocation requests. The search string is delivered in
the data attribute of the request as an in-band transfer.
Registering for active search
To register your app as an invocation target for active search, here's how you can specify your app in the
config.xml file:
<invoke-target id="com.blackberry.search.asyoutype.test1">
<invoke-target-type>APPLICATION</invoke-target-type>
<filter>
<action>bb.action.SEARCH.SOURCE</action>
<mime-type>application/vnd.bb.search.db.criteria</mime-type>
</filter>
</invoke-target>
When your app is registered, the Search app displays your app in one of the active search categories using
your apps name and icon. The Search app discovers and displays your app dynamically as a data source or
category (for example, alongside the Messages or Calendar apps). When the user types a search term, the
Search app queries a database in your app for results and displays the results in the appropriate category.
When the user taps a search result, an invocation request is sent to your app so that it can display the details of
that result.
When you register your app for active search, your app must provide searchable data for the Search app to
access. The BlackBerry 10 OS includes the /sharewith/search/ folder for an app to share its search data (for
example, /accounts/1000/appdata/myapp/sharewith/search/). The Search app has read-only access to this
folder, and your app must provide a searchable database in this folder to let the Search app perform queries.
Note: For more information about folders in the BlackBerry 10 OS, see File system access.
Requirements for the search database
There are a few rules that you must follow when you create the search database:
The database must be an SQLite3 database and the database file name must be search.db (for example, /
accounts/1000/appdata/myapp/sharewith/search/search.db).
The search.db database file must include two tables:
search: This table is a full-text search (FTS) table that contains the search data.
search_info: This table contains information that isn't searchable but is required by the Search app to
render, view, or sort the search results. For example, this table might provide a timestamp, an icon, and
an invocation URI for each result.
Adding Features
197
You can include other tables in the search.db file, but they are optional and depend on the features of your
app.
The search table must meet the following criteria:
It must be an FTS table, which provides the Search app with behavior and search results that are
consistent with other data sources.
It must include the title and description columns to store searchable data. The Search app uses the
data in these columns to display the search results. You should keep the data in these columns small
enough to be displayed correctly, but large enough to provide useful information to users.
It must use TOKENIZE=icu instead of the default simple tokenizer. This tokenizer provides
consistency across data sources and helps to improve the quality of search results in certain languages,
such as Chinese.
It can have as many other columns as are required to support the features in your app.
Here's an example of an SQL creation script that you can use to create the search table:
CREATE VIRTUAL TABLE search USING fts4 (
title, description,
<optional app-specific columns>,
TOKENIZE=icu);
The search_info table can optionally include the following columns:
icon_path
This column contains a relative path to an image in the app sandbox folder. If this value is empty, then
the Search app displays an image of the app in the search result. Icons must be configured as public
assets in the bar-descriptor.xml file so that they're stored in the /app/public/ folder on the device. For
example, a valid icon path is /app/public/search_icon.png.
uri
This column contains an unbound URI that can be used to invoke a specific result. If no URI is
provided, the app is invoked with a result ID as the in-band data, which is discussed in Handling an
invocation request from active search on page 199 below.
timestamp
This column contains a timestamp in Epoch format. This timestamp is localized and displayed in a
common format, depending on the locale of the device. This column can be empty if it's not
applicable in your app.
group_id
This column allows your app to control how search results are grouped and displayed in the Search
app.
Here's an example of an SQL creation script that you can use to create the search_info table:
CREATE TABLE search_info (
icon_path VARCHAR(128),
Adding Features
198
uri VARCHAR(128),
timestamp INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0);
The search and search_info tables should be organized so that the docid column in the search table has a
1:1 relationship with the rowid column in the search_info table. For more information about how to
structure these tables for your apps, see Examples on page 199.
The search.db database file that you share with the Search app can include other tables that your app uses.
The Search app reads only the search and search_info tables, and the Search app is the only part of the
BlackBerry 10 OS that has read-only access to the /sharewith/search/ folder. Your app is the only component
that has read-write access to the data that it provides.
Handling an invocation request from active search
When your app is invoked from an active search result, the data attribute contains a result ID as an in-band
transfer. Your app can use the result ID to check the search.db database file and find the corresponding
record. The result ID is one of the rowid values in the search_info table.
Note: Your app can handle the invocation as an application or a card.
Examples
The following examples show you how you can structure the search and search_info tables to provide active
search results from your app.
Searching by title and description
This example shows how you can provide titles and descriptions that are searchable and displayed in active
search results. It also demonstrates how your app can have additional custom columns that are also
searchable. The example includes the address, phone_number, and mobile_number columns, as well as the
required title and description columns.
DROP TABLE IF EXISTS search_info;
DROP TABLE IF EXISTS search;
CREATE TABLE search_info (icon_path VARCHAR(128),
uri VARCHAR(128),
timestamp INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0);
CREATE INDEX search_info_timestamp_index ON search_info(timestamp);
CREATE INDEX search_info_groupid_index ON search_info(group_id);
CREATE VIRTUAL TABLE search USING fts4 (title, description, address,
phone_number, mobile_number,
TOKENIZE=icu);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(1, "", "http://www.example.com", 0, 1);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(2, "app/public/test1.jpg", "", 0, 2);
INSERT INTO search_info(rowid, icon_path, uri, timestamp, group_id)
VALUES(3, "", "", 0, 3);
Adding Features
199
title
description
Denise
Marshall
Westlee
Barichak
icon_path
uri
timestamp
group_id
BlackBerry
BlackBerry
http://
0
www.example
.com
200
group_id)
group_id)
group_id)
group_id)
1, conversation 1");
2, conversation 1");
1, conversation 2");
2, conversation 2");
3, conversation 2");
title
description
IM
conversation
1
IM
conversation
2
icon_path
uri
timestamp
group_id
1365303001
1365003004
201
group_id)
group_id)
group_id)
group_id)
group_id)
1, conversation 1");
2, conversation 1");
1, conversation 2");
2, conversation 2");
3, conversation 2");
title
description
IM
conversation
2
icon_path
uri
timestamp
group_id
1365403004
IM
conversation
2
1365403003
IM
conversation
2
1365403002
IM
conversation
1
1365403001
Adding Features
202
rowid
title
description
icon_path
uri
timestamp
group_id
1365403000
conversation
1
1
IM
conversation
1
Settings
Opening the notification settings of an app
Here are the invocation attributes you use to open the notification settings card of an app:
Attribute
Target ID
Action
MIME type
URI
Value
sys.settings.card
bb.action.OPEN
settings/view
settings://notification/application?
id= + packageInfo.name() (for example,
settings://notification/application?
id=com.foo.bar)
To open the notification settings of a core app, you
can use the following app ID: phone, bbm,
bbmvideo, text, reminders, facebook,
twitter, linkedin, foursquare.
Adding Features
203
Attribute
Target ID
Action
MIME type
Value
sys.settings.card
bb.action.OPEN
settings/view
Here's a list of URIs you can use to invoke different Settings cards:
Setting
About screens
URIs
settings://about
settings://about/general
settings://about/hardware
settings://about/os
settings://about/network
settings://about/legal
settings://about/workspace
Accessibility
Accounts
settings://accessibility
settings://pim
settings://pim/defaultAccounts
settings://pim/createAccount
settings://pim/listAccounts
settings://pim/createAccountType?
type=<type> where type can be facebook,
twitter, linkedin, evernote, or
mail_contacts_calendar
settings://pim/showAccount?id=<id>
Adding Features
204
Setting
URIs
settings://pim/deleteAccount?id=<id>
settings://pim/EnrollmentProgress
Application Manager
settings://appmgr
Application Permissions
settings://permissions
BlackBerry Balance
settings://balance
BlackBerry ID
settings://bbid
BlackBerry Link
settings://link
BlackBerry Protect
settings://protect
Bluetooth
settings://bluetooth
Certificates
settings://certificates
Child Protection
settings://childprotection
settings://datetime
Default Applications
settings://defaultapps
Development Mode
settings://devmode
Device Monitor
settings://sysmon
Diagnostics
settings://diagnostics
Display
settings://display
settings://display/advanced
settings://language
settings://language/input
settings://language/keyboard
settings://language/spellcheck
settings://language/assistance
Location
settings://location
Mobile Hotspot
settings://mhs
Adding Features
205
Setting
URIs
Mobile Network
settings://radio
Network Connections
settings://networkconnections
NFC
settings://nfc
Notification
settings://notification
Password
settings://password
Payment Options
settings://payment
Screen Reader
settings://screenreader
Search
settings://search
Security
settings://security
Sharing
settings://sharing
SIM Card
settings://sim
Software Updates
settings://softwareupdate
Sound
settings://sound
settings://storage
Tethering
settings://tethering
USB
settings://usb
Video Chat
settings://videochat
Voice Control
settings://voice
VPN
settings://vpn
Wi-Fi
settings://wifi
Wipe
settings://wipe
Text Messages
Composing a text message
Here are the invocation attributes that you use to open the composer card for the Text Messages app with
specific body text and recipients:
Adding Features
206
Attribute
Target ID
Action
MIME type
Value
sys.pim.text_messaging.composer
bb.action.COMPOSE
application/text_messaging
Data
Value
sys.pim.text_messaging.smsuri
application/
vnd.blackberry.string.phone
Recipients phone number
You can perform the same invocation by using the following invocation attributes in your invocation request:
Adding Features
207
Attribute
Target ID
Action
URI
Value
sys.pim.text_messaging.smsuri
bb.action.SENDTEXT
tel:5198887465
Value
sys.pim.text_messaging.sharemedia
bb.action.SHARE
list://
filelist/media
You can perform the same invocation by using the following invocation attributes in your invocation request:
Attribute
Target ID
Action
URI
Value
sys.pim.text_messaging.smsuri
bb.action.SENDTEXT
tel:5198887465
Adding Features
208
"uri": "file:///path/to/file"
},
{
"uri": "file:///path/to/another_file"
},
...
Twitter
All of the invocation attributes related to the Twitter app require a Twitter account to be set up on the device.
Value
Target ID
Action
bb.action.SHARE
MIME type
text/plain
URI
data://
Data
Value
Target ID
Adding Features
209
Attribute
Value
Action
bb.action.SHARE
URI
file:///path/to/content.png
File extensions
MIME type
Value
Target ID
Action
bb.action.SHARE
URI
http://, https://
Value
Target ID
com.twitter.urihandler
Action
bb.action.VIEW
Adding Features
210
Attribute
Value
URI
twitter:connect:<twitter_profile_name
>
The profile name must not contain the at sign (@)
prefix. For example, here's the correct format:
twitter:connect:blackberry.
Searching Twitter
Here are the invocation attributes you use to search Twitter for relevant tweets containing a search term:
Attribute
Value
Target ID
com.twitter.urihandler
Action
bb.action.VIEW
URI
twitter:search:<search_term>
Using a hashtag symbol as a prefix in your search
results is optional (for example,
twitter:search:#BB10Believe).
Video editor
The video editor allows the user to change the saturation, brightness, contrast, and audio volume of a video
clip. The video editor can also trim, crop, and rotate the video clip.
Editing a video
Here are the invocation attributes you use to invoke the video editor card:
Adding Features
211
Attribute
Target ID
Action
Value
sys.video_editor.card
bb.action.EDIT
URI
videoeditor:///path/to/content.mp4
MIME type
video/mp4
Voice note
The voice note card allows the user to record a voice note and save it.
Value
sys.apps.audiorecorder
bb.action.CAPTURE
Any valid MIME type value
file://
.wav, .m4a, .3gp, .amr, .awb, .qcp
The metadata of the voice note is specified by size and format attributes. The format attribute can be
specified in any of the file extensions listed above.
YouTube
Sharing a video with YouTube
Here are the invocation attributes you use to share a video with YouTube:
Adding Features
212
Attribute
Target ID
Action
Value
Youtube
bb.action.SHARE
URI
file:///path/to/content.mp4
File extensions
.3gp, .
3gpp, .avi, .flv, .m2v, .mp4, .mov, .
webm, .wmv
Adding Features
213
</invoke-target>
Attribute
Description
<invoketarget>
<type>
Can be APPLICATION or
CARD.
<filter>
<invoketargetpattern>
and
<patternvalue>
To link to an active text target from a WebWorks app, add an anchor tag to your HTML source.
<a href="activetext://test">Active Text Link</a>
To get the value of an active text invocation, check the uri property in the invoked callback.
document.addEventListener('invoked', function (args) {
console.log(args.uri);
});
Adding Features
214
For the App Launch Shortcut type, you don't need to do anything special in your app for it to appear in this list;
your app is included automatically. The user can select the App Launch Shortcut menu option and assign your
app to the key. When the user presses and holds the shortcut key, your app starts.
Instead of just starting your app, you might want users to be able to create a shortcut to a specific task in your
app. For example, if your app allows users to create a new item or entry, you could create a shortcut directly to
the creation screen in your app. To do this, you define an invocation target with an action of
bb.action.SHORTCUT and a MIME type of application/vnd.blackberry.shortcut. These values
let your custom shortcut appear in the Other Shortcut category for the user to select and assign to a key. You
can define as many custom shortcuts as you want, each performing a specific task in your app. Don't forget to
provide an appropriate label and icon for your shortcut!
Adding Features
215
For some shortcut tasks, it doesn't make sense to invoke an app UI to perform the task. For example, for a
shortcut that mutes the notification sounds on a device, it isn't necessary to open an app UI when the shortcut
key is pressed. To support this behavior, you can use a headless invocation target as a shortcut. If you choose
to use this approach, make sure to provide the user with feedback when your headless app finishes the task.
You could flash the LED or vibrate the device, or you could consider other notification options such as
notification dialog boxes or instant previews.
To learn more about headless apps, including how to create one from scratch, see Headless apps.
You define your invocation target in the bar-descriptor.xml file for your app. Here's an example of a target that
defines the "Quick Respond" shortcut for an app:
<invoke-target id= "com.example.EmergencyResponder">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>Quick Respond</invoke-target-name>
<icon>
<image>quick_respond_icon.png</image>
</icon>
<filter>
<action>bb.action.SHORTCUT</action>
<mime-type>application/vnd.blackberry.shortcut</mime-type>
</filter>
</invoke-target>
Note: When you create filters for shortcuts in your app, it's a good idea to always give the target a meaningful
icon and name that describes the task that it performs.
For more information about defining invocation targets, see Target declaration on page 121.
Adding Features
216
Adding Features
217
Menu integration
The BlackBerry 10 OS offers a well-integrated menu system that enables you to make highly contextual apps.
There are two types of menus available on the UI of a BlackBerry 10 device: action menu and context menu.
This section shows you how to add menus to your app and how to use the invocation framework to display your
app in the context menu of other apps. This section also shows you how to configure your app to allow the
BlackBerry 10 OS to automatically populate any related actions into the context menu of your app.
It's a good practice to add invocation-related actions to the context menu. However, if an action applies to the
whole page, you can add the action to the action bar.
To learn more about the action and app menus, see Menus.
Context menu
The context menu is a vital part of building an intuitive experience and is a key feature in BlackBerry 10. When
the user presses and holds a particular area of the app UI, the context menu is presented. The context menu is
divided into two sections that offer actions related to the content selected by the user.
The upper section of the context menu is the app section, which contains all of the actions that the app adds.
For example, in the following image on the right, Add as friend, Call, Email, and Text actions are all app
actions.
The lower section of the context menu is the platform section, which contains all of the actions that the
BlackBerry 10 OS adds automatically. In the following image on the right, Delete is a platform action.
Adding Features
218
Adding Features
219
Adding Features
220
Here's how the images for the Email and Text Messages apps look in the suggestions section:
Note: As a best practice, remember to fill any transparent pixels in your image with color. This approach
prevents the background color of the suggestions grid from appearing through the transparent pixels.
You should specify the images in the config.xml file of your app, as follows:
...
<icon>
<image public="true"> icon_small.png</image>
<image public="true"> icon_big.png</image>
</icon>
...
221
Finance
Cashalyst
Import and View Quicken (qfx) and ofx bank files
Use this invocation target to import and view Quicken (qfx) and ofx bank transaction files. QFX/OFX files can be
downloaded from your online bank website.
Attribute
Target type
Target ID
Action
MIME type
File extensions
Data description
Value
application
com.digicasa.cashalyst.import
bb.action.OPEN, bb.action.VIEW
application/*, text/*
qfx, ofx
Invocation requires either a file:// with the full path to
the qfx/ofx file or a data://local with the complete
contents of the qfx/ofx file.
Games
Anagrammatist EN
Search for the anagrams
Adding Features
222
Invocation calls Anagrammatist EN app. This application provides some functions for the word games - like
checking if the provided word exists, seraching for anagrams, searching for all the possible words from the
given letters etc.
Attribute
Target type
Target ID
Action
MIME type
Data description
Value
application
AnagrammatistEN591c82ab559936cc457d58
1de4df064
bb.action.SEARCH.EXTENDED
application/vnd.bb.search.criteria
In general, the string (set of letters) is accepted.
Ambience
Ambient Sounds for BlackBerry
Create some ambience with images and sounds.
Attribute
Target type
Target ID
Value
application
ambience
Adding Features
223
Attribute
Action
MIME type
Value
bb.action.OPEN
text/plain
Photo Effect
PhotoEffect
Create beautiful photo effects.
Attribute
Target type
Target ID
Action
MIME type
URIs
File extensions
Data description
Value
application
com.umang.PhotoEffect
bb.action.OPEN
image/*, image/png, image/jpg, image/jpeg
file://
png, jpg, jpeg
Invocation requires either a file:// with the full path to
the qfx/ofx file or a data://local with the complete
contents of the qfx/ofx file.
Adding Features
224
Productivity
Value
card.composer
org.ekkescorner.charts.chartimages
bb.action.SHARE
image/jpeg
CardDone Message sends you 'Done' if all is ok and
'Cancel' if user canceled.If result is 'Done' you'll get
the path to the image from data. See the sample app
how to construct the filename right.
225
long as their BlackBerry devices are connected to a wireless network, BBM can keep users connected to their
BBM contacts and groups.
The BBM SDK, used in conjunction with the BlackBerry WebWorks SDK, lets you use the same infrastructure
upon which BBM is built to communicate between instances of your app on multiple BlackBerry devices. For
example, in a chess game app, a BlackBerry device user could invite a BBM contact to play a game of chess,
and the moves could be communicated back and forth using the BBM platform.
Leverage the features of the BBM platform
You can access the same infrastructure that BBM, one of the most successful and widely used mobile social
platforms, is built upon. With the BBM SDK, you can develop apps that incorporate social features such as
peer-to-peer connections between BlackBerry devices, or integrated chats. There is no need to develop these
social features yourself, and no server-side development is required to support them.
The BBM platform provides support for the social aspects of your app, such as tracking which BlackBerry
devices your app is installed on, managing the connections between instances of your app, and proactively
discovering the contacts who have already installed the app.
Increase the stickiness of your app
A sticky application is one that users find useful, engaging, and use frequently. When you integrate BBM into
your app you can create a community where BlackBerry device users can get together, socialize, and
communicate. Adding this social aspect can help your app maintain its presence on BlackBerry devices and
help attract users.
Increase the discoverability of your app
When people like something, they want to share it with others. Because BlackBerry device users can
communicate with any or all of their BBM contacts from within an app, when you create a BBM connected
app, you have a built-in advertising system.
Users can not only encourage their contacts to download your app, they can actively invite them to do so by
sending an invitation that links directly to the application details page in the BlackBerry World storefront.
226
BlackBerry devices, users might be encouraged to try your application. You can use the following sample
text in your description: "By connecting this application to BBM, you and your contacts can get together,
socialize, and communicate by <insert a phrase that describes what users can do (for example, playing
games against each other)>."
Create an application icon that is 114 x 114 pixels.
Design an icon that is visually interesting. Make sure that users can distinguish the icon from the
background of the screen and that they can distinguish your application from other applications. Avoid
using BlackBerry Messenger icons or BBM branding in your application.
Adding Features
227
Adding Features
228
Install Java
The first thing you need to do is download and install the Java SE 6 update 37 or later (JDK or JRE, 32-bit or 64bit).
Note: The BBM server simulator does not support Java 7.
Next, you set up Java environment variables and unlimited strength encryption.
Adding Features
229
230
6.
7.
8.
9.
Communication limitations
To prevent an application from using too much of the available bandwidth, the BlackBerry Messenger platform
limits the total volume of data that is transferred by a BBM connected application as follows:
Adding Features
231
All messages and application data transferred over channel and session connections for all BBM
connected applications that are running on a BlackBerry device are collectively limited to a maximum data
transfer rate that is configured by the BBM server. If the total volume of data attributed to an application
threatens to exceed the maximum transfer rate, the BBM platform throttles data traffic for that application
to reduce the transfer rate to an acceptable level. File transfers sent from a BBM connected application are
not considered to be application data, and are therefore exempt from this limitation on the data transfer
rate.
Data sent from a BBM connected application over a channel/session connection is limited to a maximum of
60 KB per transfer.
File transfers from a BBM connected application are limited to a maximum of 6 MB per file.
The maximum number of users in a connection is limited to 24.
UUID Guidelines
A Universally Unique Identifier (UUID), also known as a Globally Unique Identifier (GUID), is a unique, 128-bit,
36-character identifier that you generate for your app using a UUID/GUID generator. Your app must provide a
UUID when it registers with the BBM social platform to access the social platform APIs. The UUID string must
conform to the Microsoft 8-4-4-4-12 format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). Valid characters consist of
hexadecimal values in the ranges 0 to 9 and a to f.
The UUID is also used to identify your app (along with the vendor name and the app name) in the preproduction test environment, before the app is made available in BlackBerry World. If the app is installed from
BlackBerry World, the UUID is not used to identify it. You should use the same UUID when testing future
releases of the same app. If the UUID changes across versions, different versions of the same app will not be
able to communicate with each other in the pre-production environment.
Payment Service
After you create an awesome app, you might want to offer in-app purchases. The Payment Service lets you do
just that. To get started, you need to include the Payment Service classes into your app. Then you can add your
app on the vendor portal for the BlackBerry World storefront. You can add digital goods to your app, offer
subscriptions, and charge for additional features. Learn more about getting your app up for sale on BlackBerry
World.
Adding Features
232
You can use your imagination to decide what digital goods to create, and how best to offer them for sale from
within your app. For example, you can:
Sell guides to help users learn about levels, back doors, and bonus points.
Offer additional levels or new characters in your game.
Upgrade your users to the advanced version of your app.
Sell extra services, such as music or video streaming in your app.
Offer items such as eBooks, personalized greeting cards, photos, and maps.
Sell subscriptions to renewable goods, such as magazines and newsletters.
You can incorporate the Payment Service in your app and then upload the app and its digital goods, along with
pricing and a description to the BlackBerry World vendor portal. The Payment Service manages all the
technical and financial details for you. You don't have to waste time managing relationships or business terms
with payment providers and coding for integration into each provider's solution.
A fast and familiar payment solution for end users
The Payment Service provides a fast and familiar purchase experience for your users. Using their BlackBerry
ID, users can apply various payment methods, including credit card, PayPal, and carrier billing, toward the
purchase of digital goods you defineall without leaving your app.
An easy way for you to keep track of your earnings
Digital goods in your app are described and priced according to the pricing tiers presented in the BlackBerry
World vendor portal. In the vendor portal, you can manage and track sales of your app and its digital goods so
you can keep track of how much you're earning.
Adding Features
233
Component
Description
Content server
Payment providers
Adding Features
234
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.
Adding Features
235
SKU
License type
Price
Renewal price
Adding Features
236
Learn more about submitting applications and digital goods on the BlackBerry World vendor portal.
Adding Features
237
If, however, you host your digital goods on a content server and deliver them to BlackBerry devices over the
wireless network, you can update and add to your offering of digital goods without having to submit a new
release of your application to the BlackBerry World storefront.
Your content server needs to respond to the Payment Service server with a license key, which is then passed to
the user's device as part of the purchase transaction.
Initiating a purchase
You can initiate a purchase in your app by calling the purchase method.
When a user starts a purchase transaction, the blackberry.payment.purchase function is called. When
the user finishes interacting with the device to engage the payment process, the app receives a response.
When the blackberry.payment.purchase function is called, only the ID or SKU of the digital good to be
purchased is required; you don't need to provide both. If you do provide both, the ID takes precedence.
function purchase() {
alert("Trying to call purchase");
blackberry.payment.developmentMode = true;
try {
blackberry.payment.purchase({
"digitalGoodID":
"16823864",
"digitalGoodSKU":
"BB10-CG-02",
"digitalGoodName":
"SomeName",
"metaData":
"metadata",
"purchaseAppName":
"WebWorks APP",
"purchaseAppIcon":
null,
Adding Features
238
"extraParameters":
{
"key1":
"value1",
"key2":
"value2"
}
}, onPurchaseSuccess,
onPurchaseError);
} catch (e) {
alert("Purchase exception");
console.log(e);
}
The Payment Service SDK for BlackBerry WebWorks includes metaData property. You can use this property
to provide extra information that remains associated with the purchased good. For example, if a book vendor
offers multiple titles at a single price point and represents them on the vendor portal as a single digital good,
when a book is purchased, the vendor could set the metaData value as the ISBN for that book. Then, if the
user checks past purchases, the metaData property can be used to differentiate between past book
purchases.
By default, users see the app name and the icon that you registered with BlackBerry World when they interact
with purchase dialog banners. If you want users to see a customized name and icon on the purchase dialog
banners when they purchase your app, you can set the purchaseAppName and purchaseAppIcon
properties.
Using the purchaseAppName and purchaseAppIcon properties can be a good solution if you offer digital
goods with a single name and price point. For example, if you sell additional levels of a game at a single price
point, you can use a generic digital good called "My game level" for all such levels. When a user makes a
purchase, the game app should override "My game level" with the name of the level that the user purchased
(using the purchaseAppName property). This approach makes sure that the user is aware of exactly what
they are purchasing on the purchase confirmation screen.
If you use the purchaseAppIcon property, you can supply an icon in any standard format set to ?
height=100for a 100 x 100 size.
<script type="text/javascript">
function purchase() {
try {
blackberry.payment.purchase({
"digitalGoodID":"123",
"digitalGoodSKU":"someSKU",
"digitalGoodName":"SomeName",
"metaData":"metadata",
"purchaseAppName":"WebWorks APP",
"purchaseAppIcon":null,
"extraParameters": {
"key1": "value1",
"key2": "value2"
}
},
onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
Adding Features
239
Responding to a purchase
When the purchase process completes, your app calls either onSuccess if the purchase is successful, or
onFailure if the purchase is not successful.
<script type="text/javascript">
function purchase() {
try {
blackberry.payment.purchase({
"digitalGoodID":"123",
"digitalGoodSKU":"someSKU",
"digitalGoodName":"SomeName",
"metaData":"metadata",
"purchaseAppName":"WebWorks APP",
"purchaseAppIcon":null,
"extraParameters": {
"key1": "value1",
"key2": "value2"
}
},
onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(purchasedItem) {
var transId = purchasedItem.transactionID;
var sku = purchasedItem.digitalGoodSKU;
var dgId = purchasedItem.digitalGoodID;
alert("Purchased Item: " + transId + "," + sku +
}
"," + dgId);
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Error responses for blackberry.payment.purchase
The paymentError object is returned as a parameter for callbackOnFailure if the purchase process is
unsuccessful. The paymentError object has two properties: Number errorID and an errorText string.
Number errorID
The error number returned as part of the paymentError object corresponds with a preset list of specific
error conditions, as follows:
-1 = an unexpected application error
Adding Features
240
String errorText
The paymentError object returns a text string that can display as a readable message for the user.
Adding Features
241
Managing a subscription
You can use the following functions in the Payment Service for BlackBerry WebWorks to manage subscriptions
in your app.
blackberry.payment.checkAppSubscription initiates a call to confirm that the user has rights to
the current app, offering an app-level subscription.
blackberry.payment.checkExisting initiates a call to confirm that the user has rights to a digital
goods subscription.
blackberry.payment.cancelSubscription initiates a request to cancel a subscription for a digital
good.
Subscriptions can be referred to as app-level subscriptions or digital goods-level subscriptions. When you add
your app to BlackBerry World you can select Subscription as the license type for your app. If you add a digital
good to your app, you can select Subscription as the license type for your in-app digital good.
Checking an app-level subscription
When a user tries to access an app-level subscription, the Payment Service calls
blackberry.payment.checkAppSubscription to verify that the user has rights to the subscription.
If the transaction is successful and the user's BlackBerry ID matches a currently active subscription to the
app, the Payment Service returns the onSuccess function with the parameter
data.subscriptionExists set to True. If no match is made, then data.subscriptionExists is set
to False.
If the transaction is not successfully completed, the Payment Service returns the onFailure function with a
PaymentError object.
<script type="text/javascript">
function checkAppSubscription() {
try {
blackberry.payment.checkAppSubscription(onSuccess, onFailure);
} catch (e){
alert("Error" + e);
}
}
function onSuccess(data) {
alert("User is " + (data.subscriptionExists ? "" : "not ") +
"subscribed to the app.");
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Checking a digital goods subscription
Adding Features
242
When a user tries to access a digital goods subscription, the Payment Service calls
blackberry.payment.checkExisting to verify that the user has rights to the subscription. The function
includes information to describe the digital good: id for the identifier assigned by BlackBerry World or sku for
the SKU of the digital good. If both arguments are included in the transaction, id takes precedence and sku is
ignored.
If the BlackBerry ID associated with the transaction is subscribed to the digital good, the Payment Service
returns the onSuccess function with the parameter data.subscriptionExists set to True. If the
transaction is successful, but no match is made, then data.subscriptionExists is set to False.
If the transaction is not successfully completed, the Payment Service returns the onFailure function with a
PaymentError object.
<script type="text/javascript">
function checkSubscription() {
try {
blackberry.payment.checkExisting({
"id": 12345"
}, onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(data) {
alert("User is " + (data.subscriptionExists ? "" : "not ") +
"subscribed to the item.");
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Canceling a subscription
A user can only cancel a subscription for a digital good; cancellation of other types of purchases (license types)
are not supported. A purchase ID is required in order to identify the subscription that a user wants to cancel, so
when a user makes a request to cancel a subscription, your app calls a getExistingPurchases function
first. A successful getExistingPurchases function returns the purchase ID so that the cancellation can
be completed.
If the blackberry.payment.cancelSubscription function is successful, the onSuccess function
returns data.subscriptionCancelled: True.
Note: If a user successfully cancels a subscription, the subscription remains valid until the end of the current
subscription period. For example, if the user has paid for a subscription to December 31st, and cancels the
subscription on December 15th, the subscription remains valid until the paid period expires on December
31st.
Adding Features
243
Adding Features
244
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.
3. Add digital goods to a new or existing app that has been added to the vendor portal.
4. Enable Development Mode on your device by navigating to Settings > Security and Privacy > Development
Mode and enabling the Use Development Mode toggle button.
Adding Features
245
5. Start BlackBerry World on your device and swipe down from the top bezel to display the application menu.
Tap Settings > Development Mode, then enter the ID or SKU of your app and tap Load to download your
app.
Note: This Development Mode screen, where you can enter the ID of your application and download it right
from your vendor account, will be visible only if your device is in Development Mode.
Here are some things to consider when you use the BlackBerry World vendor portal to test your in-app digital
goods:
Make sure the connection mode in your app is set to Production so that your test purchases go through the
BlackBerry World server.
Apps that are in draft can only be downloaded from BlackBerry World when you are using a sandbox user
account (any other kind of user account won't work).
You can only retrieve past purchases for the current test session. Digital goods that are purchased in a draft
status are not written to the transaction database, so when you end the test session the cache is cleared.
You can test purchasing an app only from a physical device, not from the BlackBerry 10 Device Simulator.
BlackBerry World has a cache, so there may be a delay before your new digital goods are accessible from
BlackBerry World on your device.
You can use a sandbox user account to purchase your own apps and digital goods that are approved and
for sale on the BlackBerry World storefront without being charged.
Adding Features
246
You don't need to remove an existing app from sale on the BlackBerry World storefront to add new digital
goods in draft status, and test them with a sandbox user account.
If you add a new app (meta data) and digital goods to the BlackBerry World vendor portal, you must also
add a release (application data) in order to test the download and purchase of the digital goods.
Push Service
You can use the Push Service to develop a push-enabled app that runs on a BlackBerry device and receives
push messages from a Push Initiator. The Push Initiator can deliver up to 8 KB of content (images, text, or
audio) to many devices at the same time.
To use the Push Service, you must register with BlackBerry. For more information about registering, visit Push
Service in the Platform Services documentation. If you're using the Push Service with BlackBerry Enterprise
Service 10 or later, you don't need to register with BlackBerry. For more information, see Push technology for
the enterprise.
Architecture
The architecture diagram below shows a complete Push Service solution that includes the server-side library
and the client-side library. The libraries work together to deliver content from the Push Initiator to a pushenabled app.
Adding Features
247
Push Initiator
The Push Initiator is the app that creates request messages using the server-side library and sends them
to the push proxy gateway (PPG).
Server-side library
You can use the Push Service SDK as the server-side library or you can provide your own library. If you
use the Push Service SDK, the server-side library provides the Java APIs that the Push Initiator uses to
interact with the PPG. For information about developing a Push Initiator using the Push Service SDK, see
the Push Service SDK documentation.
Push Proxy Gateway
The PPG processes push request messages that it receives from the Push Initiator. After the PPG
processes a push request message, it sends a response message that communicates the overall result of
the push message. The response message contains a result code or a PAP error code.
Client-side library
The BlackBerry 10 WebWorks SDK contains the client-side library. The client-side library provides the
Qt-based APIs that the push-enabled app uses to create a PushService object, create and destroy a
channel, and receive push messages.
Push-enabled app
The push-enabled app runs on a device and acknowledges the push request to the PPG. The pushenabled app uses the client-side library to create a PushService object, create and destroy a channel,
and receive push messages.
248
The Push Service minimizes the impact on device batteries because the push-enabled app listens in the
background for the Push Initiator to send content to it. The app doesn't need to poll the push server for
content.
Less coding
The Push Service SDK minimizes the amount of code that you need to write to create a Push Service
solution. You can use the APIs in the server-side and client-side libraries to perform common tasks.
Client-side app
A client-side push-enabled app runs on a device and communicates, through the Push Service, with a serverside app, called a Push Initiator. Before you develop your own push-enabled app, you may find it helpful to try
out the Push Capture sample app available on github.
Prerequisites
To develop and test a push-enabled app, you need the following:
Item
Requirement
Push Initiator
To test your push-enabled app, you need a Push Initiator. To develop the
Push Initiator, you can use our Push Service SDK or another library of your
choice. The Push Service SDK includes two sample Push Initiators that you
may be able to use to test your push-enabled app.
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 device
249
Adding a plugin copies the plugin to your project's plugins folder, and makes the APIs available to your app. It
also adds the required <feature> element to your app's config.xml file. After you add a plugin, the contents
of the plugin are packaged together with your other app resources the next time you build your app. You can
add the plugins from the command line or with the SDK web tool.
To add the plugins from the command line:
1. Open a command line in your app's project folder.
2. Run the following commands:
webworks plugin add com.blackberry.push
webworks plugin add com.blackberry.invoked
To add the plugins using the SDK web tool:
1. With your project open in the SDK web tool, in the navigation panel, click Plugins.
2. In the Plugin Name or URL field, type com.blackberry.push, then click Add plugin
3. Repeat the above step for the com.blackberry.invoked plugin.
Adding Features
250
2. To allow your app to be opened from BlackBerry Hub notifications, add the following statements.
<!-- config.xml -->
<!-- Have an invoke entry here for when a notification is clicked
<!-- on in the BlackBerry Hub. This will cause the app
<!-- to be opened -->
<rim:invoke-target id="sample.pushcapture.invoke.open">
<type>app</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>text/plain</mime-type>
</filter>
</rim:invoke-target>
Note that the action tag is set to bb.action.OPEN. This value indicates that the invocation relates to
an open invoke event. In the sample app, an open invoke event occurs when a user taps a notification for a
push message in the BlackBerry Hub. The event listener in the sample app also uses this value to check
that the invoke event is an open invoke event. For more information about the event listener and the open
invoke event, see Handling notifications in the BlackBerry Hub.
Call PushService.create()
The static PushService.create() function instantiates a PushService object. If the object is created
successfully, the create function calls the successCreatePushService() callback function with the
PushService object that the app can use. If the object isn't created, the create function calls the
failCreatePushService() callback function with a result number value. The result corresponds to
one of the error constants provided in the PushService class. For more information about the error
constants, see the PushService class in the API Reference.
Adding Features
251
The call to PushService.create() is different depending on whether or not the Push Service is used with
the BlackBerry Enterprise Service. If the Push Service is not used with the BlackBerry Enterprise Service, the
create function call looks like this:
var ops;
if (sample.pushcapture.usingpublicppg) {
// Consumer app using public push
ops = { invokeTargetId : sample.pushcapture.invokeTargetIdPush,
appId : sample.pushcapture.appid,
ppgUrl : sample.pushcapture.ppgurl
};
} else {
// Enterprise app using enterprise push
}
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
If the Push Service is used with the BlackBerry Enterprise Service, the create function call looks like this:
var ops;
if (sample.pushcapture.usingpublicppg) {
// Consumer app using public push
} else {
// Enterprise app using enterprise push
if (sample.pushcapture.usesdkaspi) {
// If we're using the Push Service SDK for our Push
// Initiator implementation, we will have specified
// our own application ID to use.
ops = { invokeTargetId :
sample.pushcapture.invokeTargetIdPush,
appId : sample.pushcapture.appid
};
} else {
ops = { invokeTargetId :
sample.pushcapture.invokeTargetIdPush };
}
}
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
Adding Features
252
Call successCreatePushService()
The successCreatePushService() callback function stores the PushService object in a global
variable. The app can use the global variable to make calls to the other functions of the PushService class
without having to call PushService.create() again.
PushCapture.prototype.successCreatePushService = function(service) {
};
Call failCreatePushService()
The failCreatePushService() callback function shows the error handling if the PushService object
isn't created, and the error messages that you can use for debugging. In your app, you might want to handle
the errors differently. For example, you might want to retry an operation first before displaying an error
message. The API Reference lists the possible actions that you can take for each error constant. The API
Reference also tells you which error codes apply to which function calls.
PushCapture.prototype.failCreatePushService = function(result) {
// ...
if (result == blackberry.push.PushService.INTERNAL_ERROR) {
alert("Error: An internal error occurred while calling " +
"blackberry.push.PushService.create. Try restarting the
app.");
} else if (result == blackberry.push.PushService.
INVALID_PROVIDER_APPLICATION_ID) {
// This error only applies to consumer apps that use
// a public/BIS PPG
alert("Error: Called blackberry.push.PushService.create with
a missing " + "or invalid appId value. It usually means a
programming error.");
} else if (result == blackberry.push.PushService.
MISSING_INVOKE_TARGET_ID) {
alert("Error: Called blackberry.push.PushService.create with
a missing " + "invokeTargetId value. It usually means a
programming error.");
} else if (result ==
blackberry.push.PushService.SESSION_ALREADY_EXISTS) {
alert("Error: Called blackberry.push.PushService.create with an
appId or " + "invokeTargetId value that matches another
app. It usually means a " + "programming error.");
} else {
alert("Error: Received error code (" + result + ") after " +
"calling blackberry.push.PushService.create.");
Adding Features
253
};
Adding Features
254
After you type the username and password, and tap Submit, the sample app tries to create a channel.
If you're not subscribing with the Push Service SDK, you don't need to provide a username and password. You
can simply tap Register and Submit, and the sample app tries to create a channel.
Call createChannel()
The sample app calls createChannel() to create a channel to the PPG. The createChannel() function
includes the createChannelCallback callback function as an argument. If the channel creation is
successful, createChannelCallback returns a token that isn't null. The token represents the device and
the app that receives push messages. You need to communicate the token to the Push Initiator so that the
Push Initiator can use the token to send push messages to the app. If the channel creation fails, the token is
null, and you should ignore it.
sample.pushcapture.pushService.createChannel(
sample.pushcapture.createChannelCallback);
The createChannelCallback callback function shows the error handling if the create channel operation
fails. In your app, you might want to handle the errors differently. For example, you might want to retry an
operation first before displaying an error message. The API Reference lists the possible actions that you can
take for each error constant. The API Reference also shows which error codes apply to which function calls.
sample.pushcapture.constructor.prototype.createChannelCallback =
function(result, token) {
if (result == blackberry.push.PushService.SUCCESS) {
// Success! Communicate the token to the Push Initiator.
} else {
Adding Features
255
};
// Error handling
Call subscribeToPushInitiator()
If the channel creation is successful, and you're subscribing with the Push Service SDK, the sample app calls
subscribeToPushInitiator() to subscribe with the Push Initiator. The subscribe function passes in the
token to the Push Initiator and the username and password that you typed on the Register screen. If you're not
subscribing with the Push Service SDK, the sample app doesn't call subscribeToPushInitiator().
sample.pushcapture.constructor.prototype.subscribeToPushInitiator =
function(token) {
document.getElementById("progressinfo").innerHTML
= "Subscribing to Push Initiator...";
var type;
if (sample.pushcapture.usingpublicppg) {
type = "public";
} else {
type = "bds";
}
var
var
var
var
var
username = document.getElementById("reguserid").value.trim();
password = document.getElementById("regpwd").value.trim();
address = token;
osversion = blackberry.system.softwareVersion;
model = blackberry.system.hardwareId;
256
};
};
xmlHttp.send();
};
sample.pushcapture.pushNotificationHandler(pushPayload);
} else if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.OPEN") {
// Do something
}
The push message is stored in the data field of the PushPayload object. The type of the data field is Blob.
You need to convert the push message from a Blob object to a format that you can work with. The API
Reference shows you how to convert the Blob object to binary data and plain text.
You should also look at the sample.pushcapture.pushNotificationHandler() function in the
sample app code for examples of how to check for duplicate push messages, how to store push messages in
the database, and how to convert the Blob object to plain text and Base64 encoded strings for binary data.
Adding Features
257
258
259
When a user taps on a notification in the BlackBerry Hub, the sample app receives an open invoke event,
and displays the push message that corresponds to the notification.
When the sample app receives a push message, it adds a notification to the BlackBerry Hub.
When a user taps on the push message in the sample app, the app removes the notification from the
BlackBerry Hub.
When a user deletes an individual push message in the sample app, the app removes the notification for
the push message from the BlackBerry Hub.
When a user taps Mark All Open or Delete All in the sample app, the app removes all the notifications for
the sample app from the BlackBerry Hub.
260
};
} else {
// The home screen has not loaded up yet. We need to wait
// until it loads before we can open the push, so we do it
// after the pushes are displayed by the call to
// initPushList() in pushlist.js.
sample.pushcapture.isOpenInvoke = true;
sample.pushcapture.selectedPushSeqnum = payload;
}
Adding Features
261
After you tap Submit, the sample app tries to destroy the channel.
If you're not subscribing with the Push Service SDK as the Push Initiator, you don't need to provide a username
and password. You can tap Unregister and Submit, and the sample app tries to destroy the channel.
Call destroyChannel()
The sample app calls destroyChannel() to destroy the channel to the PPG. The destroyChannel()
function includes the destroyChannelCallback callback function as an argument.
sample.pushcapture.pushService.destroyChannel(
sample.pushcapture.destroyChannelCallback);
The destroyChannelCallback callback function shows the error handling if the destroy channel
operation fails. In your app, you might want to handle the errors differently. For example, you might want to
retry an operation first before displaying an error message. The API Reference lists the possible actions that
Adding Features
262
you can take for each error constant. The API Reference also shows which error codes apply to which function
calls.
sample.pushcapture.constructor.prototype.destroyChannelCallback =
function(result) {
if (result == blackberry.push.PushService.SUCCESS ||
result == blackberry.push.PushService.
CHANNEL_ALREADY_DESTROYED ||
result == blackberry.push.PushService.
CHANNEL_ALREADY_DESTROYED_BY_PROVIDER ||
result == blackberry.push.PushService.
CHANNEL_SUSPENDED_BY_PROVIDER ||
result == blackberry.push.PushService.
PPG_SUBSCRIBER_NOT_FOUND ||
result == blackberry.push.PushService.
CREATE_CHANNEL_NOT_DONE) {
// Success!
} else {
.
.
.
// Error handling
}
};
Call unsubscribeFromPushInitiator()
If the destroy channel operation is successful, and you're subscribing with the Push Service SDK, the sample
app calls unsubscribeFromPushInitiator() to unsubscribe from the Push Initiator. The unsubscribe
function passes in the username and password that you typed on the Unregister screen. If you're not
subscribing with the Push Service SDK, the sample app doesn't call
unsubscribeFromPushInitiator().
sample.pushcapture.constructor.prototype.unsubscribeFromPushInitiator
= function() {
document.getElementById("progressinfo").innerHTML = "Unsubscribing
from Push Initiator...";
var username = document.getElementById("unreguserid").value.trim();
var password = document.getElementById("unregpwd").value.trim();
var params = "appid=" + encodeURIComponent(sample.pushcapture.appid)
+ "&";
params += "username=" + encodeURIComponent(username) + "&";
params += "password=" + encodeURIComponent(password);
var unsubscribeUrl = sample.pushcapture.piurl + "/unsubscribe?"
+ params;
var xmlHttp = new XMLHttpRequest();
Adding Features
263
xmlHttp.open("GET", unsubscribeUrl);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var status = xmlHttp.status;
var returnCode = xmlHttp.responseText;
};
};
sample.pushcapture.pushInitiatorUnsubscribeHandler(status,
returnCode);
xmlHttp.send();
Removes the user and all the push messages associated with the user from the database.
Removes notifications in the BlackBerry Hub that are associated with the user.
Unsubscribes the user from the Push Initiator if the user chose to subscribe with the Push Service SDK.
Displays a message indicating that the SIM card has changed.
Displays the Register screen so that a new user, or the same user with a new SIM card, can register.
Adding Features
264
Call onPushTransportReady()
To handle the push transport error and PPG server error, the sample app specifies an
onPushTransportReady() callback in its call to the static PushService.create function so that the
app can try to create or destroy the channel again.
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
Adding Features
265
alert(message);
The sample app handles these errors by explicitly telling the user about the errors. In your app, you could
handle the errors the same way, or your onPushTransportReady callback could check which operation
failed, and then try the operation again without telling the user about the errors.
Adding Features
266
Frameworks
Find out more about the community frameworks that you can use in your WebWorks apps.
jQuery
If you want to use jQuery or jQuery Mobile in your BlackBerry WebWorks app, you might find the information in
this section helpful.
What is jQuery?
jQuery is a JavaScript library that simplifies many complex actions, such as DOM manipulation and web service
calls, using JSON or AJAX. When you use jQuery, you can minimize the amount of code you write, reduce
development cycles, and simplify the maintenance of your application.
To find out more about jQuery, visit the official jQuery website.
It's important to remember that since jQuery is built on top of JavaScript, the functionality of your code on a
given platform depends on the platform's support of JavaScript. If you already have a desktop web application
that uses jQuery, there is a very good chance that currently existing as well as future desktop and mobile
platforms will simply run your code.
You can use jQuery for commercial application development. To use jQuery in commercial projects, view the
jQuery license.
Frameworks
267
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.
268
applications. This includes the jQuery Mobile framework. The jQuery Mobile framework does not provide any
BlackBerry specific look and feel either. There are two options to address this.
One option is from an open-source project that is integrated with jQuery Mobile to provide a BlackBerry 10 look
and feel to your BlackBerry WebWorks apps. For more information, visit the GitHub repository for the jQuery
Mobile BlackBerry 10 theme.
The other option is to use the bbUI.js framework. It is a UI framework that is designed specifically for the
BlackBerry platform with a focus on BlackBerry 10. This framework makes a number of optimizations to
increase performance and reduce the memory footprint. Similar to using the jQuery Mobile framework, to use
the bbUI.js framework you set <div> attributes to identify components that the bbUI.js framework then
replaces to turn the components into compelling controls. For more information, visit the GitHub repository for
the bbUI.js framework.
.
Debugging
Eventually, you're bound to run into issues. With some luck, the problem is simply a missing semicolon. Other
times, you might come across something that's really broken. Here are some ways to more easily solve your
problem.
JavaScript validation
Before you run your code, you should be fairly confident that it will run. JSLint is a great tool for validating code.
Depending on which HTML or text editor you're using, there is likely a JSLint plug-in that you can leverage as
well. Running JSLint will pick out the most common errors for you, including syntax or formatting.
Web Inspector
If you have developed a web application for desktop computers, chances are you've come across some form of
Web Inspector tool to let you examine the source code as it runs. This functionality is also available for
BlackBerry WebWorks applications. See Debugging using Web Inspector on page 292 for details on using Web
Inspector.
Reporting bugs
If you find a bug, you can report it at the appropriate site below:
jQuery Core
BlackBerry WebWorks APIs
If you have feedback regarding your experience with BlackBerry WebWorks and jQuery, visit the Web and
WebWorks Development forums to share your insight or see what others are saying.
Resources
Here are some resources that can help you with your jQuery application:
Frameworks
269
BlackBerry WebWorks
Common BlackBerry WebWorks development pitfalls that can be avoided
Code signing
Set up your computer for testing and signing
Building and signing your completed app
Debugging
JSLint
Debugging using Web Inspector on page 292
GitHub repositories
blackberry/WebWorks-Samples - Sample BlackBerry WebWorks applications
Other resources
BlackBerry World
Sencha Touch 2
Sencha Touch 2 is a widget library for creating web apps for mobile devices. It contains widgets (also known as
components) that enable you to create web apps for mobile devices with the look and feel of native mobile
apps. It is based entirely on web standards such as HTML5, JavaScript, and CSS3.
Tab panels
Nested lists
Navigation views
Form controls
Carousels
Cards
270
Offline capabilities: APIs are available to provide offline data storage functionality that is based on HTML5
local storage and session storage mechanisms.
AJAX support: Full AJAX support, including CORS and JASON-P.
DOM support: Support for manipulating HTML and XML using the DOM-related methods.
Feature detection: Automatic detection of features such as geolocation, canvas, and orientation.
Touch events: Support for a full range of touch events and gestures such as tap, swipe, and pinch.
Further reading
Getting started with Sencha Touch
Features of Sencha Touch
Frameworks
271
Dojo Toolkit
Overview
The Dojo Toolkit is a JavaScript toolkit for creating cross-platform JavaScript/AJAX applications. It contains a
rich collection of lightweight and independent modules. The toolkit enables you to use its lightweight solution
for DOM manipulation and AJAX services by allowing you to choose only the modules you need for your
application. It also allows you to create complex JavaScript classes with multiple inheritance.
Date/time picker
Accordion views
Pop up menu with icons
TabBar views
Image/content carousel
Transition effects
Dijit package
You can also add functionality from the Dijit package. The Dijit package includes an extensive library of UI
controls and other useful widgets that are not available in the Dojo Mobile module, such as a color palette or a
calendar. While the widgets in Dojo Mobile are specifically tailored for mobile devices, you might still want to
explore the widgets available in Dijit. As of version 1.8, most widgets in Dijit support mobile device events such
as touch and gesture events.
Frameworks
272
Note: There are plenty of GUI widgets in the DojoX package and there are other packages, such as dgrid
( http://dgrid.io/ ), which offer a high-performance grid that works on mobile and desktop browsers.
Frameworks
273
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).
Further reading
Getting Started with dojox/mobile: http://dojotoolkit.org/documentation/tutorials/1.8/mobile/tweetview/
getting_started/
Modern Dojo syntax: http://dojotoolkit.org/documentation/tutorials/1.8/modern_dojo/
DOM and event handling: http://dojotoolkit.org/documentation/tutorials/1.8/events/
Frameworks
274
Enyo 2.0
Overview
Enyo 2.0 is a free and open source JavaScript framework for building cross-platform web apps. You can use
Enyo 2.0 to build apps for the BlackBerry platform. If you already have an Enyo 2.0 based app, you can port it
to the BlackBerry platform.
Frameworks
275
Further reading
Enyo Bootplate
Onyx UI library
Frameworks
276
Layout library
Creating a new BlackBerry WebWorks project. For more information, see Creating a WebWorks project.
Placing your app source files in the /www folder of your new project.
Generating an unsigned .bar file for testing. For more information, see Building your app for testing.
Generating a signed .bar file containing your complete project. For more information, see Building and
signing your complete app.
To complete this task, you must have the BlackBerry 10 WebWorks SDK installed on your computer. You can
download the SDK from the Downloads page.
Construct 2
Construct 2 includes an Export Project wizard that allows you to export your project to BlackBerry 10. The
export process creates an HTML5 version of your game's project files. You can use the BlackBerry 10
WebWorks SDK to package those files into a BlackBerry 10 WebWorks app.
Before you attempt to export your Construct 2 game into a BlackBerry 10 app, you need to complete the
following steps:
Download and install the BlackBerry 10 WebWorks SDK.
Set up your computer for testing and signing by creating your BlackBerry ID token and then creating your
developer certificate.
Once you have the WebWorks SDK installed and your signing token in place, you can create a WebWorks
project, then export your Construct 2 project assets into that project.
Frameworks
277
4. Enter C:\TestApps in the Project Path field. This folder is the root folder for your WebWorks project,
represented by <project-root> later in this tutorial.
5. Click Save. The tool creates a pre-populated WebWorks sample project.
Leave the SDK web tool open for now. You'll return to it once you have added your Construct 2 project
assets to the WebWorks project.
6. On the command line or in a file manager, navigate to <project-root>\www folder and delete the entire
contents of the folder, including all subfolders. You can now populate your WebWorks project with the
Construct 2 content.
4. On the HTML5 export options screen, select Embed Style to export the content with no margins and no
scroll bar. This format is the most suitable for a BlackBerry WebWorks app.
5. On the HTML5 export options screen, click Export.
The following window appears:
Frameworks
278
6. Copy the files from the export folder to the <project-root>\www folder in your WebWorks project.
Description
App ID
App Name
The name of your proeject. This name identifies your app on the
device Home screen.
Frameworks
279
Preference
Description
App Description
Author
To learn more about the other configuration settings available, see Configuring your app preferences on
page 56.
4. Click Save. You can now test your Construct 2 app on a device or simulator.
3.
4.
5.
6.
7.
8.
9.
Note: If you have not yet requested your BlackBerry ID token, see set up your computer for testing and
signing.
10.Click Build & Install. After creating and installing a debug token, if necessary, the tool builds, installs, and
launches the app.
Frameworks
280
Best practices
In Construct 2, you can modify the viewport fairly easily to create games for specific BlackBerry 10 devices. For
more information on designing for different screen sizes, you can reference the screen size chart in the UI
guidelines.
BlackBerry 10 supports both WebGL and 2D Context for rendering, so you can choose which one you prefer to
use. You can also export your game for each API separately, so it can be deployed on a wider range of
operating systems.
bbUI toolkit
The bbUI toolkit is an open source JavaScript toolkit that allows you to give your BlackBerry WebWorks
applications the look and feel of a native BlackBerry application.
The bbUI toolkit was created to provide a design language for HTML5 applications using the BlackBerry
WebWorks framework. It provides common UI constructs that are found on the BlackBerry platform so that
you can create an application that follows BlackBerry specific UI guidelines and looks at home on a BlackBerry
device with very little effort.
The bbUI toolkit supports all BlackBerry platforms from BlackBerry Device Software 5.0 through to BlackBerry
7, as well as BlackBerry PlayBook OS and BlackBerry 10. In each case, the toolkit uses CSS that achieves a
similar user experience to the native applications on the platform, and tailors it to suit the capabilities of the
device.
Frameworks
281
Further reading
To learn more about the specific implementation details and functionality of the bbUI toolkit, refer to the bbUI
toolkit project in GitHub. This project site contains overview information, samples, and an extensive wiki that
provides in-depth documentation on how the toolkit is used.
Some useful links include:
Application structure
config.xml requirements
Toolkit initialization
Data attribute reference
bbUI screens and UI components reference
Frameworks
282
283
[-
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>
<ip-address>
-t device | simulator
-p <password>
--pin <device-pin>
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>
284
On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.
Navigate to Settings > About.
In the Category drop-down list, click Network.
Under the Wi-Fi heading, note the value under IPv4. This is the IP address you should be supplying when
setting up the device as a test target.
Note: To view the Wi-Fi section on the Network Settings page, you must have Wi-Fi turned on, and the
device must be connected to the Wi-Fi network.
285
286
4. Click Build.
The tool packages your app into a .bar file, and places the unsigned copy of the .bar file in the following
location: <your_app_project_directory>\platforms\blackberry10\build\device.
Description
--debug
-p|--params <JSON-file>
-l|--loglevel <level>
287
288
Parameters
Description
--devicepass <password>
--target <target_id>
--no-build
--no-launch
289
1. Open BlackBerry WebWorks <version>. A new browser window opens, displaying the BlackBerry 10
WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. From the Install Target drop down list, select one of the following:
To deploy to a device connected via USB, select Autodetect.
To deploy to a device over Wi-Fi, select appropriate device target from the list.
5. Enter your device password.
6. Enter your keystore password, which you defined when you requested your BlackBerry ID token. If you have
not yet requested your BlackBerry ID token, see set up your computer for testing and signing.
7. Click Build & Install.
The tool packages your app into a .bar file, installs it on your device, and then opens it. If a .bar file with the
same name exists on the device, the SDK first uninstalls the existing .bar file before deploying the new .bar file.
If a valid debug token is not already present on the device, the tool creates and installs the debug token for you
before installing and opening the app. For more information about debug tokens, see Signing and debugging:
Frequently Asked Questions on page 16.
If you don't supply a device or keystore password, or supply an incorrect password, the SDK prompts you to
enter the correct password before continuing the deployment process.
290
If successful, the run command launches the app on the device. It also places a copy of the unsigned .bar
file in the following location: <your_app_project_directory>\platforms\blackberry10\build\device.
For example, the following sample will deploy the app on the default target device, as well as create and install
a debug token, if one does not already exist on the device. If the app has already been deployed to the default
target, it uninstalls the previous version before installing the new version.
webworks run --keystorepass mypass
All parameters are optional. Check the table below for parameter details:
Parameters
Description
--devicepass <password>
--target <target_id>
-k | --keystorepass <keystore_pw>
--no-build
--no-launch
291
292
To enable Web Inspector in a signed app, you must build your app from the command line (using webworks
build --release command), and include the --web-inspector flag in the command. See Building and
signing your completed app on page 316 for more information.
Note: You should enable Web Inspector for signed apps sparingly. Leaving the debugging port open may allow
unintentional access to your application.
When you load a Web Inspector enabled BlackBerry WebWorks application on a BlackBerry device or
simulator and run it, a dialog appears that provides the IP address and the port number required to connect
from your desktop browser.
293
Verify that your computer has the Google Chrome desktop browser installed.
Verify that development mode is enabled on your device or simulator.
Once you have enabled Web Inspector in your BlackBerry WebWorks app or in the BlackBerry Browser, you
can remotely connect to your BlackBerry device or simulator to inspect and modify the content.
1. On your computer, open Google Chrome.
2. In the address bar, type the IP address of the BlackBerry device or simulator, and specify the port number
used by the app serving the content. The port number is displayed when you open a BlackBerry WebWorks
app that is Web Inspector enabled, or when you first enable Web Inspector in the BlackBerry Browser.
Typically, port numbers are assigned starting at 1337, and increase sequentially for each additional
WebWorks app or browser tab that you choose to inspect. For example:
http://<IP_address>:<port_number>
A list of one or more links is displayed in your browser, representing the webpage currently displayed in
each of the tabs open in the BlackBerry Browser.
3. Click any of the available links to view the content in Web Inspector.
On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.
Navigate to Settings > About.
In the Category drop-down list, click Network.
Under the Wi-Fi heading, note the value under IPv4. This is the IP address you should be supplying when
setting up the device as a test target.
Note: To view the Wi-Fi section on the Network Settings page, you must have Wi-Fi turned on, and the
device must be connected to the Wi-Fi network.
294
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.
295
Panel
Icon
Description
Timeline
The Timeline panel allows you to view how much time it takes for the browser to
load and render the webpage and its resources.
Profiles
The Profiles panel allows you to examine how your JavaScript code is utilizing
memory. With the Profiles panel, you can determine where programmatic
inefficiencies exist.
Audits
The Audits panel allows you to examine the network utilization and webpage
performance and suggests areas where performance can be improved.
Console
The Console panel provides a command-line driven utility that allows you to debug
JavaScript errors or HTML parsing errors.
296
The Elements panel is divided into two sections. On the left is the document pane, which displays the DOM
tree of the HTML source document. Each element is displayed as a separate node. You can expand the nodes
of the DOM tree to view the children of a container element. The document pane of the Elements panel is a
good tool to use to view the source of a page; because the panel displays the page as a tree, the document is
easy to view and to navigate, even when the original webpage is minified or poorly formatted and difficult to
read. Within the document pane, you can edit aspects of the DOM, such as attribute values or text.
On the right is a set of collapsible panes which display various pieces of information related to the element
currently selected in the document pane. Some of these panes, such as the Computed Style pane and the
Event Listeners pane, are informative; you use them simply to track information about the element. Other
panes are editable, and allow you to change the styles or properties associated with the selected element. You
can edit content in the following panes:
Styles: The Styles pane is divided into sections which show each matched CSS rule, and the associated
style declarations. It also displays style values that have been inherited. Inherited values that have been
overwritten by other style declarations are displayed with strikethough text.
Metrics: The Metrics pane provides a visual representation of the box model, which you can edit to
optimize the layout of a container element on the screen. The box model refers to the amount of space a
container element occupies in a rendered webpage. You can apply styles such as margins, borders, and
padding to an element to adjust the size of the content block and improve the page layout.
Properties: The Properties pane allows you to view the page as it is viewed by JavaScript code, as a
collection of DOM objects with associated property values. Although some of the property values are
editable, in most cases, it is easier to edit style values in the Styles pane.
297
298
The Resources panel displays a complete list of the resources that the WebKit engine must request and load to
render the webpage, as well as any client-side resources created and used by the web page. You can also use
the Resources panel to view the content of any resource file. Resources are organized in the panel into the
following categories:
Frames: Contains the resources for each frame displayed in the content, including images, fonts, scripts,
stylesheets, and other content resources, such as embedded video or Flash files. Subframes within the
main window are displayed as subfolders beneath the main Frames folder.
Databases: Contains all the database tables that are associated with your content or app.
Local Storage: Contains all Local Storage objects, that is, storage objects which persist after a browser
session has ended.
Session Storage: Contains all Session Storage objects, that is, storage objects which are only valid for the
current browser session.
Cookies: Contains all the cookies associated with the webpage or app.
Application Cache: Contains the resources included in the manifest of an offline web application.
299
2. In the list in the left pane of the Resources panel, double-click a category to show the resources and
subgroups. Continue to drill down until you locate the resource you are interested in viewing.
3. Double-click the resource in the left pane. The right pane displays the contents of that resource. For
example, selecting an image resource displays the image itself, as well as the file size and URL of the image
file. Selecting a script or style sheet displays the content of that script or style sheet.
300
By default, the table lists each of the requested resources in the order in which they were requested, and
charts the network activity as a waterfall timeline, with resources color-coded by type.
The waterfall timeline plots resources by the total time required to load the resource, from the initial request to
the completion of the download. The pale segment of the resource bar in the chart represents the total latency,
that is, the time the browser engine must wait from the moment it initially makes the request to the moment it
receives the first packet of data for the resource. Two vertical lines on the chart provide mark key page load
milestones:
The blue line indicates the time at which parsing of the content is complete and the DOMContent event
fires.
The red line indicates the time at which all the resources have been loaded and the load event fires.
You can customize how the content is displayed in the Network panel; resources can be filtered based on type
or sorted by any of the table headings, and the chart can be reformatted to highlight different time measures.
301
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.
302
The Sources panel is divided into two sections. On the left is the document pane, which allows you to view and
debug JavaScript. On the right is a set of collapsible panes which display information related to the displayed
script.
A toolbar at the top of the Sources panel allows you to choose the script file you want to inspect and to cycle
between open scripts. It also provides a set of controls that allow you to step through the script displayed in the
document pane.
303
To remove a breakpoint, locate and click the breakpoint marker in the line gutter of the document pane.
The marker no longer appears in the line gutter, and the breakpoint is removed from the Breakpoints
pane.
304
All browser engine activity pauses when the device or simulator screen is locked, or the BlackBerry Browser or
BlackBerry WebWorks application that you are inspecting is minimized.To record any activity, the BlackBerry
Browser or BlackBerry WebWorks application must be the active application, and the device or simulator
screen must not be locked.
The Timeline panel is divided into two panes.
In the top pane, the Timeline panel allows you select which timeline view you want to display. You can choose
three views:
Events: Displays the time it takes for the browser engine to complete each of the events required to
completely load the content.
Frames: Displays the browser engine activity for each screen refresh.
Memory: Displays memory consumption over time.
In the lower pane, the Timeline panel displays a waterfall timeline for the timespan that was selected in the top
pane. The data in the timeline is determined by which mode you select in the top pane of the Timelines panel.
305
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.
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.
306
Hover over a paint record to see the affected region of the screen by overlaying the area with a transparent
blue rectangle.
307
308
) to nest asynchronous events. Click the button again to turn nesting off.
309
310
The profile results indicate the amount of time the browser engine spent executing each function during the
recording process, as well as the number of times each function was called. An excessive amount of time
spent in any one function can indicate that there is an issue.
5. To sort the data, perform any of the following actions:
To sort the data by values in any column, double-click the column heading.
To display calls based on greatest impact on all exceptions or where they occurred in the call stack, in
the status bar at the bottom of the panel, toggle between Heavy (Bottom Up) and Tree (Top down).
To specify whether values are presented as a time value or as a percentage of the total CPU usage
required to process all the functions, toggle the percent button
(
) on or off.
To view a single function, select the call in the table and click the focus button
(
).
To exclude a single function from the data, select the function in the table and click the exclude button
(
).
Building and Testing
311
To reload the original profile after focusing on or excluding a function, click the reload button
(
).
The profile results indicate the amount of time the browser engine spent matching each selector in the
associated stylesheets, as well as the total number of times the browser engine found a match for the
selector.
5. To specify whether the value of the Total column is presented as a time value or as a percentage of the total
time required to process the CSS, toggle the percent button
(
) on or off.
Building and Testing
312
The Audits panel provides a few options; you can choose to audit network utilization, page performance, or
both. You can also choose to run the audit against the static page, or reload the page and run the audit as the
page loads.
Once you have run an audit, Web Inspector adds the report to the list at the left of the panel and displays the
results in the main pane. The audit results suggest improvements you can make to your webpage to increase
efficiencies.
Building and Testing
313
314
3. Pass the last evaluated expression property ($_) to the inspect() function.
To learn more about the Console, and view the Console and Command Line API reference guides, visit Chrome
Developer Tools Guide.
315
You can overwrite an app that your administrator pushes, but if the "Development Mode Access to Work
Space" IT policy rule is disabled, your app is removed and isnt reinstalled.
If your device is activated with BlackBerry Enterprise Service 12 (BES12):
The "Restrict development mode" IT policy rule must not be selected.
The "Allow development mode access to work space" IT policy rule must be selected.
If the "Allow development mode access to work space" IT policy rule is disabled, apps that you
previously tested in the work space are removed.
You can overwrite an app that your administrator pushes, but if the "Allow development mode access to
work space" IT policy rule is disabled, your app is removed and isnt reinstalled.
316
Description
--release
317
Parameters
Description
-d, --web-inspector
"blackberry-signer": {
"-proxyhost": "host",
"-proxyport": "port",
"-proxyusername": "user
name",
"-proxypassword": "password"
}
}
318
Parameters
Description
When you execute the build command and include
the --params params.json, the proxy settings
specified in the file are passed to the blackberrysigner command, enabling the command to
communicate with the BlackBerry Signing Authority
to sign your app.
319
Parameters
Description
--release
-d, --web-inspector
"blackberry-signer": {
"-proxyhost": "host",
"-proxyport": "port",
"-proxyusername": "user
320
Parameters
Description
name",
}
"-proxypassword": "password"
321
322
Best Practices
Learn about the best practices for developing web apps for the BlackBerry device.
When you follow best practices, you can improve the performance of your app and make it easier to debug and
maintain.
UI guidelines
Personally identifiable information
Note: The following best practices are based on the BlackBerry Guidelines for Personally Identifiable
Information, published on February 7, 2014. For information about what PII is, and what your responsibilities
as an app developer are, see the Guidelines.
A primary privacy concern for most mobile customers is what happens to information that personally identifies
them, commonly called personally identifiable information (PII). When handling customers PII, BlackBerry
recommends app developers use the following best practices:
Use the principle of least permissions. Only collect, use, or disclose personal information for purposes that
are reasonable. Likewise, only request the permissions your app reasonably needs to perform its intended
functions. Do not request or require permissions that your app can function without, and always explain why
you are seeking the permissions requested.
Consider the impact of third-party code. If your app includes third-party code, understand how it works,
the functionality it provides, and if or how it handles customers information. Ensure that appropriate
contracts are in place with any third-party service that you use. Consider how SDKs and third-party add-ins
affect your app. For example, a third-party ad service might access and use PII that your app would not
otherwise access.
Get consent and implement a privacy policy. If your app processes PII, you should have a publicly available
privacy policy that complies with applicable law and explains what you do with information you gather.
Ensure that your privacy policy is easily available and understandable to users. If you use unexpected practices
or process sensitive information, be explicit about your practices and the reasons for them when obtaining
consent from users.
Be accountable. Understand where your app is being sold and what legal privacy protection is in place for
users in those locations. Ensure your app and its policies comply with all applicable laws. Be aware that
data collected about minors or children can require additional special protection depending on the particular
jurisdiction in which the app is sold.
Best Practices
323
Be transparent. Build trust with your customers by explaining clearly and simply how your app works, what
data it collects, and what it does with that data. The explanation should include information about whether
the information is sent off the device to remote servers. Consider options to explain these aspects, such as a
separate link to how the app works or a special notice page in the app.
Secure your customers data. If the app collects, accesses, stores, or sends data to an external server,
always safeguard that data. Use encryption at all layers, including encrypting the data stored on the phone,
and use a secure transport layer for off device access such as SSL or TLS. Limit access to all user data to those
who have a legitimate business purpose for accessing the data
Empower your customers to control their information. Give users additional choices and controls,
including the use of a settings menu or privacy-sensitive default settings. For example, if you are collecting
additional PII that is not strictly necessary for the app, make it clear to the customer that providing it is optional
and allow users to opt out. Consider providing a paid version that doesnt include ad packages.
Best Practices
324
Best Practices
325
Create a manifest
To use the AppCache feature, your web application must provide a "manifest" to the browser that lists all the
resources that it needs so that the application can function when offline. After the first time a web page is
loaded, the resources specified in the manifest file are obtained from the application cache, not from the web
server. The manifest is simply a text file that typically has a file extension of .appcache.
CACHE MANIFEST
# 2012-03-08:v1
# Explicitly cached resources
index.html
css/app.css
js/app.js
# offline.html displays if the user is offline
FALLBACK:
/ /offline.html
# All other resources require an online connection
NETWORK:
*
# Additional cached resources
CACHE:
img/logo.png
Your manifest file must be served with the mime-type text/cache-manifest. You may need to add a
custom file type to your web server or configuration. For example, to serve this mime-type in Apache, add this
line to your configuration file (httpd.conf):
AddType text/cache-manifest .appcache
To access the manifest file, you must declare it in your HTML document by adding the manifest attribute to
the <html> tag. The manifest attribute points to the manifest file. If your web application has more than
one page, make sure that each page includes the manifest attribute, otherwise those pages won't be part of
AppCache, and they won't work offline.
<html manifest="html5.appcache">
326
Related resources
To learn more about appcache, visit the following resources:
ApplicationCache API specification
Article from A List Apart Magazine
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">
327
External files are cached by the browser. This reduces the number of HTTP requests; however, inline
JavaScript and CSS is downloaded each time the HTML document is requested.
Reduces the size of the HTML document. Since the JavaScript and CSS files are external, there is less
inline code in the original HTML document to parse and render.
Note:
For BlackBerry WebWorks applications, the resources are typically bundled with the application. The following
information applies mainly to web (browser-based) applications.
The benefits for external files aren't experienced in every situation. Before you start externalizing your
application's resources, consider only making the resource external if:
The resource is used in more than one HTML document
The resource changes infrequently
Here are some tips when using external files in your web application:
Source your files off a well-known host, which can reduce the number of DNS lookups.
Spread the resources out to another domain. The browser has a limited number of connections that it will
open to a particular domain; if you spread the files out to another domain, it increases the browsers
freedom to parallelize requests.
Use CDN (Content Delivery Network) hosted files for common JavaScript libraries (for example, jQuery).
This can improve your web application's performance by decreasing latency and improving what's cached.
For example, if a user has visited another site that uses CDN hosted files, those files will already be cached
on the device. When the user visits your site for the first time, the library will already be available. Here's a
code example that uses the Google's CDN-hosted jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
jquery.min.js">
</script>
Analyze the performance of your web application by using the Web Inspector. For more information about
the Web Inspector, see Debugging using Web Inspector on page 292.
328
...
<link rel="stylesheet" href="styles1.css">
</head>
<body>
...
</body>
</html>
Best Practices
329
Unless you're using the deprecated document.write to generate the body, your scripts can typically be
moved to the bottom of the HTML document.
Another advantage to putting the script in the BODY (before the closing body tag) is that you don't need to
check to see if the DOM is loaded, because everything in the DOM has already loaded.
Recommended: Placing the script near the bottom of the BODY
<html lang="en">
<body>
...
<script src="js/app.js"></script>
</body>
</html>
330
document.body.appendChild(elem);
if (window.addEventListener) {
window.addEventListener("load", lazyload, false);
} else if (window.attachEvent) {
window.attachEvent("onload", lazyload);
} else {
window.onload = lazyload;
For more information on lazy loading, see the following resources:
Google Analytics - Tracking Basics (Asynchronous Syntax)
Microjs
Best Practices
331
So, the idea is to write more specific style rules so that the browser spends less time looking to match your
style.
#main-navigation {
}
body.home #page-wrap {
.main-navigation {
}
ul li a.current {
}
ul {
}
ul li a { }
* {
}
#content [title='home']
/*
/*
/*
/*
/*
/*
/*
/*
ID (Fastest) */
ID */
Class */
Class *
Tag */
Tag */
Universal (Slowest) */
Universal */
Note:
Although there might be a performance benefit in using appropriate CSS selectors, you shouldn't take the
selector rules too far because you might see a disproportionate increase in maintenance costs vs. the
performance benefits you gain. As always, you should analyze the performance of your application by using the
Web Inspector. For more information about the Web Inspector, see Debugging using Web Inspector on page
292.
There are four types of selectors. ID and class selectors are more efficient than tag or universal selectors.
Selector
Description
ID
This selector matches the unique element in the page with the specified ID.
Example: #chapter1 {text-align: center; }
Class
This selector matches all elements with a class attribute contain the class name.
Example: .chapter1 { font-weight: bold; }
Tag or type
This selector matches every instance of the element type in the document tree.
Example: h1 { font-family: sans-serif; }
Universal
The following example shows where a class selector would be more efficient that a descendant selector:
Slower
ul li {color: blue;}
ol li {color: red;}
Best Practices
332
Faster
.unordered-list-item {color: blue;}
.ordered-list-item {color: red;}
Examples
HTML
Inline CSS
Best Practices
333
External CSS
Here's an example that uses the nth-child notation along with CSS sprites to create a navigation menu:
#navcontainer li {
background-image: url('spritebg.jpg'); /* single image */
}
#navcontainer ul li:nth-child(1) {
background-position: -130px -700px; /* position = xpos ypos */
}
#navcontainer ul li:nth-child(2) {
background-position: -130px -718px;
}
#navcontainer a {
width: 250px; /* size */
height: 18px;
}
Best Practices
334
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.
335
contains a lot of content can result in performance issues, such as sluggish scrolling or an inconsistent
response to touch input.
To benefit from hardware acceleration, include the -webkit-overflow-scrolling: touch property if
you use an overflow property in your app. Here's an example:
... {
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
}
When you make this addition, it allows for momentum and smoother scrolling, a visual bounce effect when the
user reaches the top or bottom of the list, and a more responsive touch interaction.
Best Practices
336
Namespace collisions occur when two regions of code use the same global variable name for different
purposes. In JavaScript, variables defined outside a function or object are globally available and are part of the
global namespace. As your application grows and you add libraries to it, the risk of naming collisions increases.
Using global variables can also affect the performance of your script. If code inside a function or another scope
references a particular global variable, the script engine must go through each scope until it reaches the global
scope. A variable in the local scope is found more quickly. Variables in the global scope also persist through
the life of the script, whereas local scope variables are destroyed when the local scope is lost. The memory that
local variables use can then be freed by the garbage collector.
The following code snippet defines a function and variables that are global in scope. As a result, it is both
inefficientsince it persists in memory much longer than necessaryand at risk for future namespace
collisions.
//define global variables
var lang = "en";
var debug = true;
//define global function
function setLang (arg) {
lang = arg;
}
In the following example, we've rewritten the previous snippet to define and use a namespace. The namespace
object, myApp, is created and assigned values and functions to it. By using this technique, we limit the scope
of the variables and functions.
var myApp = {
lang: "en",
debug: true,
};
myApp.setLang = function (arg) {
this.lang = arg;
}
Structuring your code this way helps avoid name collisions and as your code base grows, you can neatly
separate the objects into logical files.
337
The following example shows a loop than might throw several exceptions affecting the performance of the
script:
var object = ['foo', 'bar'], i;
for (i = 0; i < object.length; i++) {
try {
// do something
} catch (e) {
// handle exception
}
}
We've re-written the previous code to improve the effectiveness of the try-catch block. Instead of including
the try-catch block within the loop, we restructure the code so that the try-catch block surrounds the
loop.
var object = ['foo', 'bar'], i;
try {
for (i = 0; i < object.length; i++) {
// do something
}
} catch (e) {
// handle exception
}
Example
str += "l";
Using string.concat()
Using array.join()
If you're concatenating just a few strings, then any of the above methods are acceptable and perform equally.
However, if the length and number of strings increase then you should optimize how you concatenate strings.
Best Practices
338
Best Practices
339
operator and by combining the control conditions. In the following example, the control condition is reduced
from two comparisons (is i < len and is the condition true?) to one (is the condition true?):
for (var i = arr.length; i--;) {
// in reverse
}
Best Practices
340
Best Practices
341
342
A repaint (often called a "redraw") occurs when you change an element that modifies its visibility but does not
affect its layout (for example, changing the background color). The browser recognizes the visual change and
repaints the document.
A reflow involves changes that affect the layout of a portion of the page (or the whole page) and causes the
reflow of all child and ancestor elements (for example, a table). With a reflow, the browser looks to see how
your changes affect the overall layout of the document. The browser recalculates the geometrics of the
changed element as well as the geometrics and positions of other elements that could be affected by the
change.
343
For static styles, change the class names not the styles. For dynamic styles, edit the cssText property.
// bad - changing the stle - accessing DOM multiple times
var myElement = document.getElementById('mydiv');
myElement.style.borderLeft = '2px';
myElement.style.borderRight = '3px';
myElement.style.padding = '5px';
// good - use cssText and modify DOM once
var myElement = document.getElementById('mydiv');
myElement.style.cssText = 'border-left: 2px; border-right: 3px; padding:
5px;';
When you have a number of changes to apply to a DOM element, batch the changes and perform them
outside the "live" document tree before any reflow-triggering actions.
Create a copy of the node you want to update by using cloneNode(), work on that copy, and then
replace the old node with your updated copy.
// slower - multiple reflows
var list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
elem.appendChild(content);
document.body.appendChild(elem); // multiple reflows
}
// faster - create a copy
var orig = document.getElementById('container'),
clone = orig.cloneNode(true), // create a copy
list = ['foo', 'bar', 'baz'], elem, contents;
clone.setAttribute('width', '50%');
Modify an invisible element. If you need to modify an element, temporarily change its display
property to none, modify the element, and then set the display property to block. This technique
temporarily removes the element from the document flow, thus reducing the number of reflows.
// slower
var subElem = document.createElement('div'),
elem = document.getElementById('animated');
elem.appendChild(subElem);
elem.style.width = '320px';
// faster
var subElem = document.createElement('div'),
elem = document.getElementById('animated');
elem.style.display = 'none'; // will not be repainted
elem.appendChild(subElem);
elem.style.width = '320px';
elem.style.display = 'block';
Best Practices
344
Create a document fragment by using DocumentFragment() to make multiple changes to the DOM
in a single operation. After you've made your changes, append that fragment to the original document.
// slower
var list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
elem.appendChild(content);
document.body.appendChild(elem); // multiple reflows
}
// faster
var fragment = document.createDocumentFragment(),
list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
fragment.appendChild(content);
}
document.body.appendChild(fragment); // one reflow
Best Practices
345
Best Practices
346
Legal notice
2015 BlackBerry. All rights reserved. BlackBerry and related trademarks, names, and logos are the
property of BlackBerry Limited and are registered and/or used in the U.S. and countries around the world.
Adobe, Adobe Illustrator, and Photoshop are trademarks of Adobe Systems Incorporated. Bluetoothis a
trademark of Bluetooth SIG. Facebook and the Facebook logo is a trademark of Facebook, Inc. Slate Pro Font
is a trademark of Monotype Imaging Inc. and may be registered in certain jurisdictions. Twitter is a trademark
of Twitter, Inc. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are the property of their
respective owners.
This documentation including all documentation incorporated by reference herein such as documentation
provided or made available on the BlackBerry website is provided or made accessible "AS IS" and "AS
AVAILABLE" and without condition, endorsement, guarantee, representation, or warranty of any kind by
BlackBerry Limited and its affiliated companies ("BlackBerry") and BlackBerry assumes no responsibility for
any typographical, technical, or other inaccuracies, errors, or omissions in this documentation. In order to
protect BlackBerry proprietary and confidential information and/or trade secrets, this documentation may
describe some aspects of BlackBerry technology in generalized terms. BlackBerry reserves the right to
periodically change information that is contained in this documentation; however, BlackBerry makes no
commitment to provide any such changes, updates, enhancements, or other additions to this documentation
to you in a timely manner or at all.
This documentation might contain references to third-party sources of information, hardware or software,
products or services including components and content such as content protected by copyright and/or thirdparty web sites (collectively the "Third Party Products and Services"). BlackBerry does not control, and is not
responsible for, any Third Party Products and Services including, without limitation the content, accuracy,
copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other
aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Services
in this documentation does not imply endorsement by BlackBerry of the Third Party Products and Services or
the third party in any way.
EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL
CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS,
GUARANTEES, REPRESENTATIONS OR WARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR
PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NON-INFRINGEMENT, SATISFACTORY
QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF
TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE
OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES
REFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY
STATE OR PROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF
IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED
WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE
EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROM
Legal notice
347
THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE
CLAIM.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL
BLACKBERRY BE LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE,
OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD
PARTY PRODUCTS AND SERVICES REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE
FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL,
PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGES FOR LOSS OF PROFITS OR REVENUES, FAILURE TO
REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS
OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE
ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH
BLACKBERRY PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF BLACKBERRY
PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OF
SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR
PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN
IF BLACKBERRY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, BLACKBERRY
SHALL HAVE NO OTHER OBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR
OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY.
THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE
NATURE OF THE CAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO
BREACH OF CONTRACT, NEGLIGENCE, TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND
SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE
OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B) TO BLACKBERRY AND ITS
AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIME
SERVICE PROVIDERS), AUTHORIZED BLACKBERRY DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE
PROVIDERS) AND THEIR RESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS.
IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY
DIRECTOR, EMPLOYEE, AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF BLACKBERRY
OR ANY AFFILIATES OF BLACKBERRY HAVE ANY LIABILITY ARISING FROM OR RELATED TO THE
DOCUMENTATION.
Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to
ensure that your airtime service provider has agreed to support all of their features. Some airtime service
providers might not offer Internet browsing functionality with a subscription to the BlackBerry Internet
Service. Check with your service provider for availability, roaming arrangements, service plans and features.
Installation or use of Third Party Products and Services with BlackBerry's products and services may require
one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third
party rights. You are solely responsible for determining whether to use Third Party Products and Services and if
any third party licenses are required to do so. If required you are responsible for acquiring them. You should
not install or use Third Party Products and Services until all necessary licenses have been acquired. Any Third
Party Products and Services that are provided with BlackBerry's products and services are provided as a
convenience to you and are provided "AS IS" with no express or implied conditions, endorsements,
Legal notice
348
guarantees, representations, or warranties of any kind by BlackBerry and BlackBerry assumes no liability
whatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject
to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties,
except to the extent expressly covered by a license or other agreement with BlackBerry.
The terms of use of any BlackBerry product or service are set out in a separate license or other agreement with
BlackBerry applicable thereto. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY
EXPRESS WRITTEN AGREEMENTS OR WARRANTIES PROVIDED BY BLACKBERRY FOR PORTIONS OF ANY
BLACKBERRY PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION.
BlackBerry Limited
2200 University Avenue East
Waterloo, Ontario
Canada N2K 0A7
BlackBerry UK Limited
200 Bath Road
Slough, Berkshire SL1 3XE
United Kingdom
Published in Canada
Legal notice
349
Legal notice
350