blackberry_java_sdk-development_guide--1394789-1217034013-001-us

72
BlackBerry Java SDK Super App Development Guide

Upload: odane-p-hamilton

Post on 11-Mar-2016

213 views

Category:

Documents


1 download

DESCRIPTION

Super App Development Guide Published: 2010-12-17 SWD-1394789-1217034013-001 1 Introduction to Super App development.......................................................................................................... 3

TRANSCRIPT

BlackBerry Java SDKSuper App

Development Guide

Published: 2010-12-17SWD-1394789-1217034013-001

Contents1 Introduction to Super App development.......................................................................................................... 3

2 Always on.......................................................................................................................................................... 5Approaches to the always-on experience......................................................................................................... 5Creating an always-on experience.................................................................................................................... 6

Running an application at startup............................................................................................................. 6Keeping the application running in the background................................................................................. 6Creating alternate entry points................................................................................................................. 8Scheduling processes to run periodically.................................................................................................. 10

3 Highly contextualized........................................................................................................................................ 13Approaches to adding context.......................................................................................................................... 13Adding connectivity context............................................................................................................................. 15Adding battery level context............................................................................................................................. 15

Power level change events........................................................................................................................ 15BlackBerry device characteristics...................................................................................................................... 17Adding location context.................................................................................................................................... 19

Accessing and displaying GPS location information.................................................................................. 19Retrieve the location of a BlackBerry device............................................................................................. 20

Using contextual menus................................................................................................................................... 21Pop-up menus and submenus................................................................................................................... 21Creating a pop-up menu............................................................................................................................ 22Create a pop-up menu............................................................................................................................... 23

4 Integrated......................................................................................................................................................... 27Approaches to integrating your application..................................................................................................... 27Integrating by invoking a core application........................................................................................................ 28Handling content.............................................................................................................................................. 29Adding custom menu items.............................................................................................................................. 30Adding application icons................................................................................................................................... 31Customizing the Phone screen......................................................................................................................... 32Embedding UI components.............................................................................................................................. 33

5 Social and connected........................................................................................................................................ 36Approaches to connecting................................................................................................................................ 36The details......................................................................................................................................................... 37

Releasing a book........................................................................................................................................ 37Finding a book........................................................................................................................................... 43

6 Proactive and notification-driven..................................................................................................................... 46Approaches to notification............................................................................................................................... 46Understanding the BlackBerry Push Service..................................................................................................... 47Making Bookshelf a push-enabled application................................................................................................. 48

Implement the MessageListener interface................................................................................................ 48Subscribe to the Push Initiator.................................................................................................................. 50Update the banner indicator..................................................................................................................... 51

7 Efficient............................................................................................................................................................. 52Approaches to efficient application design...................................................................................................... 52Responding to the status of the device............................................................................................................ 53Eliminating unnecessary processing on the device.......................................................................................... 56Using location services effectively.................................................................................................................... 57Using the Profiler tool....................................................................................................................................... 59Storing data on the device................................................................................................................................ 61

8 Glossary............................................................................................................................................................ 65

9 Provide feedback.............................................................................................................................................. 67

10 Legal notice....................................................................................................................................................... 68

Introduction to Super App development 1Create a transformative mobile application experience on the BlackBerry platform.

Whether you develop in Java®, or HTML and JavaScript®, you can leverage the unique capabilities of the BlackBerry®Application Platform to create a Super App. When you design a mobile application, the most important question toask is this: how do I create the best experience for my user given the constraints of a mobile device?

The question is important because whether your app is free, sold, or pushed to the user, its success and reputationdepends in part on creating the best-in-class mobile experience. What does "best-in-class mobile experience" meanin practice? It means that your users can't live without your app. It means that your app makes every day richer andeasier for your user. Those apps are Super Apps.

This guide demonstrates the principles behind outstanding mobile application design. Super Apps have the followingsix characteristics:

1. Always-on

Super Apps run in the background on a BlackBerry device to ensure that information is ready for the user before theyneed it. Whether it runs on device startup, or while the user works with another application, a Super App:

• Pulls critical data to the device• Registers custom menu items• Listens for and reacts to events• Creates notifications• Shares data with other applications

2. Highly contextualized

Super Apps provide users with information based on location or activity. A Super App can use GPS data, the call log,calendar appointments, and more to sense and deliver on the user's information requirements.

3. Tightly integrated with core applications

Many core applications on a BlackBerry device expose an API that allows you to add menu items for one-click accessto your Super App, use specific components from the core application, or inject data.

4. Social and connected

Super Apps facilitate interaction between users. BlackBerry APIs enable you to capture photos and videos. You canshare your media with other devices, or over the Internet. You can also create emails, SMS messages, MMS messages,and instant messages.

5. Proactive and notification-driven

Super Apps keep users informed about events or when important new data arrives. Your Super App can play a soundor vibrate the device, change the app's Home screen icon, and more.

6. Efficient and scalable

Development Guide Introduction to Super App development

3

A Super App respects the constraints of a mobile device: battery life, cellular data costs, and limited processing power.A Super App can rely on technologies like the BlackBerry® Push Service and Wi-Fi® to execute code only when needed,and minimize network bandwidth.

Developing a Super App

The chapters that follow demonstrate the six characteristics of Super Apps by developing an application namedBookshelf. This application is designed to catalog the books in a user's collection, and connect the user with otherswho share a love of books. The user can enter the title and description for each book in their collection and displaya list of their books.

One way to make Bookshelf engaging is to enable its users to share their love of books. Adding social features to thecatalog functions effectively will force us to explore all six Super App characteristics. To add a social dimension toBookshelf, there are four user stories to consider:

1. A user wants to broadcast their thoughts and feelings about a book.

2. A user wants to share their thoughts with others who have read the same book.

3. A user wants to encourage others to read a book.

4. A user is looking for book recommendations.

Each of those user stories requires some kind of communication channel between two Bookshelf users, and a preciseway to refer to books. Creating a channel for users who already know each other can be straightforward. For example,you could devise a way to associate information from the Contacts application on a BlackBerry device with knownBookshelf users. Then, you could then send a message from one device to another through BlackBerry® Messengeror email.

A more challenging problem arises when you want to create an opportunity for users who may not know each otherto interact. In this case, you will need a network server to coordinate the interactions of Bookshelf users. You coulduse any social networking tool to post messages about books. This approach would cover user stories 1, 2, and 4. Toinclude user story 3, you could create a systematic way to leave a book in a publicly accessible place, such as a coffeeshop, for another Bookshelf user to find.

Imagine that you can socialize Bookshelf users through a web service. The Bookshelf web service would perform thefollowing functions:

• Associate books with users, either by copy, edition, or title.• Provide a unique, printable QR code for users to attach to a book. This gives users a precise way to refer to books.• Provide location information about books that were released.• Push information related to a book that a user has released.

By the end of this guide, the Bookshelf app will enable a user to participate in a community of book-lovers throughtheir catalog of books.

Development Guide Introduction to Super App development

4

Always on 2Whether it listens and reacts to events, generates notifications, or shares data with other applications, a Super Appis always working behind the scenes. By permitting your application to run in the background, you can take advantageof a number of powerful features of the BlackBerry® Application Platform. Do you want your application to listen forpushed content and notify BlackBerry device users when the content arrives? Do you want your application to providelocation-specific information updates to your users? These types of tasks rely on your application's ability to run inthe background.

This chapter focuses on how to create the framework for an application that provides an always-on experience, whichis a fundamental characteristic of a Super App. Once we've demonstrated the framework by using the Bookshelfapplication, you'll have a starting point and can begin implementing other Super App characteristics that are discussedin later chapters.

What are the benefits of an always-on application?• Keep the user informed. You can create a framework that supports push communication, allowing BlackBerry

device users to receive information and updates as changes occur.• Use the capabilities of BlackBerry devices. A BlackBerry device is a multitasking environment that integrates

with a user's schedule and needs.• Anticipate the needs of your users. Your application can download content before users need it.• Integrate with other applications. Your application can communicate with other applications that are running

in the background.

Approaches to the always-on experienceTo create an always-on experience, you can implement some of the following approaches.

Approach Description

Run your application at startup. One of the most basic steps in creating an always-on experience is makingyour application run automatically when users turn on their BlackBerry®devices.

Keep your application running in thebackground.

Once your application is up and running, there are steps that you can taketo make sure that it continues to run efficiently in the background, evenafter a user closes the UI component for your application.

Create alternate entry points. By creating alternate entry points, you can split your application intomultiple processes. For example, your main entry point might launch a UIcomponent (using an icon on the Home screen) while another entry pointstarts a background process that listens for pushed content and sends usersnotifications.

Schedule processes to runperiodically.

By scheduling processes to run at set intervals, you can keep your users up-to-date and you can conserve memory and battery power on the devicewhen the process doesn't need to be running.

Development Guide Always on

5

Creating an always-on experienceThe Bookshelf app can receive pushed information about books that other Bookshelf users release and informationabout the books that interest you (see the Social and connected and Proactive and notification-driven chapters formore information). Since you don't want to have to wait for users to manually start Bookshelf before they can receivenotifications when new information arrives, it's up to you to make sure that there are threads running in thebackground that can listen for updates, and send notifications to your users when new content is available.

Bookshelf can also help users locate books that other users release. To locate these books, make sure that Bookshelfcan efficiently retrieve the position of the BlackBerry® device so that the application can notify users when booksare nearby.

Running an application at startupMaking your application to run when BlackBerry® device users turn on their devices doesn't require any changes toyour application code. If you're using the BlackBerry® Java® Plug-in for Eclipse®, you can edit theBlackBerry_App_Descriptor.xml file so that your application runs each time the BlackBerry device turns on. ForBlackBerry® WebWorks™ application developers, a similar option is available in the BlackBerry® WebWorks™ Plug-in for Eclipse in the config.xml file.

If you want your application to run when BlackBerry device users turn on their devices, chances are that you probablydon't want to launch the UI component for the application (most users are not going to want to see your applicationUI every time they turn on their devices). In Bookshelf, we need the ability to launch a background process that canlisten for push events.

Run an application at startup

1. In Eclipse®, in the Package Explorer view, expand a BlackBerry® application project and double-clickBlackBerry_App_Descriptor.xml.The application descriptor opens in the Editor view.

2. In the General Information section, select the Auto-run on startup check box.

3. On the File menu, click Save.

Keeping the application running in the backgroundIf your application has a UI component, you might want to keep your application running in the background evenafter a BlackBerry® device user closes the screen for your application. By default, when the last screen for yourapplication is popped off the display stack, Screen.onClose() invokes System.exit() to terminate theapplication. To get your application to continue to run in the background, you can override Screen.onClose() andinvoke UiApplication.getUiApplication().requestBackground() to push the application to thebackground when a user closes the last screen in the display stack.

Though it might seem inefficient to keep your application always running, there are a number of steps that you canperform to ensure that your application isn't hogging resources or draining the battery. See the Efficient chapter formore information about releasing unneeded resources, stopping UI processes, and managing the backlight.

Development Guide Creating an always-on experience

6

Keep the application running in the background

The following steps demonstrates how to create an application that displays a simple screen. When the BlackBerry®device user closes the screen (for example, by pressing the Escape key or by switching applications) the applicationis pushed to the background rather than terminated. If you want to verify that the application is still running, youcan press and hold the Menu key until the Switch Application menu appears. The icon for your application is stillpresent.

1. Import the required classes and interfaces.

import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.UiApplication;

2. Create the application framework by extending the UiApplication class. In main(), create an instance of thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheBackgroundAppDemoScreen class, which is described in step 3, represents the custom screen.

public class BackgroundAppDemo extends UiApplication{ public static void main(String[] args) { BackgroundAppDemo app = new BackgroundAppDemo(); app.enterEventDispatcher(); }

public BackgroundAppDemo() { BackgroundAppDemoScreen screen = new BackgroundAppDemoScreen(); pushScreen(screen); }

3. Create the framework for the custom screen by extending the MainScreen class. In the screen constructor,invoke setTitle() to specify the title for the screen.

public class BackgroundAppDemoScreen extends MainScreen{ public BackgroundAppDemoScreen() { setTitle("Background app demo"); }}

4. In the class for the custom screen, override onClose() and invoke requestBackground() so that theapplication is pushed to the background rather than terminated when a user closes the screen.

public boolean onClose(){ requestBackground(); return true;}

Development Guide Creating an always-on experience

7

Creating alternate entry pointsYou can use alternate entry points in your application, to launch an application in different ways. For example, yourapplication could have one entry point that launches the UI component for your application and another entry pointthat launches a background process that listens for incoming push messages, pre-processes data, or initializesnetwork communications with a host server.

In Bookshelf, we need at least three entry points. The main entry point, which launches the UI component for theapplication, runs when BlackBerry® device users click the Home screen icon for the application. A second entry point,which runs automatically when the device turns on, listens for pushed content in the background. A third entry point,which also runs automatically at startup (and then afterwards at scheduled intervals) acquires the location of thedevice and communicates the location to the Bookshelf web service. We'll discuss this entry point later on, when wediscuss how to schedule processes to run periodically.

If you're using the BlackBerry® Java® Plug-in for Eclipse®, you can specify an alternate entry point in theBlackBerry_App_Descriptor.xml file. After you set up an entry point in Eclipse, you need to set up the main() methodin your application to support the alternate entry points.

Specify the alternate entry point settings for a BlackBerry application

1. In Eclipse®, in the Package Explorer view, expand a BlackBerry® application project.

2. Double-click BlackBerry_App_Descriptor.xml.

3. On the Alternate Entry Points tab, click Add.

4. In the New Entry Point dialog box, type the name of a project in the workspace that this project invokes.

5. Click OK.

6. Select the Alternate entry point properties and Locale Resources.

7. On the File menu, click Save.

Properties for the alternate entry point settings

Setting Description

Title Type a name for the alternate entry point that is displayed on the Homescreen of the BlackBerry® device.

Application arguments Specify the arguments to pass into the application's main() method.Do not show the application icon onthe BlackBerry device Home screen

Select this setting to run the application in the background, withoutdisplaying an icon on the Home screen of the BlackBerry device.

This setting is not available if the Application type is Library.Auto-run on startup Select this setting to start the application automatically when the BlackBerry

device starts.

Applications that run automatically must be digitally signed by Research InMotion to run on a BlackBerry device.

Development Guide Creating an always-on experience

8

Setting Description

Startup tier If the Auto-run on startup setting is selected, specify the priority in whichthe application is started, in relation to other applications.

For third-party applications, you can select tier 6 or 7 (other start-up tiersare reserved for core BlackBerry Applications). The default setting is 7(lowest priority).

Internationalized resource bundleavailable

Select this setting if the title and the description of the alternate entry pointhave been internationalized in a resource bundle.

Resource bundle Select the resource header file to use for the alternate entry point.Title ID Select the resource key to use for the application title (for example,

AEP_TITLE). If you do not provide a resource key for the application title,the BlackBerry® Java® Plug-in uses the title that is specified in the Title field.

Alternate Entry Point icons Add the files for application icons from the project's resources or from alocation external to the project.

To specify a rollover icon, select Rollover.

The number of application icons is limited to two.

Support alternate entry points in an application

The following steps demonstrate how to create a simple application that supports multiple entry points. The main() method checks to see which entry is used to enter the application by checking the application argument (thisexample specifies pushListener as the argument to check for). If the application is entered by using thepushListener argument, the BlackBerry® device vibrates. If the application is started by using any other argument,the application launches the UI component for the application.

1. Import the required classes and interfaces.

import net.rim.device.api.system.Alert;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.UiApplication;

2. Create the application framework by extending the UiApplication class. In main(), create an if statementthat checks to see which entry point is used to enter the application. In the if block, invoke Alert.setVibrate() to make the device vibrate if the application is entered by using the pushListener argument. In theelse block, create an instance of the new class and invoke enterEventDispatcher() to enable theapplication to receive events. In the application constructor, invoke pushScreen() to display the custom screenfor the application. The EntryPointsDemoScreen class, which is described in step 3, represents the customscreen.

public class EntryPointsDemo extends UiApplication{ public static void main(String[] args) { if (args != null && args.length > 0 && "pushListener".equals(args[0])) { Alert.startVibrate(2550);

Development Guide Creating an always-on experience

9

} else { EntryPointsDemo app = new EntryPointsDemo(); app.enterEventDispatcher(); } } public EntryPointsDemo() { EntryPointsDemoScreen screen = new EntryPointsDemoScreen(); pushScreen(screen); }

3. Create the framework for the custom screen by extending the MainScreen class. In the screen constructor,invoke setTitle() to specify the title for the screen.

public class EntryPointsDemoScreen extends MainScreen{ public EntryPointsDemoScreen() { setTitle("Entry points demo"); }}

Scheduling processes to run periodicallyThe Bookshelf app permits users to find books that other Bookshelf users release to the world. To notify users whenthere are books nearby, Bookshelf needs to send the Bookshelf web service the current location of the BlackBerry®device. Since acquiring the location of a device can consume a lot of battery power, it can make sense to schedulethis process to run periodically rather than run constantly in the background. To schedule your application to run ata particular time, you can use ApplicationManager.scheduleApplication().

Schedule processes to run periodically

This task demonstrates how to create a simple application that can schedule itself to run again. The main() methodchecks to see which entry is used to enter the application by checking the application argument (this example specifiesstartVibrate as the argument to check for). Each time the application is entered using the startVibrateargument, the BlackBerry® device vibrates and schedules the application to run again. If the application is enteredusing any other argument, the application launches the UI component for the application and does not schedule theapplication to run again.

1. Import the required classes and interfaces.

import net.rim.device.api.system.Alert;import net.rim.device.api.system.ApplicationDescriptor;import net.rim.device.api.system.ApplicationManager;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.UiApplication;

Development Guide Creating an always-on experience

10

2. Create the application framework by extending the UiApplication class. In main(), create an if statementthat checks to see which entry point is used to enter the application. In the if block, invoke scheduleVibrate(), which is the custom static method that starts the vibration and schedules the application to run again. Inthe else block, create an instance of the new class and invoke enterEventDispatcher() to enable theapplication to receive events. In the application constructor, invoke pushScreen() to display the custom screenfor the application. The ScheduleAppDemoScreen class, which is described in step 3, represents the customscreen.

public class ScheduleAppDemo extends UiApplication{ public static void main(String[] args) { if (args != null && args.length > 0 && "startVibrate".equals(args[0])) { scheduleVibrate(); } else { ScheduleAppDemo app = new ScheduleAppDemo(); app.enterEventDispatcher(); } } public ScheduleAppDemo() { ScheduleAppDemoScreen screen = new ScheduleAppDemoScreen(); pushScreen(screen); }

3. Create the framework for the custom screen by extending the MainScreen class. In the screen constructor,invoke setTitle() to specify the title for the screen.

public class ScheduleAppDemoScreen extends MainScreen{ public ScheduleAppDemoScreen() { setTitle("Schedule app demo"); }}

4. Create scheduleVibrate(). Invoke Alert.startVibrate(2550) to make the device vibrate. Create anApplicationDescriptor object by invokingApplicationDescriptor.currentApplicationDescriptor() to retrieve the application descriptor ofthe application that is currently running. Invoke setPowerOnBehavior(ApplicationDescriptor.DO_NOT_POWER_ON) on the application descriptor so that when the applicationruns as scheduled, if the device is currently off, the application doesn't force the device to turn on. InvokeApplicationManager.getApplicationManager() to retrieve an instance of the system'sApplicationManager. Invoke ApplicationManager.scheduleApplication() and specify theApplicationDescriptor that you created and the time that you want the application to run as arguments.

private static void scheduleVibrate(){ Alert.startVibrate(2550); ApplicationDescriptor current = ApplicationDescriptor.

Development Guide Creating an always-on experience

11

currentApplicationDescriptor(); current.setPowerOnBehavior(ApplicationDescriptor.DO_NOT_POWER_ON); ApplicationManager manager = ApplicationManager.getApplicationManager(); manager.scheduleApplication(current, System.currentTimeMillis() + 60000, true);}

Development Guide Creating an always-on experience

12

Highly contextualized 3A typical BlackBerry® device application performs a task in response to user input. If the application needs additionalinformation to perform the task, the application queries the user for that information. A well-designed, typicalapplication might store information so it doesn't have to ask for the information again. But a Super App is designedto avoid querying its users at all. Instead, a Super App tries to gather the information it needs programmatically.

Access to a GPS radio, an accelerometer, comprehensive APIs for gathering BlackBerry device information, APIs forusing core BlackBerry application functionality, and reliable connectivity to a wide variety of web services—withthese features, a Super App can gather much of the contextual information it requires.

A typical application might perform a task at a scheduled time, but a typical application doesn't often initiate tasks.A Super App with more information about the context it is running in, can initiate appropriate tasks and presentusers with appropriate features and options at the right time. With a Super App, you can surprise your users.Sometimes a Super App almost appears to be intelligent.

The Clock application on a BlackBerry device includes a great example of a simple, highly contextualized feature.When you travel between time zones, the Clock application offers to reset your home time zone to the zone thatyou have travelled into. This feature improves the application in two ways. First, you are reminded to update yourtime zone. And second, you are presented with the correct time zone. You only have to press a button to confirmthat you want the Clock application to make the change.

What are the benefits of a highly contextualized application?• Improve the user experience. Applications that anticipate user needs and prompt users to verify input might

be easier to use than applications that do not anticipate user needs and require users to input information fromscratch.

• Reduce input errors. Getting geographical coordinates of a device's current location by using the GPS radio ismuch less error prone than asking a user to enter the name of the city they are currently in.

• Lower support costs. Less user input and more contextually intelligent presentation of features can result infewer support calls about how to invoke a feature or how to enter information in the correct format.

Approaches to adding contextYou can make your application highly contextualized by using any of the following approaches.

Approach Examples

Add location context. If your application includes a search feature, the feature can probably beimproved by automatically incorporating the current location of theBlackBerry® device into the search criteria. Users searching for gas stationsare likely most interested in ones near their current location. Many webservices provide location-specific services. Your Super App can use thoseservices.

Development Guide Highly contextualized

13

Approach Examples

Add time context. Imagine you create an application that can search for restaurants. You canadd some context by using the location of the device to organize the searchresults by distance from the device. If the data service you use includesinformation about hours of operation, you can make the results even betterby only showing restaurants that are open. The data service might eveninclude information about lunch or dinner specials and, taking into contextthe current time, you could present the results accordingly.

Add date context. Some web sites and applications display custom themes to celebrate specialdays such as holidays, birthdays of famous people, or current events. Thiscustomization is an example of how you can improve an application with aminor tweak that makes use of context. In this case, the context is the date.

Your Super App should customize its actions according to the current datewhen doing so could improve the user experience.

Add battery level context. Your Super App should check the power level of the battery beforeperforming tasks that consume a lot of power. Your app can let the userknow that they are about to perform a task that consumes a lot of powerand that their battery is low. It could also stop doing any unnecessarybackground processing or prefetching.

Add connectivity context. Your Super App should check the type of network connections that areavailable. For example, if the user requests that the application downloadand play a large video file when the device is roaming on a wireless network,the application should warn the user that the download might be expensive.A Super App might also leverage a web service to determine roaming ratesand calculate the approximate cost.

If the device is connected to a low-cost, but very low-bandwidth, Wi-Fi®connection, the application should warn the user that the download mighttake a very long time. The application might provide an approximatedownload time, and let the user decide whether to proceed.

Add device characteristics context. Your Super App should adapt to the device model it is running on. Batterylife and connectivity are universal contexts for BlackBerry deviceapplications. But device characteristics such as the available keyboardtypes, screen type and dimensions, audio capabilities, inserted memorycards, and the presence of an accelerometer are specific to the particularBlackBerry device.

Super Apps provide good default choices for their users. For example, on adevice with a touch screen that supports gestures, a Super App displayshints about how to zoom in and out using pinch gestures.

Development Guide Approaches to adding context

14

Approach Examples

Use contextual menus. Your Super App should provide users with options that make sense basedon what the users are currently doing within the app. Use pop-up menusto provide users with a quick way to access the most common actions fora highlighted item.

Adding connectivity contextSuper Apps are designed to take into account the BlackBerry® device models that they run on and the variable levelsof connectivity. Super Apps are also designed to take into account different types of connections with differentassociated costs. Often, Wi-Fi® connections are cheap, and roaming cellular connections are expensive.

Your application can determine the type of network the device is connected to, discover and interpret signal levels,and check if a device is using a roaming cellular connection.

You can use RadioInfo.getSignalLevel() to get the signal level of the current connection. The following tablecan help you interpret the results.

Network type Strong signal Medium signal Weak signal

GSM® > -76 dBm -86 dBm to -92 dBm < -101 dBmCDMA > -83 dBm -92 dBm to -105 dBm < -109 dBmWi-Fi > -50 dBm -70 dBm to -60 dBm < -80 dBm

Use the NETWORK_SERVICE_ROAMING flag to determine if a device is currently using a roaming cellular connection,as demonstrated in the following code sample.

int networkService = RadioInfo.getNetworkService();if ( (networkService & RadioInfo.NETWORK_SERVICE_ROAMING) != 0){ //BlackBerry device is using a roaming connection}

Adding battery level context

Power level change eventsYour can register a BlackBerry® device application so it is notified when power level change events take place on thedevice it is running on. If the battery power level is low, you can respond by turning off or modifying some featuresof your application to conserve power. When your application receives notification that the battery power level isgood again, you can turn on those features again.

To process power level change events, your application must implement thenet.rim.device.api.system.SystemListener interface.

Development Guide Adding connectivity context

15

The following code sample demonstrates how to implement the SystemListener interface.

import java.util.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;

public class PowerChangeEventextends Application implements SystemListener{ public static PowerChangeEvent theApp;

public static void main(String args[]) { theApp = new PowerChangeEvent(); theApp.enterEventDispatcher(); }

public PowerChangeEvent() { Application.getApplication().addSystemListener(this); System.out.println("PowerChangeEvent: PowerChangeEvent has started!"); }

public void powerOff() { System.out.println("PowerChangeEvent: The device is powering off."); }

public void powerUp() { System.out.println("PowerChangeEvent: The device is powering up."); }

//Invoked when the internal battery voltage falls below a critical level. public void batteryLow() { System.out.println("PowerChangeEvent: The battery is getting low!"); }

//Invoked when the internal battery voltage has returned to normal. public void batteryGood() { System.out.println("PowerChangeEvent: The battery level is now good!"); }

//Invoked when the internal battery state has changed. //Not used in this sample. public void batteryStatusChange(int status) { }}

Development Guide Adding battery level context

16

BlackBerry device characteristicsThere are a number of methods, mostly in classes in the net.rim.device.api.system package, that provideinformation about a device. The following is a list of some common device information you can get using thosemethods. Most of the methods are static. Some of the methods return integral types that represent a set of bit flags.When that is the case, the class includes bit masks you can use to extract the information.

Device characteristic MethodIdentitydevice is simulator DeviceInfo.isSimulator()manufacturer DeviceInfo.getManufacturerName()device name DeviceInfo.getDeviceName()PIN DeviceInfo.getDeviceId()IMSI SIMCardInfo.getIMSI()ESN CDMAInfo.getESN()MEID CDMAInfo.getHexMEID()IMEI GPRSInfo.getIMEI()owner information OwnerInfo.getOwnerInformation()owner name OwnerInfo.getOwnerName()vendor ID Branding.getVendorId()branding data version Branding.getVersion()branding data is signed Branding.isDataSigned()Batterybattery power level (%) DeviceInfo.getBatteryLevel()additional battery information DeviceInfo.getBatteryStatus()battery temperature (°C) DeviceInfo.getBatteryTemperature()battery voltage (mV) DeviceInfo.getBatteryVoltage()battery is removable DeviceInfo.isBatteryRemovable()Speaker and Headsetaudio is supported Audio.isSupported()codec is supported Audio.isCodecSupported()volume level (%) Audio.getVolume()headset is built-in Audio.hasBuiltInHeadset()headset is connected Audio.isHeadsetConnected()Accelerometeraccelerometer is supported AccelerometerSensor.isSupported()Flip Sensorflip is open or closed Sensor.getState()phone is flip Sensor.isSupported()Holster Sensor

Development Guide BlackBerry device characteristics

17

phone is in holster Sensor.getState()holster sensor is supported Sensor.isSupported()Slide Sensorsliding keyboard is supported Sensor.isSupported()slide is open Sensor.isSlideOpened()slide is closed Sensor.isSlideClosed()slide is moving Sensor.isSlideInTransition()Displayhorizontal resolution (pixels per meter) Display.getHorizontalResolution()vertical resolution (pixels per meter) Display.getVerticalResolution()drawable area height (pixels) Display.getHeight()drawable area width (pixels) Display.getWidth()number of display colors Display.getNumColors()additional display information Display.getProperties()Backlightbacklight is on Backlight.isEnabled()backlight brightness (%) Backlight.getBrightness()backlight brightness is configurable Backlight.isBrightnessConfigurable()backlight brightness default (%) Backlight.getBrightnessDefault()default backlight timeouts Backlight.getTimeoutDefault()LED IndicatorLED is supported LED.isSupported()LED is multi-color LED.isPolychromatic()Radioswireless access family is supported RadioInfo.getSupportedWAFs()GPSGPS mode is available GPSInfo.isGPSModeAvailable()default GPS mode GPSInfo.getDefaultGPSMode()BluetoothBluetooth® radio is supported BluetoothSerialPort.isSupported()Bluetooth information BluetoothSerialPort.getSerialPortInfo()Phonephone number Phone.getDevicePhoneNumber()voice mail is present Phone.isVoiceMailIndicatorOn()Memoryflash memory size (bytes) DeviceInfo.getTotalFlashSizeEx()free flash memory (bytes) Memory.getFlashFree()RAM statistics Memory.getRAMStats()OS and softwareplatform version DeviceInfo.getPlatformVersion()software version DeviceInfo.getSoftwareVersion()

Development Guide BlackBerry device characteristics

18

Cameracamera is supported DeviceInfo.hasCamera()USB portUSB port is supported USBPort.isSupported()USB connection state USBPort.getConnectionState()

Adding location context

Accessing and displaying GPS location informationA BlackBerry® device user can use a BlackBerry device application to access GPS data and view information on thelocation, speed, and direction of the BlackBerry device. A BlackBerry device application can use a source for GPS datathat provides data within specific accuracy parameters, at a specific cost, and uses a specific amount of battery power.

A BlackBerry device creates an object of the javax.microedition.location.Criteria class and invokes themethods of the class to specify the source of GPS data. For example, a BlackBerry device application invokesCriteria.setHorizontalAccuracy(2) and Criteria.setVerticallAccuracy(2) to specify that a sourceof GPS data must provide vertical and horizontal data values that is accurate within 2 meters of the actual values. ABlackBerry device application invokes Criteria.setCostAllowed(true) to use a source of GPS data that costsmoney to use. The BlackBerry device application can invoke Criteria.setPreferredPowerConsumption(POWER_USAGE_LOW) to use a source of GPS data that makes minimal use of the battery power on a BlackBerrydevice.

A BlackBerry device application sets the properties of the Criteria object to specify the mode the application usesto retrieve GPS data. The cell site mode allows a BlackBerry device application to retrieve GPS data from a cell sitetower. This mode is faster but less accurate than other modes. The assisted mode allows a BlackBerry deviceapplication to retrieve GPS data from a satellite. This mode is faster than the autonomous mode and more accuratethan the cell site mode. The autonomous mode allows a BlackBerry device application to retrieve GPS data from theBlackBerry device. This mode is slower but more accurate than other modes.

After creating and setting the properties of the Criteria object, a BlackBerry device application invokesjavax.microedition.location.LocationProvider.getInstance(Criteria) using the Criteria objectas a parameter to retrieve a LocationProvider object. A BlackBerry device application can invokeLocationProvider.getLocation() to retrieve an object of thejavax.microedition.location.Location class to access data for a location.

Invoking the Location.getSpeed() and Location.getCourse() methods retrieves the speed and the directionof the BlackBerry device. Invoking the Location.getQualifiedCoordinates() method retrieves ajavax.microedition.location.QualifiedCoordinates object that can provide the latitudinal andlongitudinal coordinates of the BlackBerry device.

A BlackBerry device application can listen for updates from a source for GPS data to provide a BlackBerry device userwith current GPS information. The BlackBerry device application must implement thejavax.microedition.location.LocationListener interface and invoke theLocationProvider.setLocationListener(LocationListener int, int, int) method to register the

Development Guide Adding location context

19

LocationListener with a LocationProvider.You can invoke LocationProvider.setLocationListener(LocationListener int, int, int) and use an integer value as the interval argument to specify how often,in seconds, the BlackBerry device application checks for new GPS data.

Retrieve the location of a BlackBerry device

1. Import the required classes.

import javax.microedition.location.*;

2. Create a class and a constructor.

public class handleGPS{ public handleGPS() { }}

3. Declare static fields in the class.

static GPSThread gpsThread;static double latitude;static double longitude;

4. In the constructor, create and start a local thread.

gpsThread = new GPSThread();gpsThread.start();

5. In the class, create a private class that extends Thread, and create a run() method.

private class GPSThread extends Thread{ public void run() { }}

6. In the run() method, create an instance of the Criteria class. Invoke setCostAllowed(false) to specifythat the autonomous mode.

Criteria myCriteria = new Criteria();myCriteria.setCostAllowed(false);

7. In the run() method, create a try/catch block. In the block create a LocationProvider object by gettingan instance of the Criteria object. Create another try/catch block to create a Location object to requestthe current location of the BlackBerry® device and specify the timeout period in seconds. When thegetLocation() method returns, request the latitude and longitude coordinates.

try{ LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);

Development Guide Adding location context

20

try { Location myLocation = myLocationProvider.getLocation(300); latitude = myLocation.getQualifiedCoordinates().getLatitude(); longitude = myLocation.getQualifiedCoordinates().getLongitude(); } catch ( InterruptedException iex ) { return; } catch ( LocationException lex ) { return; }}catch ( LocationException lex ){ return;}return;

Using contextual menus

Pop-up menus and submenusYou can add a pop-up menu and a submenu to your application by using the classes provided in thenet.rim.device.api.ui.menu package.

Menu Description

Pop-up menu A pop-up menu, similar to a context menu, contains a list of the mostcommon actions that BlackBerry® device users can perform within thecurrent context. An item in the pop-up menu can include the text, anapplication icon, and a command.

A pop-up menu replaces a context menu, or a short menu, that was availablein previous versions of the BlackBerry® Java® SDK. The BlackBerry® DeviceSoftware automatically converts an existing context menu into a pop-upmenu.

Development Guide Using contextual menus

21

Menu Description

Submenu A submenu is a group of related menu items. A submenu appears as a subsetof a menu item in the full menu. When you include items in a submenu,users can find frequently-used items or important items more easily in thefull menu.

Find out more

For more information about pop-up menus and submenus, visit the following resources:

• net.rim.device.api.ui.menu package overview• Command Framework sample application that is included in the BlackBerry Java SDK• BlackBerry Java SDK UI and Navigation Development Guide• UI Guidelines for BlackBerry Smartphones

Creating a pop-up menuYou can create a pop-up menu by using classes that are available in the net.rim.device.api.ui.menu package,and you can define the functionality of the pop-up menu items by using the Command Framework API.

Development Guide Using contextual menus

22

A pop-up menu consists of a context menu provider, a command item provider, and command items.

Component Description

Context menu provider You use the DefaultContextMenuProvider class to create and displaya screen's pop-up menu. When a BlackBerry® device user opens a pop-upmenu, the context menu provider looks for fields on the screen that arecommand item providers. DefaultContextMenuProvider is the defaultimplementation of ContextMenuProvider. If you do not provide a screenwith a context menu provider, the legacy context menu is converted anddisplayed as a pop-up menu.

Command item provider You use the CommandItemProvider class to configure a field on your UIscreen so that the field can provide context and command items to the pop-up menu based on the current context. For example, you could configurean email address as a command item provider and provide the user withdifferent actions based on whether the email address is in the user's contactlist.

Command items You use the CommandItem class to specify the text, icon, and behavior of apop-up menu item. You define the behavior of the pop-up menu by usinga command. The command acts as a proxy to an instance of a commandhandler, which defines the functionality of the pop-up menu item. Forexample, for an email address, you could provide command items to addor view a contact based on whether the selected email address appears inthe user's contact list. The command handler would contain the code to addor view the contact.

For more information on commands and command handlers, see CommandFramework API. The Command Framework sample application that isprovided in the BlackBerry® Java® SDK demonstrates commands andcommand handlers.

If you use a legacy context menu, BlackBerry® Device Software 6.0 converts the context menu items to commanditems and provides them to the command item provider. For more information, see Support for legacy context menus.

Create a pop-up menu

1. Import the required classes and interfaces.

import net.rim.device.api.command.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.menu.*;

Development Guide Using contextual menus

23

import net.rim.device.api.ui.image.*;import net.rim.device.api.util.*;import java.util.*;

2. Create the application framework by extending the UiApplication class. In main(), create an instance of thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheMyPopUpMenuScreen class, which is described in step 3, represents the custom screen.

public class MyPopUpMenuApp extends UiApplication { public static void main(String[] args) { Mypop-upMenuApp theApp = new Mypop-upMenuApp(); theApp.enterEventDispatcher(); } public Mypop-upMenuApp() { pushScreen(new Mypop-upMenuScreen()); } }

3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor,invoke setTitle() to specify the title for the screen.

class MyPopUpMenuScreen extends MainScreen{ EmailAddressEditField emailAddress; public Mypop-upMenuScreen() { setTitle("Pop-Up Menu Demo"); }}

4. In the screen constructor, specify a context menu provider. Pass a DefaultContextMenuProvider object toScreen.setContextMenuProvider() to enable your screen to display a pop-up menu.

setContextMenuProvider(new DefaultContextMenuProvider());

5. In the screen constructor, create UI components that can invoke the pop-up menu. In the following code sample,the label uses the Field.FOCUSABLE property to allow users to highlight the field.

LabelField labelField = new LabelField("Click to invoke pop-up menu", Field.FOCUSABLE);emailAddress = new EmailAddressEditField("Email address: ", "[email protected]", 40);

6. In the screen constructor, configure the UI components as command item providers. TheDefaultContextMenuProvider object looks for fields that are configured as command item providers, anduses them to create and display a pop-up menu. For each component, invokeField.setCommandItemProvider() to configure the field as a command item provider. TheItemProvider class is described in step 7.

Development Guide Using contextual menus

24

ItemProvider itemProvider = new ItemProvider(); labelField.setCommandItemProvider(itemProvider);emailAddress.setCommandItemProvider(itemProvider);

7. In the custom screen, implement the CommandItemProvider interface. In getContext(), return the fieldthat is configured as a command item provider. In getItems(), create a Vector object to add the pop-upmenu items to.

class ItemProvider implements CommandItemProvider { public Object getContext(Field field) { return field; } public Vector getItems(Field field) { }}

8. In getItems(), provide the pop-up menu items by creating instances of the CommandItem class. For eachcommand item, specify the pop-up menu text, icon, and command. In the following code sample, an if-then-else statement is used to check which component invoked the pop-up menu before creating theCommandItem. The command is a proxy to an instance of a class that extends the abstract CommandHandlerclass, which is described in step 9. Invoke Vector.addElement() to add the pop-up menu items to theVector. Return the Vector.

CommandItem defaultCmd;

Image myIcon = ImageFactory.createImage(Bitmap.getBitmapResource("my_logo.png"));

if(field.equals(emailAddress)){ defaultCmd = new CommandItem(new StringProvider("Email Address"), myIcon, new Command(new DialogCommandHandler()));}else { defaultCmd = new CommandItem(new StringProvider("Label Field"), myIcon, new Command(new DialogCommandHandler()));}

items.addElement(defaultCmd);

return items;

9. In the custom screen, create a command handler by creating a class that extends the abstractCommandHandler class. In execute(), define the functionality that you want to associate with the pop-upmenu items. This command handler could be used by any UI component on your screen (for example, full menuitems, buttons, and so on). Because canExecute() is not implemented, this command is always executable.In the following code sample, a dialog box appears when the user clicks a pop-up menu item.

class DialogCommandHandler extends CommandHandler{ public void execute(ReadOnlyCommandMetadata metadata, Object context) {

Development Guide Using contextual menus

25

Dialog.alert("Executing command for " + context.toString()); } }

Development Guide Using contextual menus

26

Integrated 4An important goal for your Super App is to make it work seamlessly with other applications on the BlackBerry® device.BlackBerry device users want a natural experience, where the flow between your application and other applicationsis seamless and easy to use. They likely aren't concerned with what happens behind the scenes, and many usersdon't have the time or patience to ramp up and learn the details of a new application. Users want your app to work,and they'd like it to integrate with the applications they use the most. By integrating with core applications and third-party applications, you can provide a seamless and natural experience for the user.

What are the benefits of integrating with other applications?• Use what's already built. You can use the existing features and functions of core applications and third-party

applications to make your app an extension to the BlackBerry experience.• Lower the learning curve. Users don't have to stop and learn how to access your application because it's

integrated with applications they already know and use. This approach helps to provide an intuitive and seamlessexperience for the user, which can often decrease user frustration and increase app adoption.

• Become part of the user's routine. An integrated app can become an integral app. If a core or third-partyapplication is already part of a user's routine, by integrating with that application, you can provide consistentbehaviors and essential features that can also become part of the user's routine.

Approaches to integrating your applicationYou can integrate your application by using any of the following approaches.

Approach Examples

Invoke an application and passinformation to the application.

• When a user selects the address of a bookstore in the Contactsapplication, launch a turn-by-turn navigation application to providedirections to the associated address.

• While listening to a song on a radio application, launch anotherapplication that provides the option to purchase the song.

Development Guide Integrated

27

Approach Examples

Integrate with existing or newcontent handlers.

• When a user selects a link for an audio book, launch the media playerto play the audio book file.

• When a user receives a Microsoft® Word document, open thedocument by using the Documents To Go® application.

Integrate directly into an applicationby

• Creating custom menu items• Embedding UI components in

core applications• Adding custom UI fields

• Add a custom menu item in the Calendar application that can open ameeting planner application.

• Display a custom icon on the Home screen that changes based on thelocal weather forecast.

• Embed a map that displays bookstore locations that stock therecommended book.

Integrating by invoking a core applicationYou can provide an integrated experience for your users by invoking a core application from your application andpassing data to the core application. For example, in the Bookshelf application, a BlackBerry® device user can indicatethat a book is loaned by clicking a menu item, such as Loan, which launches the Contacts application and retrievescontact information. From the Contacts application, the user can return to the Bookshelf application and log theinformation about the person that the book was loaned to.

You can use the Invoke API in the net.rim.blackberry.api.invoke package to invoke core applications andpass data to those applications. Core applications that can be invoked include Contacts, Calculator, Calendar, Camera,BlackBerry® Maps, MemoPad, Messages, Phone, Search, and Tasks.

To invoke a core application from your application, you can use Invoke.invokeApplication(int appType,ApplicationArguments args), where appType represents the core application that you are invoking, andargs represents the data you are passing to the application.

Code sample: Invoking the Phone application

int appType = Invoke.APP_TYPE_PHONE;ApplicationArguments appArgs = new PhoneArguments(PhoneArguments.ARG_CALL, "519-555-5555");Invoke.invokeApplication(appType, appArgs);

An effective use of the Invoke API is to pair it with the ApplicationMenuItem class, which is provided in thenet.rim.blackberry.api.menuitem package. When you pair the Invoke API with ApplicationMenuItem, youcan provide the user with the ability to launch the invoked application and return to your application by using menuitems. For more information about menu items, see Adding custom menu items.

Find out more

For more information about invoking applications, visit the following resources:

• Application Integration category overview, in the API reference for the BlackBerry® Java® SDK

Development Guide Integrating by invoking a core application

28

• BlackBerry Java SDK Integration Development Guide

Handling contentAnother approach to creating a seamless user experience is to make sure your application can handle content byintegrating with existing or new content handlers. For example, when a user clicks a URL to an audio book, the mediaplayer opens and plays the audio book.

The Content Handler APIs, which are provided in the javax.microedition.content andnet.rim.device.api.content packages, allow applications to integrate with and use functionality in third-partyand core applications that use these APIs. For example, DataViz®, in the Documents To Go® applications, use theContent Handler APIs to register their applications as the content handlers for various document types. This suite ofapplications that is preloaded on most BlackBerry® devices also provides handles to allow third-party applicationsto invoke the Documents To Go applications with the supported document types. For example, your application caninvoke Documents To Go by using the Content Handler APIs and the URL to a spreadsheet or text document.

Using the Content Handler APIs, you can register your application to handle specific files based on their MIME typeor file extension or you can use these APIs to query for specific content handlers and then invoke the handler.

To make an application that is a content handler, you must register the application with the Registry API by using aunique ID. As part of the registration, you also specify the file types that the application can handle along with theactions that it supports for those files types. For example, you can register an application to print files of a specifiedtype. Once your application is registered as a content handler, other applications can query the registry to getinformation about the content types and actions this content handler supports, as well as invoke the content handler.

Code sample: Registering an application as a content handler

private static String ID = "com.rim.samples.device.chapidemo";private static String CLASSNAME = ID + ".CHAPIDemo";

private static void registerApp(){ String[] types = { "text/csv" }; String[] suffixes = { ".csv" }; String[] actions = { ContentHandler.ACTION_OPEN }; Registry registry = Registry.getRegistry( CLASSNAME ); registry.register( CLASSNAME, types, suffixes, actions, null, ID, null);}

To invoke a content handler, your application must initialize an Invocation instance with the information requiredto identify the content and/or the content handler. Typically, this information could include the URL, type, action,and content handler ID. Your application may also supply arguments and data, and specify whether a response isrequired. To invoke a core application that is a content handler, you can use thenet.rim.device.api.content.BlackBerryContentHandler class, which provides IDs for all core applicationhandlers on the device. These IDs are used with the Invocation class to invoke a specific content handler, or withthe Registry class to retrieve a specific ContentHandler class. You start the invocation request by calling theRegistry.invoke() method.

Development Guide Handling content

29

Code sample: Invoking the Media application by using a URL

//Create an Invocation instance with the file URLInvocation invocation = new Invocation("file:///SDCard/BlackBerry/music/001.mp3");

//Retrieve a Registry objectRegistry _registry = Registry.getRegistry("myPackageName.myClass");

//Invoke the content handler_registry.invoke(invocation);

Find out more

For more information about handling content, visit the following resources:

• Application Integration category overview, in the API reference for the BlackBerry® Java® SDK• How to use the content handler video in the BlackBerry Developer Knowlege Base

Adding custom menu itemsTo integrate your application with core applications, you can add a custom menu item. By adding custom menu itemsin core applications, you can provide a seamless experience for the BlackBerry® device user, where they can launchyour application from another application they use frequently. For example, you can add a menu item called LoanBook to the Contacts application. When the user clicks Loan Book, the Bookshelf application opens and displays thescreen for logging the loaned book.

You can define menu items to display in core applications by using the ApplicationMenuItem class, which is definedin the net.rim.blackberry.api.menuitem package.

The ApplicationMenuItem instance you create must be registered with theApplicationMenuItemRepository class. The ApplicationMenuItemRepository class provides the constantsthat specify the core application that your menu item appears in. For example, the MENUITEM_MESSAGE_LISTconstant specifies that the menu item appears in the list view of the Messages application, or theMENUITEM_SYSTEM constant specifies that your menu item appears in most core applications.

Development Guide Adding custom menu items

30

To specify where your menu item appears in the menu list, assign an Integer value to represent the display orderof the menu item. Positions are relative, so a lower number corresponds to a higher position in the menu. In thefollowing example, the Loan Book menu item has an order value of 0x350100, which displays the menu item lowerin the menu (higher numbers mean the menu item appears lower in the menu and lower values mean the itemappears higher in the menu).

When an ApplicationMenuItem is invoked, the core application passes a context object to your application. Thecontext that is returned depends on the core application from which your menu item was invoked. In the followingexample, the context returned is a contact.

Code sample: Creating a custom menu item in the Contacts application

int placement = 0x350100;ApplicationMenuItem ami = new ApplicationMenuItem(placement){ public Object run(Object context) { if (context instanceof Contact) { myContact = (Contact)context; //do something with the contact info } return null; } public String toString() { return "Loan Book"; }};

//register the menu item to display when the user views a contactApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance();amir.addMenuItem(ApplicationMenuItemRepository.MENUITEM_ADDRESSCARD_VIEW, ami);

Find out more

For more information about creating custom menu items, visit the following resources:

• Application Integration category overview, in the API reference for the BlackBerry® Java® SDK• BlackBerry Java SDK Integration Development Guide

Adding application iconsThe Home screen of the BlackBerry® device is the most visible and most accessed area for the BlackBerry device user.You can provide quick and easy access to your application by adding an icon to the Home screen. When the userclicks the icon, your application is launched. For added visual appeal, you can create a rollover effect for the icon,where the icon changes when the icon receives focus.

Development Guide Adding application icons

31

You can add an application icon and specify rollover effects by changing the properties for the application project inthe BlackBerry® Java® Plug-in for Eclipse®. The application properties for the project are contained in theBlackBerry_App_Descriptor.xml file. For more information about changing project properties, see the BlackBerryJava Plug-in for Eclipse Development Guide.

For further integration, you can customize the icon to change dynamically based on the state of the application. Forexample, a weather application icon can change based on the weather forecast — a sun to indicate a sunny forecastor rain drops to indicate a rainy forecast. Using a state type icon allows the user to see the most relevant information.If the user wants further details, they can simply click the icon to launch the app. This sort of customized icon isrelated to making your application proactive and notification-driven. For information about creating a dynamic icon,see the Proactive and notification-driven chapter.

Find out more

For more information about creating custom menu items, visit the following resources:

• Create an icon for an application BlackBerry Developer Knowledge Base article• UI Guidelines for BlackBerry Smartphones

Customizing the Phone screenYou can integrate your application with the Phone application by customizing the call screens to display informationfrom your application on the Incoming call and the Active call screens. For example, information that is provided bythe Bookshelf application can be displayed when a BlackBerry® device user receives a call from a fellow Bookshelf user.

You can customize the call screens on BlackBerry devices that are running BlackBerry® Device Software 5.0 or laterby using the Phone Screen API that is provided in the net.rim.blackberry.api.phone.phonegui package.

The device displays the content on the lower part of the call screen. If multiple applications provide content for acall screen, the device displays each application's content in sequence for approximately two seconds until the nextcall screen appears. For example, if you display content on the incoming call screen, the device displays the contentuntil the user answers the call and the active call screen appears.

Development Guide Customizing the Phone screen

32

Code sample: Customizing the incoming call screen

public void callIncoming(int callId){ ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING); LabelField labelField = new LabelField("Loaned book") { public void paint(Graphics g) { g.setColor(44504); super.paint(g); } }; labelField.setFont(phoneScreenPortrait.getCallerInfoFont()); phoneScreenPortrait.add(labelField); screenModel.sendAllDataToScreen();}

Find out more

For more information about displaying content on the phone screen, visit the following resources:

• net.rim.blackberry.api.phone.phonegui package overview• UI Guidelines for BlackBerry Smartphones• BlackBerry® Java® SDK Integration Development Guide

Embedding UI componentsThere are a number of specialized UI components that core applications on the BlackBerry® device use. You canintegrate these UI components in your application to provide users with a familiar and seamless experience on theirBlackBerry device. Below are some examples of UI components that you can integrate into your application:

Development Guide Embedding UI components

33

Component Description

AutoCompleteField You can use the AutoCompleteField class to compare the text that a user typesin the field against the items in a data source, and display the matches in a drop-down list below the field. The data source can retrieve information from otherapplications (for example, names from the Contacts application), or usecustomized information (for example, days of the week).

LocationPicker You can use the LocationPicker class to give users the ability to select alocation by using sources such as contacts from the Contacts application, GPScoordinates, recent locations, and suggestions from applications.

FilePicker You can use the FilePicker class to provide users with the ability to select afile by navigating to a folder.

MapField You can use the MapField class to embed a map in your application.BrowserField You can use the BrowserField class to embed web content in your application.Media fields injavax.microedition.media andjavax.microedition.media.control

You can use the media fields to embed media players and media recorders inyour application by using the Mobile Media API (JSR 135).

Code sample: Creating an AutoCompleteField UI component

BasicFilteredList filterList = new BasicFilteredList();String[] days = {"Fiction","Biography","History", "Non-fiction"};filterList.addDataSet(1,days,"days",BasicFilteredList.COMPARISON_IGNORE_CASE);AutoCompleteField autoCompleteField = new AutoCompleteField(filterList);add(new LabelField("Choose a book type:"));add(autoCompleteField);

Find out more

For more information about embedding UI components, visit the following resources:

Development Guide Embedding UI components

34

• UI Guidelines for BlackBerry Smartphones• BlackBerry® Java® SDK UI Component Quick Reference Guide• BlackBerry Java SDK UI and Navigation Development Guide• BlackBerry Java SDK Integration Development Guide

Development Guide Embedding UI components

35

Social and connected 5A Super App makes it easy for people to build relationships. The most frequently used applications can help peopleshare their experiences, data, and media with others. For example, an application could help an insurance salespersonretrieve key account details for a client during a meeting, or take a picture of a new item to be added to a policy. Ina personal context, an application could help someone coordinate a social event with friends, and share the memoriesfrom that event. When your app helps people interact, you make it easy for them to build relationships.

What are the benefits of a social and connected application?• Create personal and professional connections between users. When users use your app to share or enrich their

experiences, your app helps them create meaningful connections and encourages them to continue to use yourapp in the future.

• Share experiences as they happen. Life happens quickly, and your app can be there to help users capture andshare the moments that matter the most.

Approaches to connecting

Approach Examples

Deliver timely and relevant informationthrough the BlackBerry® Push Service. In acorporate environment, you can sendpush messages through the BlackBerry®Enterprise Server.

• An application that reports sports information can push scoresand news from games as they become available.

• A weather application can update weather information when itis published, so that the application always has the most currentinformation.

• The manager of an airport baggage system could receive updatesabout flight arrivals and departures through the airport'sBlackBerry Enterprise Server.

Fetch additional information for a userfrom web sites and social networkingservices using the Communication API(BlackBerry® 6 and later), or the NetworkAPI (BlackBerry® Device Software 5.0 andlater).

• A weather application that receives the basic details of theforecast through a push message could download satelliteimages before the user views the forecast.

• A social networking application could synchronize contact listsbetweeen a BlackBerry device and the web service.

Send application data between BlackBerrydevices using the BlackBerry® MessengerSocial Platform SDK.

• A personal health management application can collect and sendinformation about the medications a patient takes.

• A media player application can report the current song, image,or video that a user is enjoying.

Capture and share pictures, audio, andvideo.

• An event management application can capture images and othermedia from an event, and automatically share that them throughthe BlackBerry® Messenger Social Platform, or another socialnetwork.

Development Guide Social and connected

36

Approach Examples

Enable people to discover informationabout their environment by scanning one-dimensional and two-dimensional barcodes.

• An application could facilitate city-wide scavenger hunts whereusers had to find and scan QR codes to receive clues about whereto go next.

The detailsThe following examples demonstrate some of the features of the BlackBerry® Application Platform that enable socialfeatures. By the end of the chapter, the Bookshelf app will communicate with the Bookshelf web service to send anotification of a book released to the community of application users, and retrieve information from the web serviceabout books that have been released.

Releasing a bookTo release a book for other users, Bookshelf communicates a book's identity and location to the Bookshelf webservice. However, if the book is hidden in a public place, a person might not find it using the location informationalone. Bookshelf should also allow the user who releases the book to add more information about the location ofthe book in the form of text, images, audio, or video.

To identify a specific copy of a book, a user generates a QR code for the book from the web service's web interface.The user could then print and attach the QR code to the book. Anyone who picks up the book in the future couldscan the code to add the book to their list. Once the book is added to their list, the user could then retrieve the historyof that copy of the book, and add their comments to the history of the book.

The following code samples demonstrate how to capture images, audio, or video, and open a network connectionto send this information to the Bookshelf web service. For more information about retrieving the location of theBlackBerry® device, see the Highly contextualized chapter.

Capturing media

You can enable a user to capture audio, video, and images using the javax.microedition.media.Player class.

Capture audio

The following code sample demonstrates how to create a Thread to instantiate a Player object and specify audiorecording parameters. You can invoke this thread from your user interface to start and stop the recording.

private class AudioRecorderThread extends Thread implements javax.microedition.media.PlayerListener{ private Player _player; private RecordControl _recordControl;

AudioRecorderThread() { }

Development Guide The details

37

public void run() { try { _player = javax.microedition.media.Manager.createPlayer ("capture://audio?encoding=audio/amr");

_player.addPlayerListener(this);

_player.realize(); _recordControl = (RecordControl) _player.getControl( "RecordControl" ); _recordControl.setRecordLocation ("file:///store/home/user/AudioRecordingTest.amr"); _recordControl.startRecord(); _player.start(); } catch( IOException e ) { Dialog.alert(e.toString()); } catch( MediaException e ) { Dialog.alert(e.toString()); } }

public void stop() { if (_player != null) { _player.close(); _player = null; }

if (_recordControl != null) { _recordControl.stopRecord(); try { _recordControl.commit(); } catch (Exception e) { Dialog.alert(e.toString()); } _recordControl = null; }

public void playerUpdate(Player player, String event, Object eventData) { Dialog.alert("Player " + player.hashCode() + " got event "

Development Guide The details

38

+ event + ": " + eventData); }}

Find out more

For more information about recording audio, visit the following resources:

• BlackBerry® Java® SDK Multimedia Development Guide

Capture video

The following code sample demonstrates how to create a Thread to instantiate a Player object and specify videorecording parameters. You can invoke this thread from your user interface to start and stop the recording.

private class VideoRecorderThread extends Thread implements javax.microedition.media.PlayerListener{ private Player _player; private RecordControl _recordControl;

VideoRecorderThread() { }

public void run() { try { _player = javax.microedition.media.Manager.createPlayer ("capture://video?encoding=video/3gpp");

_player.addPlayerListener(this);

_player.realize(); VideoControl videoControl = (VideoControl) _player.getControl ("VideoControl"); _recordControl = (RecordControl) _player.getControl( "RecordControl" );

Field videoField = (Field) videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");

try { videoControl.setDisplaySize(Display.getWidth(), Display.getHeight()); } catch( MediaException me ) { // setDisplaySize is not supported } add(videoField);

_recordControl.setRecordLocation ("file:///store/home/user/VideoRecordingTest.3gpp" );

Development Guide The details

39

_recordControl.startRecord(); _player.start(); } catch( IOException e ) { Dialog.alert(e.toString()); } catch( MediaException e ) { Dialog.alert(e.toString()); } } public void stop() { if (_player != null) { _player.close(); _player = null; }

if (_recordControl != null) { _recordControl.stopRecord(); try { _recordControl.commit(); } catch (Exception e) { Dialog.alert(e.toString()); } _recordControl = null; } }

public void playerUpdate(Player player, String event, Object eventData) { Dialog.alert("Player " + player.hashCode() + " got event " + event + ": " + eventData); } }}

Find out more

For more information about recording video, visit the following resources:

• BlackBerry® Java® SDK Multimedia Development Guide

Development Guide The details

40

Capture images

The following code sample extends the MainScreen class to create a viewfinder to capture images. You can presentthis screen to a user when they are ready to capture an image, and retrieve the image from the _rawImage variable.

class ImageCaptureDemoScreen extends MainScreen{ Player _p; VideoControl _videoControl; byte[] _rawImage = null; public ImageCaptureDemoScreen() { try { _p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768"); _p.realize(); _videoControl = (VideoControl) _p.getControl("VideoControl");

if (videoControl != null) { Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field"); _videoControl.setDisplayFullScreen(true); _videoControl.setVisible(true); _p.start();

EnhancedFocusControl efc = (EnhancedFocusControl)p.getControl("net.rim.device.api.amms.control.camera.EnhancedFocusControl"); efc.startAutoFocus();

if(videoField != null) { add(videoField); } } } catch(Exception e) { Dialog.alert(e.toString()); } }

protected boolean invokeAction(int action) { boolean handled = super.invokeAction(action); if(!handled) { if(action == ACTION_INVOKE) { try { _rawImage = _videoControl.getSnapshot(null);

Development Guide The details

41

} catch(Exception e); { Dialog.alert(e.toString()); } } } return handled; }

public byte[] getImage() { if(_rawImage != null) { return _rawImage; } else { return byte[0]; } }}

Send data to an HTTP server

After the application user has captured some media to share, you can send that data to an HTTP server by using theCommunication API. The following code sample demonstrates how to send an image captured by the camera.

import net.rim.device.api.io.messaging.*;import net.rim.device.api.io.URI;

class SubmitPicture {

private static UiApplication _app = UiApplication.getUiApplication(); private String _result;

public SubmitPicture(byte[] picture) { Thread t = new Thread(new Runnable() { public void run() { Message response = null; String uriStr = "http://bookshelfwebservice/releaseBook?addPic"; BlockingSenderDestination bsd = null; try { bsd = (BlockingSenderDestination) DestinationFactory.getSenderDestination ("CommAPISample", URI.create(uriStr)); if(bsd == null) { bsd = DestinationFactory.createBlockingSenderDestination

Development Guide The details

42

(new Context("CommAPISample"), URI.create(uriStr) ); }

ByteMessage pictureMsg = bsd.createByteMessage(); pictureMsg.setBytePayload(picture) ((HttpMessage) pictureMsg).setMethod(HttpMessage.POST);

// Send message and wait for response response = bsd.sendReceive(pictureMsg);

if(response != null) { BSDResponse(response); } } catch(Exception e) { // process the error } finally { if(bsd != null) { bsd.release(); } } }

}); t.start(); } }

private void BSDResponse(Message msg) { // process return message: picture accepted or picture rejected }

}

Finding a bookTo help a user find books that have been released by others, Bookshelf needs to communicate with the Bookshelfweb service about the current location of the user's BlackBerry® device. Bookshelf can use location information tonotify the user if there is a book nearby. Book sharing is one way a Bookshelf keeps users connected to each otherand the application.

Acquiring the location of the device can consume a lot of battery power. There are several strategies to use batterypower efficiently in this scenario. The following table discusses three of those strategies.

Development Guide The details

43

Strategy Description

Schedule an application to runperiodically.

The ApplicationManager.scheduleApplication() methodrequests that the BlackBerry device runs an application at a particulartime. Each time Bookshelf runs to retrieve the current location of thedevice, it can request that the device run the app again at a later time.In this way, you can have your application run periodically rather thanuse memory and battery power on the device when the application isnot required.

For more information, see the Always on chapter.Start with a cell-tower position. To calculate the BlackBerry device's location, the GPS receiver must scan

the sky for satellites. This part of acquiring location informationconsumes the most battery power.

In some cases, you can find the device's approximate location from thecell tower to which the device has a wireless connection. This strategyrequires significantly less battery power than using the GPS receiver.

Bookshelf can then submit the location to the Bookshelf web service,which will respond with any books located in that area. If you want toonly return books within a smaller area, you can then provide a morespecific list based on the particular location acquired by using GPS.

For more information, see the Highly contextualized chapter.Use message notifications. When a user installs Bookshelf, the application creates an

ApplicationMessageFolder. When Bookshelf discovers that a bookis nearby, the application can add a new message to theApplicationMessageFolder. By default, the message appears in theuser's Messages application. On devices running BlackBerry® 6 or later,the message will also appear in the Notifications tray on the Homescreen. This strategy is energy efficient because a user can review thedetails of a book before launching Bookshelf.

Bookshelf also implements ApplicationIndicator to display acustom icon for new message notifications. Instead of displaying a closedenvelope icon, the BlackBerry device displays a book icon.

For more information, see the Proactive and notification-driven chapter.

After a user has found a book, they can register their acquisition and join the community of people who have readthat copy of the book. To do so, they can scan the two-dimensional bar code that was attached by the person whoreleased the book.

Find out more

For more information about scanning bar codes, visit the following resources:

Development Guide The details

44

• How to use the Barcode API BlackBerry Developer Knowledge Base article

Development Guide The details

45

Proactive and notification-driven 6Proactive and notification-driven applications are fundamental to the BlackBerry® experience. Much of the successof BlackBerry devices was built upon the core BlackBerry applications with these qualities.

Consider the Messages application on the device. A distinguishing feature of this application is not just that you canreceive email anywhere, but that the content of the email is delivered to the device as soon as it is available, withno user intervention. A user doesn’t need to pull a message down from the messaging server to read it. When theserver receives an email message for a user, the server proactively “pushes” that message to the user’s device. TheMessages application listens in the background for messages to arrive and, upon receiving a new message, displaysa notification icon at the top of the screen.

The push model is largely responsible for helping to make BlackBerry devices so invaluable to their users. This samemodel can be applied to any application by using the BlackBerry® Push Service, which allows content developers tosubmit requests to push up to 8 KB of content to one or more BlackBerry devices.

Being proactive—getting information to the user as soon as it is avaliable and without the user requesting it—cantake your app from common to uncommonly useful, from app to Super App.

What are the benefits of a proactive and notification-driven application?• Use more efficient strategies than polling. Polling techniques waste battery power, since these techniques are

designed to regularly open a connection to check for new data, even when there is no new data available. Withpush technology, an application listens on a specified port number in the background for incoming push content.A network connection is only opened when new push content is available.

• Bring information directly to the user's attention. Once an app is registered to receive push content, the userdoes not need to do anything to transfer the content to the BlackBerry device. The app simply receives thecontent from the server, and only needs to notify the user when the content is available on the device.

• Deliver content in a timely manner. With push technology, content can be sent as soon as it is available. Typically,there is very little lag between the push content arriving at the server and being delivered to the device.

Approaches to notificationTo notify a BlackBerry® device user of an event, you can choose from a number of notification types. Some of thesenotifications are discreet, noticed only when the user is looking for them, and others are more overt. You can issuemultiple notifications for a single event.

The discoverability of the notification type, or types, should match the importance of the event to the user. For urgentevents, you may want to issue an audio notification or a vibration that immediately attracts the user's attention. Forless important events, you can use more discreet notification types. Regularly occurring events, for example, in anapp in which sports scores are pushed overnight, require only subtle notification—or no notification at all—since theuser has an expectation that the content will arrive around the same time each day.

Development Guide Proactive and notification-driven

46

Approach Example

Display a banner indicator. When a new message is pushed to the device, a small icon is displayed in theHome screen banner. You can customize the image so that it is specific toyour application.

Flash the LED indicator. When the daily sports scores are pushed to the device, the BlackBerry deviceLED flashes. You can customize the behavior of the LED notification. Forexample, you can configure the LED to flash a yellow light when the eventoccurs.

Play a sound. When a new text message arrives, a sound is played. You can use any of thedefault sounds that are available on the device, or provide your own customsounds.

Vibrate the BlackBerry device. When a stock you are monitoring reaches a specified value, the BlackBerrydevice vibrates.

Send an email or text message. When an update to an application is available, the application sends amessage to the Messages application. As a best practice, if you send amessage as a notification, you should also display a custom banner indicator,so that the user can see what type of message has arrived.

Display a popup dialog box. When a critical event occurs, the application displays a popup dialog box. Theuser must actively dismiss the dialog box. Because a popup dialog box is a UIelement, it is not appropriate for background notifications.

Display an alternate Home screenicon.

When new push content is available for an application, the application iconon the Home screen changes to an alternate image.

Understanding the BlackBerry Push ServiceBefore getting into the specifics of creating a push solution, it is helpful to understand the features and architectureof the BlackBerry® Push Service. The BlackBerry Push Service provides developers with access to the push technologyupon which much of the success of BlackBerry devices is built.

A push solution is made up of three main components:

Component Description

Push Proxy Gateway (PPG) The PPG is the middleware, specifically a push data server, within theBlackBerry® Infrastructure. The PPG is the main functional component of theBlackBerry Push Service, and is responsible for receiving push requests froma Push Initiator and delivering the content to the appropriate port on theBlackBerry device.

Push Initiator The Push Initiator is the server-side application. A Push Initiator takes thecontent that is to be pushed to users, packages it in a push request with a PAPcontrol entity (an XML document that contains the recipient addresses and

Development Guide Understanding the BlackBerry Push Service

47

Component Description

defines delivery parameters such as an expiry time or reliability level), andsubmits that push request to the PPG for delivery. In our scenario, theBookshelf web service plays the role of the Push Initiator.

Extending the Bookshelf web service to function as a Push Initiator is beyondthe scope of this guide. However, Research In Motion has provided theBlackBerry® Push Service SDK to help simplify the process of creating andsubmitting push messages.

Push-enabled app The push-enabled app is the client-side application that is installed on theBlackBerry device. A push-enabled app is an application that is designed tolisten on a specific port and receive incoming content that has been pushedto this port on the device. In our scenario, we’ll be extending the Bookshelfapp to become a push-enabled app.

Be aware that to create a push solution, you must first register your solution with the BlackBerry Push Service. Whenyou register, you will receive an Application ID for your push solution, which is used to associate your Push Initiatorwith your push-enabled application.

Find out moreFor more information about pushing content, visit the following resources:• BlackBerry Push Services web page• BlackBerry Push Service SDK Development Guide

Making Bookshelf a push-enabled applicationTo listen for and receive push content, a push-enabled application must:

• Implement the MessageListener interface• Create and send a subscription message, to inform the Push Initiator and the BlackBerry® Push Service that the

application is present on the BlackBerry device, and is a valid address for push content sent from this PushInitiator

• Issue a notification to the user when new content arrives

In addition, to ensure that the application is always ready to receive push content while the BlackBerry device is on,we'll need to create an alternate entry point for Bookshelf. This entry point runs a background process automaticallywhen the BlackBerry device turns on but does not display the UI, allowing Bookshelf to receive and process pushcontent as it arrives. See the Always on chapter for more information on setting up an alternate entry point.

Implement the MessageListener interface

1. Import the required classes and interfaces.

Development Guide Making Bookshelf a push-enabled application

48

import net.rim.device.api.io.messaging.*; import java.io.IOException; import java.io.InputStream;

2. Define a class that implements the MessageListener interface.

public class MyMessageListener implements MessageListener {

3. Implement onMessage().

public void onMessage(Destination dest, Message incomingMessage) {

4. Initialize a String variable (in this sample, called payload) to hold the response data.

String payload = null;

5. If the response is a ByteMessage object, retrieve the response as a String and assign it to payload.

if (incomingMessage instanceof ByteMessage) { ByteMessage reply = (ByteMessage) incomingMessage; payload = (String) reply.getStringPayload(); }

6. If the response is a StreamMessage object, retrieve the response as an InputStream object.

else if(incomingMessage instanceof StreamMessage) { StreamMessage reply = (StreamMessage) incomingMessage; InputStream is = reply.getStreamPayload();

a. If the response is small, convert the contents of the stream into a byte array.

byte[] data = null; try { data = net.rim.device.api.io.IOUtilities.streamToBytes(is); } catch (IOException e) { // process the error }

b. If the conversion was successful, convert the byte array to a String and assign it to payload.

if(data != null) { payload = new String(data); } }

7. If payload contains data, issue a notification to alert the BlackBerry® device user about the newly arrivedcontent.

Development Guide Making Bookshelf a push-enabled application

49

if(payload!=null) { updateIndicator( 1 ); }

8. Implement onMessageCancelled() and onMessageFailed().

Subscribe to the Push Initiator

1. Import the required classes and interfaces.

import net.rim.device.api.io.messaging.*;

2. Initialize a NonBlockingReceiverDestination variable to manage the subscription.

NonBlockingReceiverDestination nbrd = null;

3. Create a MessageListener object to process incoming push content.

try{ MyMessageListener pushListener = new MyMessageListener();

4. Create a URI object that specifies the port number that the application listens on.

URI pushURI = URI.create("http://:101");

5. Create an InboundDestinationConfiguration object to set parameters for the push subscription.

InboundDestinationConfiguration config = InboundDestinationConfigurationFactory.createBPSConfiguration (false, // don't start this application when a push message arrives false, // allow other applications to receive these push messages false, // do not store these messages (persistence not supported) "12-Ab234cD5eF67h890", // application ID, BPSuri); // BlackBerry Push Service URI

6. Create a NonBlockingReceiverDestination object that specifies theInboundDestinationConfiguration object that defines the parameters for the push subscription, the portnumber on which the app listens, and the MessageListener object responsible for receiving and processingthe incoming push content.

nbrd = DestinationFactory .createNonBlockingReceiverDestination (config, pushURI, pushListener);

7. Create a NonBlockingSenderDestination object to send a subscription message.

NonBlockingSenderDestination bpsDestination = DestinationFactory.createNonBlockingSenderDestination (myContext, uri, responseListener);

8. Build the subscription message.

Development Guide Making Bookshelf a push-enabled application

50

ByteMessage subMsg = BpsSubscriptionMessageBuilder.createByteSubscriptionMessage (bpsDestination, nbrd, "user", "pwd");

9. Send the subscription message.

bpsDestination.send();

Update the banner indicator

1. Import the required classes and interfaces.

import net.rim.blackberry.api.messagelist.*;import net.rim.device.api.system.EncodedImage;

2. Obtain a reference to an ApplicationIndicatorRegistry object.

ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();

3. Create an indicator based on an encoded image by invoking EncodedImage.getEncodedImageResource() and passing in the file name as an argument. Save a reference to the encoded image in an EncodedImagevariable. Create an instance of the ApplicationIcon class using the EncodedImage as an argument.

EncodedImage image = EncodedImage.getEncodedImageResource("BookShelf-Icon-notification-32x32.png" );ApplicationIcon icon = new ApplicationIcon( image );

4. Register the image as an application indicator by invoking ApplicationIndicatorRegistry.register(). In the following code sample, the second parameter specifies that the indicator can have a numeric valueassociated with it (for example, new message count). The third parameter specifies that the indicator should bevisible.

ApplicationIndicator indicator = reg.register( icon, true, true);

5. Retrieve the registered indicator by invokingApplicationIndicatorRegistry.getApplicationIndicator(). Save the return value in anApplicationIndicator variable.

ApplicationIndicator appIndicator = reg.getApplicationIndicator();

6. Set the image and value for the indicator by invoking ApplicationIndicator.set(). You should consideronly showing a value if it is greater than 0.

appIndicator.set( newIcon, newValue );

Development Guide Making Bookshelf a push-enabled application

51

Efficient 7The other chapters in this guide describe how to implement five of the features and characteristics of Super Apps inyour application. For BlackBerry® device users to enjoy using your application on a daily basis and recommend it toothers, you should implement these features efficiently.

An efficient application takes into consideration the limited resources of a mobile device, such as processor power,battery life, and memory, and uses these resources as effectively as possible. An efficient application doesn't consumebattery power too quickly, open unnecessary network connections that might increase a user's wireless data charges,or make the UI on the BlackBerry device sluggish or unresponsive.

Remember that users don't usually report or provide feedback on performance issues with applications; they typicallydelete these applications from their devices. For this reason, it's important to focus on creating efficient Super Apps.

What are the benefits of an efficient application?• Increase battery life. A longer battery life means that users can spend more time using your application and

less time charging their devices or searching for applications to remove to improve performance (includingyours!).

• Improve response times. Efficient applications can respond quickly to a user's input, which means less waitingon the user's part and more potential for productivity.

• Reduce data costs. Users don't want to see an increase on their bill from their wireless service provider becauseyour application is transferring data unnecessarily. If your application transfers very little data while it's in use,your users are more likely to continue to use your application and recommend it to others.

• Increase the "stickiness" of your application. A "sticky" application is one that a user sticks with, that engagesthe user, that the user comes back to over and over again. By focusing on efficiency when you design yourapplication, you can improve your user's experience and help increase the stickiness of your application.

Approaches to efficient application designYou can help make your application efficient by using any of the following approaches.

Approach Examples

Be aware of the status of theBlackBerry® device (such as batterypower level, network connectivity,and so on) and respond accordingly.

• If your application is designed to download songs or videos from awebsite, your application should stop downloading content if thebattery level or available memory on the device is low.

• Download large files only when the device is connected to a Wi-Fi®network.

Eliminate or defer unnecessaryprocessing on the device.

• If your application needs to perform complex calculations, performthese calculations when the device is idle.

• Have data such as news items, status updates, or other data pushedto the device periodically instead of having the device poll to retrievethe data.

Development Guide Efficient

52

Approach Examples

Use location services, such as GPSand geolocation, carefully.

• If your application needs to obtain a GPS fix, perform full scans of thesky to locate satellites for the fix only when necessary.

• Use assisted GPS mode sparingly.Use the Profiler tool to optimize yourcode.

• Find out what methods in your application take the most time to run,and try to optimize these methods.

• Determine how many objects your application creates while it'srunning, and try to reduce this number if possible.

Responding to the status of the deviceThe Highly contextualized chapter describes how to consider the contexts (such as battery, connectivity, and devicecharacteristics) that are associated with BlackBerry® devices. When you design your application, the monitoring ofcertain contexts, or states, of the device can help your application be more efficient while also providing anexceptional user experience. Your application can detect states such as low battery level, poor wireless coverage,and Wi-Fi® connectivity to increase efficiency.

You can change the behavior of your application in response to state changes. For example, the Bookshelf applicationcommunicates with a web service that provides information about books that have been released. If Bookshelfdetects that the device is connected to a Wi-Fi network, Bookshelf can use the bandwidth that the Wi-Fi connectionprovides to request more detailed information about a book, such as cover art, audio clips, and extended synopses.

Using listeners

One of the most effective ways to respond to state changes on a device is by using listeners. You can register yourapplication as a listener for different types of events. You might want your application to close automatically if thebattery level reaches a certain point, or to provide different options if the device is connected to a computer usinga USB connection. You can also use listeners to monitor global events on the device and use these global events tocommunicate between processes.

To be enabled as a listener, your application must implement one or more listener interfaces (for example,CoverageStatusListener or GlobalEventListener). The following table describes some common listenerinterfaces and the events that they listen for.

Interface Description

SystemListener2 You can use this listener to listen for system events, such as changes to thestate of the backlight or changes to the state of the USB connection.

GlobalEventListener You can use this listener to listen for global events, such as changes to thetime zone or events that are associated with interprocess communication.

CoverageStatusListener You can use this listener to listen for changes to wireless transports, suchas HTTP over WAP or the BlackBerry® Mobile Data System.

WLANConnectionListener You can use this listener to listen for changes to Wi-Fi connectivity.

Development Guide Responding to the status of the device

53

Interface Description

LowMemoryListener You can use this listener to determine when the amount of availablememory is low.

If you choose to use listeners in your application, it's important to remember to deregister the listeners that you usewhen you are done with them. If you don't deregister a listener, a reference to the listener remains in memory onthe device, and your application is not properly terminated.

You can create your own listeners if the ones that are provided in the BlackBerry APIs don't suit your needs. Thisapproach might be a good way to improve the efficiency of your application. A listener that you create yourself mightbe more focused or specialized for your application's functionality than a generic listener. For example, a listenerthat is designed for the Bookshelf application might listen specifically for events that are generated by the Bookshelfweb service, such as when new information about a book's location is available.

Checking the status of the device

Your application can check the status of the device before trying to perform a particular action. For example, youcan invoke DeviceInfo.getBatteryLevel() or DeviceInfo.getBatteryStatus() before you start yourapplication, to determine if there is sufficient battery power remaining to run your application or to perform a lengthyoperation. You can also invoke DeviceInfo.getIdleTime() to determine how long the device has been idle,which is useful when you want your application to perform complex or time-consuming operations when the useris not using the device.

If your application must open a network connection, your application should check the network coverage that isavailable. If coverage is poor, your application uses more battery power to use the wireless transceiver on the device,and a more efficient approach might be to wait until coverage improves to open the connection. Alternatively, youcan design your application to retrieve a smaller, lower-quality set of data immediately, and then wait until coverageimproves or a Wi-Fi connection is available to retrieve the full set of data. You can invokeRadioInfo.getSignalLevel(), CoverageInfo.isCoverageSufficient(), orTransportInfo.hasSufficientCoverage() to help you determine the available network coverage.

You should also consider whether an IT policy rule that is set by a BlackBerry® Enterprise Server administrator mightblock a feature of the device that your application is trying to use. For example, if the Disable GPS IT policy rule isapplied to the device, your application won't be able to obtain a GPS fix and should not waste resources trying to doso.

Code sample: Listening for status changes to the wireless coverage

The following code sample demonstrates how you can listen in your application for status changes to the wirelesscoverage. Your application can respond and stop transferring data or communicating with a server or web service.

public class MyApplication extends UiApplication implements CoverageStatusListener{ // class constructor public MyApplication() {

Development Guide Responding to the status of the device

54

// ... }

public void coverageStatusChanged(int newCoverage) { // respond to the change in coverage }

// ...}

Code sample: Setting a listener when the backlight changes

The following code sample demonstrates how you can set a listener in your application when the backlight changeson the device. If the backlight is off, your application doesn't need to respond to any events, and you don't need toset a listener for the screen. If the backlight is on, your application can resume listening for events.

// override backlightStateChange() of the SystemListener2 interfacepublic void backlightStateChange(boolean on){ if (screen != null) { if (on) { // set the Screen object of your application to listen for events from // your application MyApplication.getInstance().setListener(screen); } else { MyApplication.getInstance().setListener(null); } }}

Code sample: Detecting a low battery level on a device that is not charging

The following code sample demonstrates how you can detect a low battery level on a device that is not charging. Ifthis situation occurs, you might want to close your application automatically or stop using GPS.

private boolean batteryLowNotCharging(){ int batteryStatus = DeviceInfo.getBatteryStatus(); if ((batteryStatus & DeviceInfo.BSTAT_LOW) != 0) { if ((batteryStatus & DeviceInfo.BSTAT_CHARGING) == 0) { return true; }

Development Guide Responding to the status of the device

55

} return false;}

Find out more

For more information about device status and network connections, visit the following resources:

• Device Characteristics and the BlackBerry Infrastructure category overview, in the API reference for theBlackBerry® Java® SDK

• BlackBerry Java SDK Network Communication Development Guide

Eliminating unnecessary processing on the deviceThe Always on chapter describes how to keep your application running in the background on a BlackBerry® device,as well as how to schedule processes to run periodically. When you implement these approaches correctly, you buildefficiency into your application by choosing when and how often to perform processing.

You can help make your application efficient by minimizing the amount of processing that you need to do in yourapplication, and eliminating any processing that might not be necessary at a given time. For example, the Bookshelfapplication doesn't need to check the Bookshelf web service continuously for updates to the information about abook. A book's information doesn't change very often, so it might be more efficient to use a push solution to sendthe updates to Bookshelf when the information is updated.

Running in the background

You should only run your application in the background if it makes sense to do so. Running your application in thebackground lets your application continue to process data and provide updates to the BlackBerry device user, evenwhen the user is using other applications on the device. However, running in the background can consume valuablesystem resources and battery power. There are alternatives to running your application in the background:

• You can push important information or updates to your application from an external source, such as a webserver. Your application doesn't need to be running in the background to receive push notifications. When pushdata arrives on the device, if your application is registered as a push handler, your application processes thedata automatically.

• You can schedule processes to run periodically. Your application can perform resource-intensive operations atspecific times so that your application doesn't run continuously.

When your application must perform tasks in the background, you can save battery power by making sure that yourapplication does its processing all at once, instead of spread out over a long period of time. The device can enter alow-power mode when processing is complete to minimize power consumption. You should also avoid opening manyseparate network connections to transfer small amounts of data. Instead, you should design your application to waituntil there is a significant amount of data to transfer, and then open a single connection and transfer all of the dataat once.

Detecting when your application is not displayed

Development Guide Eliminating unnecessary processing on the device

56

If your application includes any animations or contains code that repaints the screen at regular intervals, you cansave a substantial amount of battery power by not redrawing UI elements if your application is running but notdisplayed, or if your application is not in use. You can use the following methods to determine if your application isin use:

• You can use methods to stop animating or repainting the screen when the screen is not visible, and resumewhen the screen is visible again. You can override Screen.onExposed(), which is invoked when yourapplication's screen is on top of the display stack and displayed to the user. You can overrideScreen.onObscured(), which is invoked when your application's screen is not displayed to the user or isobscured by another screen.

• To determine if your application is in the foreground, you can invoke Application.isForeground(). If thismethod returns false, your application is not visible to the user.

• To determine if the backlight on the device is turned on, you can invoke Backlight.isEnabled(). If thismethod returns false, no UI elements are visible to the user. The backlight turns off automatically after a periodof inactivity. Your application should not keep the backlight on unless the device is connected to a charger, orif screen visibility is critical to the application.

• To determine how long the device has been idle, you can invoke Device.getIdleTime(). To prevent anypotential UI lag or latency, your application should perform processor-intensive operations when the device isidle.

Find out more

For more information about pushing content to devices, visit the following resources:

• BlackBerry® Push Service SDK Development Guide

Using location services effectivelyThe Highly contextualized chapter describes how location is an important context to consider when you're designingyour application. You can use GPS technology on the BlackBerry® device to add this context to your application, butyou should remember that obtaining GPS fixes can consume a lot of battery power.

You can help make your application efficient by making effective use of location services on the device, such as GPSand geolocation. For example, the Bookshelf application should notify BlackBerry device users when they are in thearea of a released book. Because maintaining a GPS fix at all times can consume battery power, Bookshelf mightobtain a GPS fix only periodically, with an option for more frequent fixes that the user can select. Bookshelf mightalso use the geolocation service to obtain the general position of the user until a more precise GPS fix is calculated.

Obtaining GPS fixes that are timely and necessary

In general, the most battery-intensive operation when your application uses GPS on a device is performing a full scanof the sky. A full scan of the sky involves locating and connecting to GPS satellites and obtaining a GPS fix using theinformation from those satellites. An application that performs full scans frequently can drain the battery very quickly.To avoid this situation, your application should perform a full scan to obtain GPS fixes only as often as required toprovide a good user experience. For example, your application might not need to maintain the user's exact position

Development Guide Using location services effectively

57

at all times, but instead can provide a good user experience if the application obtains a fix every ten minutes. If yourapplication needs to track the user's position more precisely, you can decrease the time between fixes, at the costof increased battery usage.

If your application cannot obtain a GPS fix, you should consider carefully whether to retry the request. For example,if your application hasn't been able to obtain a fix for the last 30 minutes, it might be because the user is indoors,and your application shouldn't retry the request. Your application might also reduce the frequency of fix requestsuntil a fix is successful.

Your application should use assisted GPS mode sparingly. Assisted GPS mode obtains a GPS fix by communicatingwith the wireless service provider to retrieve satellite information. This method provides a fix very quickly andconsumes less battery power than other GPS modes, but it relies on the wireless service provider and increases theircosts, as well as any network costs that are associated with communicating with the wireless service provider. Youshould design your application to use assisted GPS mode to obtain an initial fix before switching to autonomous GPSmode. If you want your application to obtain a fix using a particular GPS mode (for example, assisted GPS orautonomous GPS), your application should check to see if that mode is available by invokingGPSInfo.isGPSModeAvailable().

Using the geolocation service to obtain an approximate location

As an alternative to using GPS on a device, you can use the geolocation service to retrieve the location of the device.The geolocation service provides an approximate location (within 200 meters to 5 kilometers) and includes thelatitude, longitude, and horizontal accuracy based on the positioning of cell towers and WLAN access points. If yourapplication doesn't require the user's exact position, the geolocation service can be an excellent approach and cansave substantial amounts of battery power. The geolocation service can also function indoors, making it feasible touse in applications that don't always have access to GPS satellites (for example, applications that recommend localpoints of interest).

Code sample: Using the geolocation service to obtain an approximate location

The following code sample demonstrates how to use the geolocation service to retrieve the approximate locationof the device.

// specify the geolocation modeBlackBerryCriteria myBlackBerryCriteria = new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE);

// retrieve a location providerBlackBerryLocationProvider myBlackBerryProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myBlackBerryCriteria);

// request a single geolocation fixBlackBerryLocation myBlackBerryLoc = myBlackBerryProvider.getLocation(timeout);

// retrieve the geolocation of the device

Development Guide Using location services effectively

58

double lat = myBlackBerryLoc.getQualifiedCoordinates().getLatitude();double lng = myBlackBerryLoc.getQualifiedCoordinates().getLongitude();double lat = myBlackBerryLoc.getQualifiedCoordinates().getAltitude();

Find out more

For more information about GPS and location-based services, visit the following resources:

• Location-Based Services (LBS) category overview, in the API reference for the BlackBerry® Java® SDK• BlackBerry Java SDK Location-Based Services Development Guide

Using the Profiler toolThis chapter describes best practices for making your application more efficient. This chapter describes how torespond to the status of the BlackBerry® device, minimize or eliminate unnecessary processing in your application,and use GPS effectively to save battery power. You should also consider code-level efficiency when you're designingyour application. You can make sure that the methods in your application run as quickly and efficiently as possible,don't create too many objects, and don't commit too many objects to memory on the device. For example, if theBookshelf application creates a new object every time the application receives new location information for a bookfrom the Bookshelf web service, Bookshelf probably isn't using objects as efficiently as it could. It might be moreefficient to update the same object each time with new information.

You can use the Profiler tool to analyze and optimize your code for efficiency. The Profiler tool is available in theBlackBerry® Java® Development Environment or the BlackBerry® Java® Plug-in for Eclipse®. You can use the Profilertool to identify what threads are running at any point in the execution of your application, how long methods taketo run, how many objects your application creates, and so on.

When you're using the Profiler tool to analyze your code, the values that you obtain (for example, execution time inclock ticks or execution time in milliseconds) are most useful when considered relative to each other. For example,the number of clock ticks that one method takes to run isn't necessarily relevant, because this number can varydepending on factors such as device model, number of other applications running simultaneously, whether themethod is running on a device or on a simulator, and so on. Instead, the comparison of the number of clock ticksthat two methods that perform the same function take is more useful, and you can use this data to determine whichmethod is more efficient.

In general, you shouldn't try to reduce profiler metrics individually. Instead, you should use these metrics to helpidentify areas of inefficiency in your application. You can also use profiler metrics to identify bottlenecks in yourapplication's execution, and determine the best places to try to optimize your code.

You should try to optimize the methods in your application that run the most frequently, such as implementationsof methods that open and manage network connections and methods that draw UI elements (for example,Screen.paint(), Screen.paintBackground(), and FullScreen.sublayout()).

The following table lists some of the metrics that you can monitor by using the Profiler tool.

Development Guide Using the Profiler tool

59

Metric Description

Time spent in methods You can determine the percentage of application execution time that wasspent in each method in your application. If you have two methods thatperform similar tasks, but one method takes substantially less time to run,you should examine the methods for opportunities to optimize the slowermethod.

You can perform this type of profiling on a BlackBerry Smartphone Simulatoronly.

Samples You can determine what your application is doing at any point duringexecution. Approximately every ten milliseconds, the Profiler tool queriesyour application, and your application responds with a stack trace (asample). The higher the number of samples for a method, the longer thatmethod is taking to run. If a method produces a large number of samplesrelative to other methods in your application, this method might be acandidate for optimization.

You can perform this type of profiling on both a BlackBerry SmartphoneSimulator and a device.

Objects created You can determine how many objects your application creates duringexecution. Object allocation and garbage collection are the primary reasonsfor UI lag or latency in an application, so if a method creates a large numberof objects relative to other methods in your application, you should examinethe objects to determine if they are all required. Your application shouldreuse objects whenever possible.

You can perform this type of profiling on a BlackBerry Smartphone Simulatoronly.

Objects committed You can determine how many objects your application writes to memoryon the device during execution. Committing objects to memory is anexpensive operation (in terms of execution time), so you should minimizethese operations whenever possible. If your application must commitobjects to memory, make sure that the objects are grouped so that theycan be committed at the same time, instead of individually. Your applicationshould also commit objects at the end of a full transaction or event.

You can perform this type of profiling on a BlackBerry Smartphone Simulatoronly.

Find out more

For more information about the Profiler tool, visit the following resources:

• BlackBerry Java Plug-in for Eclipse Development Guide

Development Guide Using the Profiler tool

60

Storing data on the deviceThe Social and connected chapter describes how to capture audio and video in your application by using thejavax.microedition.media.Player class. In the code samples in that chapter, the audio and video files arestored in internal storage on the BlackBerry® device by specifying a record location of file:///Store/... Youcan choose from several data storage options to store data or files that your application creates. Each storage optionhas advantages and disadvantages, and you should carefully consider which option to use based on the type of datathat your application needs to store.

You can help make your application efficient by choosing the most appropriate storage location and storage optionfor your application's data. For example, the Bookshelf application needs to store information about a book that youhave released, such as comments about the book or the book's current location. Storing this information on thedevice is probably more efficient than querying the Bookshelf web service whenever the user requests thisinformation. If the information consists of relational data, you might choose to store the information in a SQLite®database. If the information needs to be shared between applications on the device, you might choose to store theinformation in the runtime store.

Understanding data storage options

The following table describes the main data storage options that you can use to store information that yourapplication creates.

Data storage option Description

File system You can use this data storage option to create and manage the files andfolders on a BlackBerry device or on an external media card by using theFile Connection API. The File Connection API is implemented in thejavax.microedition.io.file package.

Files that your application creates on a file system are not removedautomatically when your application is removed from the device.

SQLite You can use this data storage option to create and use SQLite relationaldatabases by using the Database API. SQLite databases require noconfiguration or administration and are very small (around 300 KB). You cancreate SQLite databases in internal storage or on an external media card.

SQLite databases that your application creates are not removedautomatically when your application is removed from the device.

Persistent store You can use this data storage option to save objects in persistent memoryon the device by using the Persistent Store API. Data is stored asPersistentObject objects, and these objects are retained in memoryafter the device restarts.

PersistentObject objects that your application defines are removedautomatically when your application is removed from the device.

Development Guide Storing data on the device

61

Data storage option Description

MIDP RMS You can use this data storage option to save data in persistent memory byusing the MIDP RMS. The MIDP RMS is modeled after a simple record-oriented database, and is the MIDP equivalent of the Persistent Store API.You can store and retrieve byte arrays using this method.

Data that your application stores by using the MIDP RMS is removedautomatically when your application is removed from the device.

Runtime store You can use this data storage option to store information and share thatinformation between applications on the device by using the Runtime StoreAPI. Data that your application stores in the runtime store is not retainedafter the device restarts.

Before you close your application, you should remove objects from theruntime store that your application no longer requires.

Choosing a data storage option

When you choose a data storage option to use in your application, you should keep in mind the followingconsiderations:

• Memory on mobile devices can be very limited, so you should consider not storing all of your data on the device.BlackBerry devices are frequently connected to wireless networks so that your application can access data whenneeded. In many cases, the best approach is to store data across device resets only when the data is frequentlyaccessed.

• The file system and MIDP RMS are standards-based approaches, and the persistent store and runtime store arespecific to BlackBerry devices. If you want your application to run on other Java® ME compatible devices, youshould consider a standards-based approach.

• The file system is typically the most efficient storage location for large, read-only files such as videos or largegraphics.

• For storing data other than large, read-only files, SQLite provides a scalable data storage option.• If you use the persistent store in your application, you should use the grouping mechanism that is provided in

the net.rim.device.api.system.ObjectGroup class to commit groups of objects to memory moreefficiently.

• If you use the runtime store in your application, make sure that you remove objects that your application addsto the runtime store when they are no longer required. Failing to remove objects from the runtime store is acommon cause of memory leaks in BlackBerry device applications.

• The BlackBerry® Java® Virtual Machine includes a garbage collection tool, which runs periodically to removeunreferenced objects and weakly referenced objects from memory. To take advantage of this functionality inyour application, you should release objects by setting their references to null after your application is donewith them.

Code sample: Creating a file in internal storage

Development Guide Storing data on the device

62

The following code sample demonstrates how to create a file in internal storage on the device.

import net.rim.device.api.system.Application;import javax.microedition.io.*;import javax.microedition.io.file.*;import java.io.IOException;

public class CreateFileApp extends Application{ public static void main(String[] args) { CreateFileApp app = new CreateFileApp(); app.setAcceptEvents(false); try { FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/newfile.txt"); // If no exception is thrown, then the URI is valid, but the file may or // may not exist. if (!fc.exists()) { // create the file if it doesn't exist fc.create(); } fc.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage()); { }}

Code sample: Creating a SQLite database

The following code sample demonstrates how to create a SQLite database in the root folder of a media card.

import net.rim.device.api.system.Application;import net.rim.device.api.database.*;import net.rim.device.api.io.*;

public class CreateDatabase extends Application{ public static void main(String[] args) { CreateDatabase app = new CreateDatabase(); try { URI strURI = URI.create("file:///SDCard/test.db"); DatabaseFactory.create(strURI); } catch (Exception e) { System.out.println(e.getMessage());

Development Guide Storing data on the device

63

} }}

Find out more

For more information about data storage, visit the following resources:

• Data Storage category overview, in the API reference for the BlackBerry® Java® SDK• BlackBerry Java SDK Data Storage Development Guide

Development Guide Storing data on the device

64

Glossary 8

APIapplication programming interface

GPSGlobal Positioning System

HTTPHypertext Transfer Protocol

ITinformation technology

Java MEJava® Platform, Micro Edition

JSRJava® Specification Request

MIDPMobile Information Device Profile

MIMEMultipurpose Internet Mail Extensions

MMSMultimedia Messaging Service

PAPPush Access Protocol

PINpersonal identification number

PPGPush Proxy Gateway

QRquick response

RMSRecord Management System

Development Guide Glossary

65

SMSShort Message Service

WAPWireless Application Protocol

WLANwireless local area network

XMLExtensible Markup Language

Development Guide Glossary

66

Provide feedback 9To provide feedback, visit www.blackberry.com/docsfeedback.

Development Guide Provide feedback

67

Legal notice 10©2010 Research In Motion Limited. All rights reserved. BlackBerry®, RIM®, Research In Motion®, and relatedtrademarks, names, and logos are the property of Research In Motion Limited and are registered and/or used in theU.S. and countries around the world.

Bluetooth is a trademark of Bluetooth SIG. Documents To Go is a trademark of DataViz, Inc. Eclipse is a trademarkof Eclipse Foundation, Inc. GSM is a trademark of GSM MOU Association. Java and JavaScript are trademarks of OracleAmerica, Inc. Microsoft is a trademark of Microsoft Corporation. Wi-Fi is a trademark of the Wi-Fi Alliance. All othertrademarks are the property of their respective owners.

This documentation including all documentation incorporated by reference herein such as documentation providedor made available at www.blackberry.com/go/docs is provided or made accessible "AS IS" and "AS AVAILABLE" andwithout condition, endorsement, guarantee, representation, or warranty of any kind by Research In Motion Limitedand its affiliated companies ("RIM") and RIM assumes no responsibility for any typographical, technical, or otherinaccuracies, errors, or omissions in this documentation. In order to protect RIM proprietary and confidentialinformation and/or trade secrets, this documentation may describe some aspects of RIM technology in generalizedterms. RIM reserves the right to periodically change information that is contained in this documentation; however,RIM makes no commitment to provide any such changes, updates, enhancements, or other additions to thisdocumentation to you in a timely manner or at all.

This documentation might contain references to third-party sources of information, hardware or software, productsor services including components and content such as content protected by copyright and/or third-party web sites(collectively the "Third Party Products and Services"). RIM does not control, and is not responsible for, any ThirdParty 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. Theinclusion of a reference to Third Party Products and Services in this documentation does not imply endorsement byRIM 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 ORWARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLEQUALITY, NON-INFRINGEMENT, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM ORA COURSE OF DEALING OR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCEOR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICESREFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE ORPROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES ANDCONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THEDOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, AREHEREBY LIMITED TO NINETY (90) DAYS FROM THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEMTHAT IS THE SUBJECT OF THE CLAIM.

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL RIM BELIABLE 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

Development Guide Legal notice

68

REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT,CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL, PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGESFOR LOSS OF PROFITS OR REVENUES, FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSSOF BUSINESS INFORMATION, LOSS OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TOTRANSMIT OR RECEIVE ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITHRIM PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTIONTHEREOF 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 ORUNFORESEEN, AND EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, RIM SHALL HAVE NO OTHEROBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANYLIABILITY FOR NEGLIGENCE OR STRICT LIABILITY.

THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THECAUSE 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 BREACHOR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINEDHEREIN; AND (B) TO RIM AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS(INCLUDING AIRTIME SERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICEPROVIDERS) 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 RIM OR ANY AFFILIATES OF RIM HAVE ANYLIABILITY 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 ensurethat your airtime service provider has agreed to support all of their features. Some airtime service providers mightnot offer Internet browsing functionality with a subscription to the BlackBerry® Internet Service. Check with yourservice provider for availability, roaming arrangements, service plans and features. Installation or use of Third PartyProducts and Services with RIM's products and services may require one or more patent, trademark, copyright, orother licenses in order to avoid infringement or violation of third party rights. You are solely responsible fordetermining 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 Servicesuntil all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIM'sproducts and services are provided as a convenience to you and are provided "AS IS" with no express or impliedconditions, endorsements, guarantees, representations, or warranties of any kind by RIM and RIM assumes no liabilitywhatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject toyou agreeing to the terms of separate licenses and other agreements applicable thereto with third parties, exceptto the extent expressly covered by a license or other agreement with RIM.

Certain features outlined in this documentation require a minimum version of BlackBerry® Enterprise Server,BlackBerry® Desktop Software, and/or BlackBerry® Device Software.

Development Guide Legal notice

69

The terms of use of any RIM product or service are set out in a separate license or other agreement with RIM applicablethereto. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY EXPRESS WRITTEN AGREEMENTS ORWARRANTIES PROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THISDOCUMENTATION.

Research In Motion Limited295 Phillip StreetWaterloo, ON N2L 3W8Canada

Research In Motion UK Limited Centrum House 36 Station Road Egham, Surrey TW20 9LF United Kingdom

Published in Canada

Development Guide Legal notice

70