BlackBerry_Java_SDK-Development_Guide--1394789-1217034013-001-US

Page 1

BlackBerry Java SDK Super App Development Guide


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


Contents 1 Introduction to Super App development..........................................................................................................

3

2 Always on.......................................................................................................................................................... Approaches to the always-on experience......................................................................................................... Creating an always-on experience.................................................................................................................... Running an application at startup............................................................................................................. Keeping the application running in the background................................................................................. Creating alternate entry points................................................................................................................. Scheduling processes to run periodically..................................................................................................

5 5 6 6 6 8 10

3 Highly contextualized........................................................................................................................................ Approaches to adding context.......................................................................................................................... Adding connectivity context............................................................................................................................. Adding battery level context............................................................................................................................. Power level change events........................................................................................................................ BlackBerry device characteristics...................................................................................................................... Adding location context.................................................................................................................................... Accessing and displaying GPS location information.................................................................................. Retrieve the location of a BlackBerry device............................................................................................. Using contextual menus................................................................................................................................... Pop-up menus and submenus................................................................................................................... Creating a pop-up menu............................................................................................................................ Create a pop-up menu...............................................................................................................................

13 13 15 15 15 17 19 19 20 21 21 22 23

4 Integrated......................................................................................................................................................... Approaches to integrating your application..................................................................................................... Integrating by invoking a core application........................................................................................................ Handling content.............................................................................................................................................. Adding custom menu items.............................................................................................................................. Adding application icons................................................................................................................................... Customizing the Phone screen......................................................................................................................... Embedding UI components..............................................................................................................................

27 27 28 29 30 31 32 33

5 Social and connected........................................................................................................................................ Approaches to connecting................................................................................................................................ The details......................................................................................................................................................... Releasing a book........................................................................................................................................ Finding a book...........................................................................................................................................

36 36 37 37 43


6 Proactive and notification-driven..................................................................................................................... Approaches to notification............................................................................................................................... Understanding the BlackBerry Push Service..................................................................................................... Making Bookshelf a push-enabled application................................................................................................. Implement the MessageListener interface................................................................................................ Subscribe to the Push Initiator.................................................................................................................. Update the banner indicator.....................................................................................................................

46 46 47 48 48 50 51

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

52 52 53 56 57 59 61

8 Glossary............................................................................................................................................................

65

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

67

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

68


Development Guide

Introduction to Super App development

Introduction to Super App development

1

Create 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 to ask 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 reputation depends in part on creating the best-in-class mobile experience. What does "best-in-class mobile experience" mean in practice? It means that your users can't live without your app. It means that your app makes every day richer and easier for your user. Those apps are Super Apps. This guide demonstrates the principles behind outstanding mobile application design. Super Apps have the following six characteristics:

1. Always-on Super Apps run in the background on a BlackBerry device to ensure that information is ready for the user before they need 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 access to 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 can share 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 sound or vibrate the device, change the app's Home screen icon, and more.

6. Efficient and scalable

3


Development Guide

Introduction to Super App development

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 named Bookshelf. This application is designed to catalog the books in a user's collection, and connect the user with others who share a love of books. The user can enter the title and description for each book in their collection and display a 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 the catalog functions effectively will force us to explore all six Super App characteristics. To add a social dimension to Bookshelf, 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 precise way 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 known Bookshelf users. Then, you could then send a message from one device to another through BlackBerry® Messenger or email. A more challenging problem arises when you want to create an opportunity for users who may not know each other to interact. In this case, you will need a network server to coordinate the interactions of Bookshelf users. You could use any social networking tool to post messages about books. This approach would cover user stories 1, 2, and 4. To include user story 3, you could create a systematic way to leave a book in a publicly accessible place, such as a coffee shop, for another Bookshelf user to find. Imagine that you can socialize Bookshelf users through a web service. The Bookshelf web service would perform the following 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 through their catalog of books.

4


Development Guide

Always on

Always on

2

Whether it listens and reacts to events, generates notifications, or shares data with other applications, a Super App is always working behind the scenes. By permitting your application to run in the background, you can take advantage of a number of powerful features of the BlackBerry® Application Platform. Do you want your application to listen for pushed content and notify BlackBerry device users when the content arrives? Do you want your application to provide location-specific information updates to your users? These types of tasks rely on your application's ability to run in the background. This chapter focuses on how to create the framework for an application that provides an always-on experience, which is a fundamental characteristic of a Super App. Once we've demonstrated the framework by using the Bookshelf application, you'll have a starting point and can begin implementing other Super App characteristics that are discussed in 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 experience To create an always-on experience, you can implement some of the following approaches. Approach Run your application at startup.

Description One of the most basic steps in creating an always-on experience is making your application run automatically when users turn on their BlackBerry® devices. Keep your application running in the Once your application is up and running, there are steps that you can take background. to make sure that it continues to run efficiently in the background, even after a user closes the UI component for your application. Create alternate entry points. By creating alternate entry points, you can split your application into multiple processes. For example, your main entry point might launch a UI component (using an icon on the Home screen) while another entry point starts a background process that listens for pushed content and sends users notifications. Schedule processes to run By scheduling processes to run at set intervals, you can keep your users upperiodically. to-date and you can conserve memory and battery power on the device when the process doesn't need to be running.

5


Development Guide

Creating an always-on experience

Creating an always-on experience The Bookshelf app can receive pushed information about books that other Bookshelf users release and information about the books that interest you (see the Social and connected and Proactive and notification-driven chapters for more information). Since you don't want to have to wait for users to manually start Bookshelf before they can receive notifications when new information arrives, it's up to you to make sure that there are threads running in the background 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 Bookshelf can efficiently retrieve the position of the BlackBerry® device so that the application can notify users when books are nearby.

Running an application at startup Making your application to run when BlackBerry® device users turn on their devices doesn't require any changes to your application code. If you're using the BlackBerry® Java® Plug-in for Eclipse®, you can edit the BlackBerry_App_Descriptor.xml file so that your application runs each time the BlackBerry device turns on. For BlackBerry® WebWorks™ application developers, a similar option is available in the BlackBerry® WebWorks™ Plugin 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 probably don't want to launch the UI component for the application (most users are not going to want to see your application UI every time they turn on their devices). In Bookshelf, we need the ability to launch a background process that can listen for push events.

Run an application at startup 1.

2. 3.

In Eclipse®, in the Package Explorer view, expand a BlackBerry® application project and double-click BlackBerry_App_Descriptor.xml. The application descriptor opens in the Editor view. In the General Information section, select the Auto-run on startup check box. On the File menu, click Save.

Keeping the application running in the background If your application has a UI component, you might want to keep your application running in the background even after a BlackBerry® device user closes the screen for your application. By default, when the last screen for your application is popped off the display stack, Screen.onClose() invokes System.exit() to terminate the application. To get your application to continue to run in the background, you can override Screen.onClose() and invoke UiApplication.getUiApplication().requestBackground() to push the application to the background 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 can perform to ensure that your application isn't hogging resources or draining the battery. See the Efficient chapter for more information about releasing unneeded resources, stopping UI processes, and managing the backlight. 6


Development Guide

Creating an always-on experience

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 application is pushed to the background rather than terminated. If you want to verify that the application is still running, you can press and hold the Menu key until the Switch Application menu appears. The icon for your application is still present. 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 the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The BackgroundAppDemoScreen 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 the application is pushed to the background rather than terminated when a user closes the screen. public boolean onClose() { requestBackground(); return true; }

7


Creating an always-on experience

Development Guide

Creating alternate entry points You can use alternate entry points in your application, to launch an application in different ways. For example, your application could have one entry point that launches the UI component for your application and another entry point that launches a background process that listens for incoming push messages, pre-processes data, or initializes network communications with a host server. In Bookshelf, we need at least three entry points. The main entry point, which launches the UI component for the application, 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 the device and communicates the location to the Bookshelf web service. We'll discuss this entry point later on, when we discuss 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 the BlackBerry_App_Descriptor.xml file. After you set up an entry point in Eclipse, you need to set up the main() method in your application to support the alternate entry points.

Specify the alternate entry point settings for a BlackBerry application 1. 2. 3. 4. 5. 6. 7.

In Eclipse®, in the Package Explorer view, expand a BlackBerry® application project. Double-click BlackBerry_App_Descriptor.xml. On the Alternate Entry Points tab, click Add. In the New Entry Point dialog box, type the name of a project in the workspace that this project invokes. Click OK. Select the Alternate entry point properties and Locale Resources. On the File menu, click Save.

Properties for the alternate entry point settings Setting Title

Description Type a name for the alternate entry point that is displayed on the Home screen of the BlackBerry® device. Application arguments Specify the arguments to pass into the application's main() method. Do not show the application icon on Select this setting to run the application in the background, without the BlackBerry device Home screen displaying an icon on the Home screen of the BlackBerry device. Auto-run on startup

This setting is not available if the Application type is Library. Select this setting to start the application automatically when the BlackBerry device starts. Applications that run automatically must be digitally signed by Research In Motion to run on a BlackBerry device.

8


Creating an always-on experience

Development Guide

Setting Startup tier

Internationalized resource bundle available Resource bundle Title ID

Alternate Entry Point icons

Description If the Auto-run on startup setting is selected, specify the priority in which the application is started, in relation to other applications. For third-party applications, you can select tier 6 or 7 (other start-up tiers are reserved for core BlackBerry Applications). The default setting is 7 (lowest priority). Select this setting if the title and the description of the alternate entry point have been internationalized in a resource bundle. Select the resource header file to use for the alternate entry point. 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. Add the files for application icons from the project's resources or from a location 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 (this example specifies pushListener as the argument to check for). If the application is entered by using the pushListener 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 statement that 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 the else block, create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The EntryPointsDemoScreen class, which is described in step 3, represents the custom screen. public class EntryPointsDemo extends UiApplication { public static void main(String[] args) { if (args != null && args.length > 0 && "pushListener".equals(args[0])) { Alert.startVibrate(2550);

9


Creating an always-on experience

Development Guide

} 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 periodically The Bookshelf app permits users to find books that other Bookshelf users release to the world. To notify users when there 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 schedule this process to run periodically rather than run constantly in the background. To schedule your application to run at a 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() method checks to see which entry is used to enter the application by checking the application argument (this example specifies startVibrate as the argument to check for). Each time the application is entered using the startVibrate argument, the BlackBerry速 device vibrates and schedules the application to run again. If the application is entered using any other argument, the application launches the UI component for the application and does not schedule the application to run again. 1.

Import the required classes and interfaces. import import import import import

10

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


Development Guide

2.

Creating an always-on experience

Create the application framework by extending the UiApplication class. In main(), create an if statement that 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. In the else block, create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The ScheduleAppDemoScreen class, which is described in step 3, represents the custom screen. 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 an ApplicationDescriptor object by invoking ApplicationDescriptor.currentApplicationDescriptor() to retrieve the application descriptor of the application that is currently running. Invoke setPowerOnBehavior (ApplicationDescriptor.DO_NOT_POWER_ON) on the application descriptor so that when the application runs as scheduled, if the device is currently off, the application doesn't force the device to turn on. Invoke ApplicationManager.getApplicationManager() to retrieve an instance of the system's ApplicationManager. Invoke ApplicationManager.scheduleApplication() and specify the ApplicationDescriptor 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. 11


Development Guide

}

12

Creating an always-on experience

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


Highly contextualized

Development Guide

Highly contextualized

3

A typical BlackBerry® device application performs a task in response to user input. If the application needs additional information to perform the task, the application queries the user for that information. A well-designed, typical application might store information so it doesn't have to ask for the information again. But a Super App is designed to 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 for using core BlackBerry application functionality, and reliable connectivity to a wide variety of web services—with these 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 present users 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 that you have travelled into. This feature improves the application in two ways. First, you are reminded to update your time zone. And second, you are presented with the correct time zone. You only have to press a button to confirm that 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 from scratch. Reduce input errors. Getting geographical coordinates of a device's current location by using the GPS radio is much 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 in fewer support calls about how to invoke a feature or how to enter information in the correct format.

Approaches to adding context You can make your application highly contextualized by using any of the following approaches. Approach Add location context.

Examples If your application includes a search feature, the feature can probably be improved by automatically incorporating the current location of the BlackBerry® device into the search criteria. Users searching for gas stations are likely most interested in ones near their current location. Many web services provide location-specific services. Your Super App can use those services.

13


Development Guide

Approach Add time context.

Add date context.

Add battery level context.

Add connectivity context.

Add device characteristics context.

Approaches to adding context

Examples Imagine you create an application that can search for restaurants. You can add some context by using the location of the device to organize the search results by distance from the device. If the data service you use includes information about hours of operation, you can make the results even better by only showing restaurants that are open. The data service might even include information about lunch or dinner specials and, taking into context the current time, you could present the results accordingly. Some web sites and applications display custom themes to celebrate special days such as holidays, birthdays of famous people, or current events. This customization is an example of how you can improve an application with a minor 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 date when doing so could improve the user experience. Your Super App should check the power level of the battery before performing tasks that consume a lot of power. Your app can let the user know that they are about to perform a task that consumes a lot of power and that their battery is low. It could also stop doing any unnecessary background processing or prefetching. Your Super App should check the type of network connections that are available. For example, if the user requests that the application download and 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 rates and 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 might take a very long time. The application might provide an approximate download time, and let the user decide whether to proceed. Your Super App should adapt to the device model it is running on. Battery life and connectivity are universal contexts for BlackBerry device applications. But device characteristics such as the available keyboard types, screen type and dimensions, audio capabilities, inserted memory cards, and the presence of an accelerometer are specific to the particular BlackBerry device. Super Apps provide good default choices for their users. For example, on a device with a touch screen that supports gestures, a Super App displays hints about how to zoom in and out using pinch gestures.

14


Adding connectivity context

Development Guide

Approach Use contextual menus.

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

Adding connectivity context Super Apps are designed to take into account the BlackBerry速 device models that they run on and the variable levels of connectivity. Super Apps are also designed to take into account different types of connections with different associated 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 table can help you interpret the results. Network type GSM速 CDMA Wi-Fi

Strong signal > -76 dBm > -83 dBm > -50 dBm

Medium signal -86 dBm to -92 dBm -92 dBm to -105 dBm -70 dBm to -60 dBm

Weak signal < -101 dBm < -109 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 events Your can register a BlackBerry速 device application so it is notified when power level change events take place on the device it is running on. If the battery power level is low, you can respond by turning off or modifying some features of your application to conserve power. When your application receives notification that the battery power level is good again, you can turn on those features again. To process power level change events, your application must implement the net.rim.device.api.system.SystemListener interface.

15


Development Guide

Adding battery level context

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

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

public class PowerChangeEvent extends 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!"); }

}

16

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


BlackBerry device characteristics

Development Guide

BlackBerry device characteristics There are a number of methods, mostly in classes in the net.rim.device.api.system package, that provide information about a device. The following is a list of some common device information you can get using those methods. 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 Identity device is simulator manufacturer device name PIN IMSI ESN MEID IMEI owner information owner name vendor ID branding data version branding data is signed Battery battery power level (%) additional battery information battery temperature (째C) battery voltage (mV) battery is removable Speaker and Headset audio is supported codec is supported volume level (%) headset is built-in headset is connected Accelerometer accelerometer is supported Flip Sensor flip is open or closed phone is flip Holster Sensor

Method DeviceInfo.isSimulator() DeviceInfo.getManufacturerName() DeviceInfo.getDeviceName() DeviceInfo.getDeviceId() SIMCardInfo.getIMSI() CDMAInfo.getESN() CDMAInfo.getHexMEID() GPRSInfo.getIMEI() OwnerInfo.getOwnerInformation() OwnerInfo.getOwnerName() Branding.getVendorId() Branding.getVersion() Branding.isDataSigned() DeviceInfo.getBatteryLevel() DeviceInfo.getBatteryStatus() DeviceInfo.getBatteryTemperature() DeviceInfo.getBatteryVoltage() DeviceInfo.isBatteryRemovable() Audio.isSupported() Audio.isCodecSupported() Audio.getVolume() Audio.hasBuiltInHeadset() Audio.isHeadsetConnected() AccelerometerSensor.isSupported() Sensor.getState() Sensor.isSupported()

17


BlackBerry device characteristics

Development Guide

phone is in holster holster sensor is supported Slide Sensor sliding keyboard is supported slide is open slide is closed slide is moving Display horizontal resolution (pixels per meter) vertical resolution (pixels per meter) drawable area height (pixels) drawable area width (pixels) number of display colors additional display information Backlight backlight is on backlight brightness (%) backlight brightness is configurable backlight brightness default (%) default backlight timeouts LED Indicator LED is supported LED is multi-color Radios wireless access family is supported GPS GPS mode is available default GPS mode Bluetooth Bluetooth速 radio is supported Bluetooth information Phone phone number voice mail is present Memory flash memory size (bytes) free flash memory (bytes) RAM statistics OS and software platform version software version

18

Sensor.getState() Sensor.isSupported() Sensor.isSupported() Sensor.isSlideOpened() Sensor.isSlideClosed() Sensor.isSlideInTransition() Display.getHorizontalResolution() Display.getVerticalResolution() Display.getHeight() Display.getWidth() Display.getNumColors() Display.getProperties() Backlight.isEnabled() Backlight.getBrightness() Backlight.isBrightnessConfigurable() Backlight.getBrightnessDefault() Backlight.getTimeoutDefault() LED.isSupported() LED.isPolychromatic() RadioInfo.getSupportedWAFs() GPSInfo.isGPSModeAvailable() GPSInfo.getDefaultGPSMode() BluetoothSerialPort.isSupported() BluetoothSerialPort.getSerialPortInfo() Phone.getDevicePhoneNumber() Phone.isVoiceMailIndicatorOn() DeviceInfo.getTotalFlashSizeEx() Memory.getFlashFree() Memory.getRAMStats() DeviceInfo.getPlatformVersion() DeviceInfo.getSoftwareVersion()


Adding location context

Development Guide

Camera camera is supported USB port USB port is supported USB connection state

DeviceInfo.hasCamera() USBPort.isSupported() USBPort.getConnectionState()

Adding location context Accessing and displaying GPS location information A BlackBerry速 device user can use a BlackBerry device application to access GPS data and view information on the location, speed, and direction of the BlackBerry device. A BlackBerry device application can use a source for GPS data that 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 the methods of the class to specify the source of GPS data. For example, a BlackBerry device application invokes Criteria.setHorizontalAccuracy(2) and Criteria.setVerticallAccuracy(2) to specify that a source of GPS data must provide vertical and horizontal data values that is accurate within 2 meters of the actual values. A BlackBerry device application invokes Criteria.setCostAllowed(true) to use a source of GPS data that costs money 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 BlackBerry device. A BlackBerry device application sets the properties of the Criteria object to specify the mode the application uses to retrieve GPS data. The cell site mode allows a BlackBerry device application to retrieve GPS data from a cell site tower. This mode is faster but less accurate than other modes. The assisted mode allows a BlackBerry device application to retrieve GPS data from a satellite. This mode is faster than the autonomous mode and more accurate than the cell site mode. The autonomous mode allows a BlackBerry device application to retrieve GPS data from the BlackBerry 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 invokes javax.microedition.location.LocationProvider.getInstance(Criteria) using the Criteria object as a parameter to retrieve a LocationProvider object. A BlackBerry device application can invoke LocationProvider.getLocation() to retrieve an object of the javax.microedition.location.Location class to access data for a location. Invoking the Location.getSpeed() and Location.getCourse() methods retrieves the speed and the direction of the BlackBerry device. Invoking the Location.getQualifiedCoordinates() method retrieves a javax.microedition.location.QualifiedCoordinates object that can provide the latitudinal and longitudinal coordinates of the BlackBerry device. A BlackBerry device application can listen for updates from a source for GPS data to provide a BlackBerry device user with current GPS information. The BlackBerry device application must implement the javax.microedition.location.LocationListener interface and invoke the LocationProvider.setLocationListener(LocationListener int, int, int) method to register the

19


Development Guide

Adding location context

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 specify that 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 getting an instance of the Criteria object. Create another try/catch block to create a Location object to request the current location of the BlackBerry速 device and specify the timeout period in seconds. When the getLocation() method returns, request the latitude and longitude coordinates. try {

20

LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);


Using contextual menus

Development Guide

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 submenus You can add a pop-up menu and a submenu to your application by using the classes provided in the net.rim.device.api.ui.menu package. Menu Pop-up menu

Description A pop-up menu, similar to a context menu, contains a list of the most common actions that BlackBerry速 device users can perform within the current context. An item in the pop-up menu can include the text, an application icon, and a command. A pop-up menu replaces a context menu, or a short menu, that was available in previous versions of the BlackBerry速 Java速 SDK. The BlackBerry速 Device Software automatically converts an existing context menu into a pop-up menu.

21


Using contextual menus

Development Guide

Menu

Description

Submenu

A submenu is a group of related menu items. A submenu appears as a subset of 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 the full 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 menu You 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. 22


Using contextual menus

Development Guide

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

Command item provider

Command items

Description You use the DefaultContextMenuProvider class to create and display a screen's pop-up menu. When a BlackBerry速 device user opens a pop-up menu, the context menu provider looks for fields on the screen that are command item providers. DefaultContextMenuProvider is the default implementation of ContextMenuProvider. If you do not provide a screen with a context menu provider, the legacy context menu is converted and displayed as a pop-up menu. You use the CommandItemProvider class to configure a field on your UI screen so that the field can provide context and command items to the popup menu based on the current context. For example, you could configure an email address as a command item provider and provide the user with different actions based on whether the email address is in the user's contact list. You use the CommandItem class to specify the text, icon, and behavior of a pop-up menu item. You define the behavior of the pop-up menu by using a command. The command acts as a proxy to an instance of a command handler, which defines the functionality of the pop-up menu item. For example, for an email address, you could provide command items to add or view a contact based on whether the selected email address appears in the user's contact list. The command handler would contain the code to add or view the contact. For more information on commands and command handlers, see Command Framework API. The Command Framework sample application that is provided in the BlackBerry速 Java速 SDK demonstrates commands and command handlers.

If you use a legacy context menu, BlackBerry速 Device Software 6.0 converts the context menu items to command items 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 import import import import import

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

23


Development Guide

Using contextual menus

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 the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The MyPopUpMenuScreen 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(); }

}

3.

public Mypop-upMenuApp() { pushScreen(new Mypop-upMenuScreen()); }

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 to Screen.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: ", "name@blackberry.com", 40);

6.

24

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


Development Guide

Using contextual menus

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

7.

In the custom screen, implement the CommandItemProvider interface. In getContext(), return the field that is configured as a command item provider. In getItems(), create a Vector object to add the pop-up menu 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 each command item, specify the pop-up menu text, icon, and command. In the following code sample, an if-thenelse statement is used to check which component invoked the pop-up menu before creating the CommandItem. The command is a proxy to an instance of a class that extends the abstract CommandHandler class, which is described in step 9. Invoke Vector.addElement() to add the pop-up menu items to the Vector. 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 abstract CommandHandler class. In execute(), define the functionality that you want to associate with the pop-up menu items. This command handler could be used by any UI component on your screen (for example, full menu items, 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) { 25


Development Guide

}

26

}

Using contextual menus

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


Integrated

Development Guide

Integrated

4

An 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 applications is seamless and easy to use. They likely aren't concerned with what happens behind the scenes, and many users don'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 thirdparty 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 seamless experience 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-party application is already part of a user's routine, by integrating with that application, you can provide consistent behaviors and essential features that can also become part of the user's routine.

Approaches to integrating your application You can integrate your application by using any of the following approaches. Approach Invoke an application and pass information to the application.

Examples •

When a user selects the address of a bookstore in the Contacts application, launch a turn-by-turn navigation application to provide directions to the associated address. While listening to a song on a radio application, launch another application that provides the option to purchase the song. 27


Integrating by invoking a core application

Development Guide

Approach Integrate with existing or new content handlers.

Examples • •

Integrate directly into an application by

• •

Creating custom menu items Embedding UI components in core applications Adding custom UI fields

When a user selects a link for an audio book, launch the media player to play the audio book file. When a user receives a Microsoft® Word document, open the document by using the Documents To Go® application. Add a custom menu item in the Calendar application that can open a meeting planner application. Display a custom icon on the Home screen that changes based on the local weather forecast. Embed a map that displays bookstore locations that stock the recommended book.

Integrating by invoking a core application You can provide an integrated experience for your users by invoking a core application from your application and passing data to the core application. For example, in the Bookshelf application, a BlackBerry® device user can indicate that a book is loaned by clicking a menu item, such as Loan, which launches the Contacts application and retrieves contact information. From the Contacts application, the user can return to the Bookshelf application and log the information 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 and pass 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, and args 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 the net.rim.blackberry.api.menuitem package. When you pair the Invoke API with ApplicationMenuItem, you can provide the user with the ability to launch the invoked application and return to your application by using menu items. For more information about menu items, see Adding custom menu items.

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

28

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


Development Guide

Handling content

BlackBerry Java SDK Integration Development Guide

Handling content Another approach to creating a seamless user experience is to make sure your application can handle content by integrating with existing or new content handlers. For example, when a user clicks a URL to an audio book, the media player opens and plays the audio book. The Content Handler APIs, which are provided in the javax.microedition.content and net.rim.device.api.content packages, allow applications to integrate with and use functionality in third-party and core applications that use these APIs. For example, DataViz®, in the Documents To Go® applications, use the Content Handler APIs to register their applications as the content handlers for various document types. This suite of applications that is preloaded on most BlackBerry® devices also provides handles to allow third-party applications to invoke the Documents To Go applications with the supported document types. For example, your application can invoke 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 type or 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 a unique ID. As part of the registration, you also specify the file types that the application can handle along with the actions that it supports for those files types. For example, you can register an application to print files of a specified type. Once your application is registered as a content handler, other applications can query the registry to get information 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 required to 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 is required. To invoke a core application that is a content handler, you can use the net.rim.device.api.content.BlackBerryContentHandler class, which provides IDs for all core application handlers on the device. These IDs are used with the Invocation class to invoke a specific content handler, or with the Registry class to retrieve a specific ContentHandler class. You start the invocation request by calling the Registry.invoke() method. 29


Development Guide

Adding custom menu items

Code sample: Invoking the Media application by using a URL //Create an Invocation instance with the file URL Invocation invocation = new Invocation("file:///SDCard/BlackBerry/music/001.mp3"); //Retrieve a Registry object Registry _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 items To integrate your application with core applications, you can add a custom menu item. By adding custom menu items in core applications, you can provide a seamless experience for the BlackBerry® device user, where they can launch your application from another application they use frequently. For example, you can add a menu item called Loan Book to the Contacts application. When the user clicks Loan Book, the Bookshelf application opens and displays the screen for logging the loaned book.

You can define menu items to display in core applications by using the ApplicationMenuItem class, which is defined in the net.rim.blackberry.api.menuitem package. The ApplicationMenuItem instance you create must be registered with the ApplicationMenuItemRepository class. The ApplicationMenuItemRepository class provides the constants that specify the core application that your menu item appears in. For example, the MENUITEM_MESSAGE_LIST constant specifies that the menu item appears in the list view of the Messages application, or the MENUITEM_SYSTEM constant specifies that your menu item appears in most core applications. 30


Development Guide

Adding application icons

To specify where your menu item appears in the menu list, assign an Integer value to represent the display order of the menu item. Positions are relative, so a lower number corresponds to a higher position in the menu. In the following example, the Loan Book menu item has an order value of 0x350100, which displays the menu item lower in the menu (higher numbers mean the menu item appears lower in the menu and lower values mean the item appears higher in the menu). When an ApplicationMenuItem is invoked, the core application passes a context object to your application. The context that is returned depends on the core application from which your menu item was invoked. In the following example, 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 contact ApplicationMenuItemRepository 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 icons The 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 user clicks 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.

31


Development Guide

Customizing the Phone screen

You can add an application icon and specify rollover effects by changing the properties for the application project in the BlackBerry® Java® Plug-in for Eclipse®. The application properties for the project are contained in the BlackBerry_App_Descriptor.xml file. For more information about changing project properties, see the BlackBerry Java Plug-in for Eclipse Development Guide. For further integration, you can customize the icon to change dynamically based on the state of the application. For example, a weather application icon can change based on the weather forecast — a sun to indicate a sunny forecast or 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 is related 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 screen You can integrate your application with the Phone application by customizing the call screens to display information from your application on the Incoming call and the Active call screens. For example, information that is provided by the 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 later by 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 a call screen, the device displays each application's content in sequence for approximately two seconds until the next call screen appears. For example, if you display content on the incoming call screen, the device displays the content until the user answers the call and the active call screen appears.

32


Development Guide

Embedding UI components

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 components There are a number of specialized UI components that core applications on the BlackBerry® device use. You can integrate these UI components in your application to provide users with a familiar and seamless experience on their BlackBerry device. Below are some examples of UI components that you can integrate into your application:

33


Embedding UI components

Development Guide

Component AutoCompleteField

LocationPicker

FilePicker MapField BrowserField Media fields in javax.microedition.media and javax.microedition.media.cont rol

Description You can use the AutoCompleteField class to compare the text that a user types in the field against the items in a data source, and display the matches in a dropdown list below the field. The data source can retrieve information from other applications (for example, names from the Contacts application), or use customized information (for example, days of the week). You can use the LocationPicker class to give users the ability to select a location by using sources such as contacts from the Contacts application, GPS coordinates, recent locations, and suggestions from applications. You can use the FilePicker class to provide users with the ability to select a file by navigating to a folder. You can use the MapField class to embed a map in your application. You can use the BrowserField class to embed web content in your application. You can use the media fields to embed media players and media recorders in your 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:

34


Development Guide

• • • •

Embedding UI components

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

35


Development Guide

Social and connected

Social and connected

5

A Super App makes it easy for people to build relationships. The most frequently used applications can help people share their experiences, data, and media with others. For example, an application could help an insurance salesperson retrieve key account details for a client during a meeting, or take a picture of a new item to be added to a policy. In a personal context, an application could help someone coordinate a social event with friends, and share the memories from 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 your app in the future. Share experiences as they happen. Life happens quickly, and your app can be there to help users capture and share the moments that matter the most.

Approaches to connecting Approach Examples Deliver timely and relevant information • An application that reports sports information can push scores through the BlackBerry® Push Service. In a and news from games as they become available. corporate environment, you can send • A weather application can update weather information when it push messages through the BlackBerry® is published, so that the application always has the most current Enterprise Server. information. • The manager of an airport baggage system could receive updates about flight arrivals and departures through the airport's BlackBerry Enterprise Server. Fetch additional information for a user • A weather application that receives the basic details of the from web sites and social networking forecast through a push message could download satellite services using the Communication API images before the user views the forecast. (BlackBerry® 6 and later), or the Network • A social networking application could synchronize contact lists API (BlackBerry® Device Software 5.0 and betweeen a BlackBerry device and the web service. later). Send application data between BlackBerry • A personal health management application can collect and send devices using the BlackBerry® Messenger information about the medications a patient takes. Social Platform SDK. • A media player application can report the current song, image, or video that a user is enjoying. Capture and share pictures, audio, and • An event management application can capture images and other video. media from an event, and automatically share that them through the BlackBerry® Messenger Social Platform, or another social network.

36


Development Guide

The details

Approach Examples Enable people to discover information • An application could facilitate city-wide scavenger hunts where about their environment by scanning oneusers had to find and scan QR codes to receive clues about where dimensional and two-dimensional bar to go next. codes.

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

Releasing a book To release a book for other users, Bookshelf communicates a book's identity and location to the Bookshelf web service. However, if the book is hidden in a public place, a person might not find it using the location information alone. Bookshelf should also allow the user who releases the book to add more information about the location of the 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 could scan the code to add the book to their list. Once the book is added to their list, the user could then retrieve the history of 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 connection to send this information to the Bookshelf web service. For more information about retrieving the location of the BlackBerry® 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 audio recording 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() { }

37


The details

Development Guide

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 "

38


The details

Development Guide

}

+ 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 video recording 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" );

39


The details

Development Guide

_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: •

40

BlackBerry® Java® SDK Multimedia Development Guide


The details

Development Guide

Capture images The following code sample extends the MainScreen class to create a viewfinder to capture images. You can present this 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);

41


The details

Development Guide

} 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 the Communication 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

42


The details

Development Guide

}

(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 book To help a user find books that have been released by others, Bookshelf needs to communicate with the Bookshelf web service about the current location of the user's BlackBerry速 device. Bookshelf can use location information to notify the user if there is a book nearby. Book sharing is one way a Bookshelf keeps users connected to each other and the application. Acquiring the location of the device can consume a lot of battery power. There are several strategies to use battery power efficiently in this scenario. The following table discusses three of those strategies. 43


The details

Development Guide

Strategy Schedule an application to run periodically.

Start with a cell-tower position.

Description The ApplicationManager.scheduleApplication() method requests that the BlackBerry device runs an application at a particular time. Each time Bookshelf runs to retrieve the current location of the device, 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 than use memory and battery power on the device when the application is not required. For more information, see the Always on chapter. To calculate the BlackBerry device's location, the GPS receiver must scan the sky for satellites. This part of acquiring location information consumes the most battery power. In some cases, you can find the device's approximate location from the cell tower to which the device has a wireless connection. This strategy requires 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 to only return books within a smaller area, you can then provide a more specific list based on the particular location acquired by using GPS.

Use message notifications.

For more information, see the Highly contextualized chapter. When a user installs Bookshelf, the application creates an ApplicationMessageFolder. When Bookshelf discovers that a book is nearby, the application can add a new message to the ApplicationMessageFolder. By default, the message appears in the user's Messages application. On devices running BlackBerry速 6 or later, the message will also appear in the Notifications tray on the Home screen. This strategy is energy efficient because a user can review the details of a book before launching Bookshelf. Bookshelf also implements ApplicationIndicator to display a custom icon for new message notifications. Instead of displaying a closed envelope 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 read that copy of the book. To do so, they can scan the two-dimensional bar code that was attached by the person who released the book.

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


Development Guide

•

The details

How to use the Barcode API BlackBerry Developer Knowledge Base article

45


Development Guide

Proactive and notification-driven

Proactive and notification-driven

6

Proactive and notification-driven applications are fundamental to the BlackBerry® experience. Much of the success of 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 can receive email anywhere, but that the content of the email is delivered to the device as soon as it is available, with no user intervention. A user doesn’t need to pull a message down from the messaging server to read it. When the server receives an email message for a user, the server proactively “pushes” that message to the user’s device. The Messages application listens in the background for messages to arrive and, upon receiving a new message, displays a 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 same model can be applied to any application by using the BlackBerry® Push Service, which allows content developers to submit 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—can take 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. With push 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 user does not need to do anything to transfer the content to the BlackBerry device. The app simply receives the content 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 notification To notify a BlackBerry® device user of an event, you can choose from a number of notification types. Some of these notifications are discreet, noticed only when the user is looking for them, and others are more overt. You can issue multiple notifications for a single event. The discoverability of the notification type, or types, should match the importance of the event to the user. For urgent events, you may want to issue an audio notification or a vibration that immediately attracts the user's attention. For less important events, you can use more discreet notification types. Regularly occurring events, for example, in an app in which sports scores are pushed overnight, require only subtle notification—or no notification at all—since the user has an expectation that the content will arrive around the same time each day.

46


Understanding the BlackBerry Push Service

Development Guide

Approach Display a banner indicator.

Example When a new message is pushed to the device, a small icon is displayed in the Home screen banner. You can customize the image so that it is specific to your application. Flash the LED indicator. When the daily sports scores are pushed to the device, the BlackBerry device LED flashes. You can customize the behavior of the LED notification. For example, you can configure the LED to flash a yellow light when the event occurs. Play a sound. When a new text message arrives, a sound is played. You can use any of the default sounds that are available on the device, or provide your own custom sounds. Vibrate the BlackBerry device. When a stock you are monitoring reaches a specified value, the BlackBerry device vibrates. Send an email or text message. When an update to an application is available, the application sends a message to the Messages application. As a best practice, if you send a message 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. The user must actively dismiss the dialog box. Because a popup dialog box is a UI element, it is not appropriate for background notifications. Display an alternate Home screen When new push content is available for an application, the application icon icon. on the Home screen changes to an alternate image.

Understanding the BlackBerry Push Service Before getting into the specifics of creating a push solution, it is helpful to understand the features and architecture of the BlackBerry速 Push Service. The BlackBerry Push Service provides developers with access to the push technology upon which much of the success of BlackBerry devices is built. A push solution is made up of three main components: Component Push Proxy Gateway (PPG)

Push Initiator

Description The PPG is the middleware, specifically a push data server, within the BlackBerry速 Infrastructure. The PPG is the main functional component of the BlackBerry Push Service, and is responsible for receiving push requests from a Push Initiator and delivering the content to the appropriate port on the BlackBerry device. The Push Initiator is the server-side application. A Push Initiator takes the content that is to be pushed to users, packages it in a push request with a PAP control entity (an XML document that contains the recipient addresses and

47


Making Bookshelf a push-enabled application

Development Guide

Component

Push-enabled app

Description defines delivery parameters such as an expiry time or reliability level), and submits that push request to the PPG for delivery. In our scenario, the Bookshelf web service plays the role of the Push Initiator. Extending the Bookshelf web service to function as a Push Initiator is beyond the scope of this guide. However, Research In Motion has provided the BlackBerry® Push Service SDK to help simplify the process of creating and submitting push messages. The push-enabled app is the client-side application that is installed on the BlackBerry device. A push-enabled app is an application that is designed to listen on a specific port and receive incoming content that has been pushed to this port on the device. In our scenario, we’ll be extending the Bookshelf app 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. When you register, you will receive an Application ID for your push solution, which is used to associate your Push Initiator with your push-enabled application.

Find out more

For 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 application To 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 Push Initiator 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 automatically when the BlackBerry device turns on but does not display the UI, allowing Bookshelf to receive and process push content as it arrives. See the Always on chapter for more information on setting up an alternate entry point.

Implement the MessageListener interface 1.

48

Import the required classes and interfaces.


Making Bookshelf a push-enabled application

Development Guide

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

7.

}

payload = new String(data);

If payload contains data, issue a notification to alert the BlackBerry速 device user about the newly arrived content.

49


Making Bookshelf a push-enabled application

Development Guide

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 {

4.

MyMessageListener pushListener = new MyMessageListener();

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 the InboundDestinationConfiguration object that defines the parameters for the push subscription, the port number on which the app listens, and the MessageListener object responsible for receiving and processing the 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.

50

Build the subscription message.


Making Bookshelf a push-enabled application

Development Guide

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 EncodedImage variable. Create an instance of the ApplicationIcon class using the EncodedImage as an argument. EncodedImage image = EncodedImage.getEncodedImageResource("BookShelf-Iconnotification-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 value associated with it (for example, new message count). The third parameter specifies that the indicator should be visible. ApplicationIndicator indicator = reg.register( icon, true, true);

5.

Retrieve the registered indicator by invoking

ApplicationIndicatorRegistry.getApplicationIndicator(). Save the return value in an ApplicationIndicator variable. ApplicationIndicator appIndicator = reg.getApplicationIndicator();

6.

Set the image and value for the indicator by invoking ApplicationIndicator.set(). You should consider only showing a value if it is greater than 0. appIndicator.set( newIcon, newValue );

51


Development Guide

Efficient

Efficient

7

The other chapters in this guide describe how to implement five of the features and characteristics of Super Apps in your application. For BlackBerry® device users to enjoy using your application on a daily basis and recommend it to others, 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 consume battery 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 typically delete 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 (including yours!). Improve response times. Efficient applications can respond quickly to a user's input, which means less waiting on 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 because your 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 engages the user, that the user comes back to over and over again. By focusing on efficiency when you design your application, you can improve your user's experience and help increase the stickiness of your application.

Approaches to efficient application design You can help make your application efficient by using any of the following approaches. Approach Examples Be aware of the status of the • If your application is designed to download songs or videos from a BlackBerry® device (such as battery website, your application should stop downloading content if the power level, network connectivity, battery level or available memory on the device is low. and so on) and respond accordingly. • Download large files only when the device is connected to a Wi-Fi® network. Eliminate or defer unnecessary • If your application needs to perform complex calculations, perform processing on the device. these calculations when the device is idle. • Have data such as news items, status updates, or other data pushed to the device periodically instead of having the device poll to retrieve the data.

52


Responding to the status of the device

Development Guide

Approach Use location services, such as GPS and geolocation, carefully.

Examples •

• Use the Profiler tool to optimize your • code. •

If your application needs to obtain a GPS fix, perform full scans of the sky to locate satellites for the fix only when necessary. Use assisted GPS mode sparingly. 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's running, and try to reduce this number if possible.

Responding to the status of the device The Highly contextualized chapter describes how to consider the contexts (such as battery, connectivity, and device characteristics) that are associated with BlackBerry® devices. When you design your application, the monitoring of certain contexts, or states, of the device can help your application be more efficient while also providing an exceptional 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 application communicates with a web service that provides information about books that have been released. If Bookshelf detects that the device is connected to a Wi-Fi network, Bookshelf can use the bandwidth that the Wi-Fi connection provides 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 your application as a listener for different types of events. You might want your application to close automatically if the battery level reaches a certain point, or to provide different options if the device is connected to a computer using a USB connection. You can also use listeners to monitor global events on the device and use these global events to communicate 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 listener interfaces and the events that they listen for. Interface SystemListener2 GlobalEventListener CoverageStatusListener WLANConnectionListener

Description You can use this listener to listen for system events, such as changes to the state of the backlight or changes to the state of the USB connection. You can use this listener to listen for global events, such as changes to the time zone or events that are associated with interprocess communication. You can use this listener to listen for changes to wireless transports, such as HTTP over WAP or the BlackBerry® Mobile Data System. You can use this listener to listen for changes to Wi-Fi connectivity.

53


Responding to the status of the device

Development Guide

Interface LowMemoryListener

Description You can use this listener to determine when the amount of available memory is low.

If you choose to use listeners in your application, it's important to remember to deregister the listeners that you use when you are done with them. If you don't deregister a listener, a reference to the listener remains in memory on the 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. This approach might be a good way to improve the efficiency of your application. A listener that you create yourself might be more focused or specialized for your application's functionality than a generic listener. For example, a listener that is designed for the Bookshelf application might listen specifically for events that are generated by the Bookshelf web 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, you can invoke DeviceInfo.getBatteryLevel() or DeviceInfo.getBatteryStatus() before you start your application, to determine if there is sufficient battery power remaining to run your application or to perform a lengthy operation. 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 user is not using the device. If your application must open a network connection, your application should check the network coverage that is available. 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, you can design your application to retrieve a smaller, lower-quality set of data immediately, and then wait until coverage improves or a Wi-Fi connection is available to retrieve the full set of data. You can invoke RadioInfo.getSignalLevel(), CoverageInfo.isCoverageSufficient(), or TransportInfo.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 might block a feature of the device that your application is trying to use. For example, if the Disable GPS IT policy rule is applied to the device, your application won't be able to obtain a GPS fix and should not waste resources trying to do so. 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 wireless coverage. 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() {

54


Development Guide

}

Responding to the status of the device

// ...

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 changes on the device. If the backlight is off, your application doesn't need to respond to any events, and you don't need to set a listener for the screen. If the backlight is on, your application can resume listening for events. // override backlightStateChange() of the SystemListener2 interface public 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. If this 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; }

55


Development Guide

}

Eliminating unnecessary processing on the device

} 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 the BlackBerry® Java® SDK BlackBerry Java SDK Network Communication Development Guide

Eliminating unnecessary processing on the device The 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 build efficiency 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 your application, and eliminating any processing that might not be necessary at a given time. For example, the Bookshelf application doesn't need to check the Bookshelf web service continuously for updates to the information about a book. A book's information doesn't change very often, so it might be more efficient to use a push solution to send the 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 the background lets your application continue to process data and provide updates to the BlackBerry device user, even when the user is using other applications on the device. However, running in the background can consume valuable system 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 web server. Your application doesn't need to be running in the background to receive push notifications. When push data arrives on the device, if your application is registered as a push handler, your application processes the data automatically. You can schedule processes to run periodically. Your application can perform resource-intensive operations at specific 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 your application does its processing all at once, instead of spread out over a long period of time. The device can enter a low-power mode when processing is complete to minimize power consumption. You should also avoid opening many separate network connections to transfer small amounts of data. Instead, you should design your application to wait until there is a significant amount of data to transfer, and then open a single connection and transfer all of the data at once.

Detecting when your application is not displayed

56


Development Guide

Using location services effectively

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

• •

You can use methods to stop animating or repainting the screen when the screen is not visible, and resume when the screen is visible again. You can override Screen.onExposed(), which is invoked when your application's screen is on top of the display stack and displayed to the user. You can override Screen.onObscured(), which is invoked when your application's screen is not displayed to the user or is obscured by another screen. To determine if your application is in the foreground, you can invoke Application.isForeground(). If this method 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 this method returns false, no UI elements are visible to the user. The backlight turns off automatically after a period of inactivity. Your application should not keep the backlight on unless the device is connected to a charger, or if screen visibility is critical to the application. To determine how long the device has been idle, you can invoke Device.getIdleTime(). To prevent any potential UI lag or latency, your application should perform processor-intensive operations when the device is idle.

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

BlackBerry® Push Service SDK Development Guide

Using location services effectively The Highly contextualized chapter describes how location is an important context to consider when you're designing your application. You can use GPS technology on the BlackBerry® device to add this context to your application, but you 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 GPS and geolocation. For example, the Bookshelf application should notify BlackBerry device users when they are in the area of a released book. Because maintaining a GPS fix at all times can consume battery power, Bookshelf might obtain a GPS fix only periodically, with an option for more frequent fixes that the user can select. Bookshelf might also 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 scan of the sky. A full scan of the sky involves locating and connecting to GPS satellites and obtaining a GPS fix using the information 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 to provide a good user experience. For example, your application might not need to maintain the user's exact position

57


Development Guide

Using location services effectively

at all times, but instead can provide a good user experience if the application obtains a fix every ten minutes. If your application needs to track the user's position more precisely, you can decrease the time between fixes, at the cost of 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 requests until a fix is successful. Your application should use assisted GPS mode sparingly. Assisted GPS mode obtains a GPS fix by communicating with the wireless service provider to retrieve satellite information. This method provides a fix very quickly and consumes less battery power than other GPS modes, but it relies on the wireless service provider and increases their costs, as well as any network costs that are associated with communicating with the wireless service provider. You should design your application to use assisted GPS mode to obtain an initial fix before switching to autonomous GPS mode. If you want your application to obtain a fix using a particular GPS mode (for example, assisted GPS or autonomous GPS), your application should check to see if that mode is available by invoking GPSInfo.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 the latitude, longitude, and horizontal accuracy based on the positioning of cell towers and WLAN access points. If your application doesn't require the user's exact position, the geolocation service can be an excellent approach and can save substantial amounts of battery power. The geolocation service can also function indoors, making it feasible to use in applications that don't always have access to GPS satellites (for example, applications that recommend local points 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 location of the device. // specify the geolocation mode BlackBerryCriteria myBlackBerryCriteria = new BlackBerryCriteria(LocationInfo.GEOLOCATION_MODE); // retrieve a location provider BlackBerryLocationProvider myBlackBerryProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myBlackBerryCriteria); // request a single geolocation fix BlackBerryLocation myBlackBerryLoc = myBlackBerryProvider.getLocation(timeout); // retrieve the geolocation of the device

58


Development Guide

Using the Profiler tool

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 tool This chapter describes best practices for making your application more efficient. This chapter describes how to respond 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 designing your 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 the Bookshelf application creates a new object every time the application receives new location information for a book from the Bookshelf web service, Bookshelf probably isn't using objects as efficiently as it could. It might be more efficient 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 the BlackBerry® Java® Development Environment or the BlackBerry® Java® Plug-in for Eclipse®. You can use the Profiler tool to identify what threads are running at any point in the execution of your application, how long methods take to 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 in clock 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 vary depending on factors such as device model, number of other applications running simultaneously, whether the method is running on a device or on a simulator, and so on. Instead, the comparison of the number of clock ticks that two methods that perform the same function take is more useful, and you can use this data to determine which method is more efficient. In general, you shouldn't try to reduce profiler metrics individually. Instead, you should use these metrics to help identify areas of inefficiency in your application. You can also use profiler metrics to identify bottlenecks in your application'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 implementations of 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.

59


Using the Profiler tool

Development Guide

Metric Time spent in methods

Samples

Objects created

Objects committed

Description You can determine the percentage of application execution time that was spent in each method in your application. If you have two methods that perform similar tasks, but one method takes substantially less time to run, you should examine the methods for opportunities to optimize the slower method. You can perform this type of profiling on a BlackBerry Smartphone Simulator only. You can determine what your application is doing at any point during execution. Approximately every ten milliseconds, the Profiler tool queries your application, and your application responds with a stack trace (a sample). The higher the number of samples for a method, the longer that method is taking to run. If a method produces a large number of samples relative to other methods in your application, this method might be a candidate for optimization. You can perform this type of profiling on both a BlackBerry Smartphone Simulator and a device. You can determine how many objects your application creates during execution. Object allocation and garbage collection are the primary reasons for UI lag or latency in an application, so if a method creates a large number of objects relative to other methods in your application, you should examine the objects to determine if they are all required. Your application should reuse objects whenever possible. You can perform this type of profiling on a BlackBerry Smartphone Simulator only. You can determine how many objects your application writes to memory on the device during execution. Committing objects to memory is an expensive operation (in terms of execution time), so you should minimize these operations whenever possible. If your application must commit objects to memory, make sure that the objects are grouped so that they can be committed at the same time, instead of individually. Your application should also commit objects at the end of a full transaction or event. You can perform this type of profiling on a BlackBerry Smartphone Simulator only.

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

60

BlackBerry Java Plug-in for Eclipse Development Guide


Storing data on the device

Development Guide

Storing data on the device The Social and connected chapter describes how to capture audio and video in your application by using the javax.microedition.media.Player class. In the code samples in that chapter, the audio and video files are stored in internal storage on the BlackBerry速 device by specifying a record location of file:///Store/... You can choose from several data storage options to store data or files that your application creates. Each storage option has advantages and disadvantages, and you should carefully consider which option to use based on the type of data that your application needs to store. You can help make your application efficient by choosing the most appropriate storage location and storage option for your application's data. For example, the Bookshelf application needs to store information about a book that you have released, such as comments about the book or the book's current location. Storing this information on the device is probably more efficient than querying the Bookshelf web service whenever the user requests this information. 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 the information 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 your application creates. Data storage option File system

SQLite

Persistent store

Description You can use this data storage option to create and manage the files and folders on a BlackBerry device or on an external media card by using the File Connection API. The File Connection API is implemented in the javax.microedition.io.file package. Files that your application creates on a file system are not removed automatically when your application is removed from the device. You can use this data storage option to create and use SQLite relational databases by using the Database API. SQLite databases require no configuration or administration and are very small (around 300 KB). You can create SQLite databases in internal storage or on an external media card. SQLite databases that your application creates are not removed automatically when your application is removed from the device. You can use this data storage option to save objects in persistent memory on the device by using the Persistent Store API. Data is stored as PersistentObject objects, and these objects are retained in memory after the device restarts. PersistentObject objects that your application defines are removed

automatically when your application is removed from the device.

61


Storing data on the device

Development Guide

Data storage option MIDP RMS

Runtime store

Description You can use this data storage option to save data in persistent memory by using the MIDP RMS. The MIDP RMS is modeled after a simple recordoriented 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 removed automatically when your application is removed from the device. You can use this data storage option to store information and share that information between applications on the device by using the Runtime Store API. Data that your application stores in the runtime store is not retained after the device restarts. Before you close your application, you should remove objects from the runtime 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 following considerations: •

• • •

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 when needed. In many cases, the best approach is to store data across device resets only when the data is frequently accessed. The file system and MIDP RMS are standards-based approaches, and the persistent store and runtime store are specific to BlackBerry devices. If you want your application to run on other Java® ME compatible devices, you should consider a standards-based approach. The file system is typically the most efficient storage location for large, read-only files such as videos or large graphics. 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 more efficiently. If you use the runtime store in your application, make sure that you remove objects that your application adds to the runtime store when they are no longer required. Failing to remove objects from the runtime store is a common cause of memory leaks in BlackBerry device applications. The BlackBerry® Java® Virtual Machine includes a garbage collection tool, which runs periodically to remove unreferenced objects and weakly referenced objects from memory. To take advantage of this functionality in your application, you should release objects by setting their references to null after your application is done with them.

Code sample: Creating a file in internal storage

62


Development Guide

Storing data on the device

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

net.rim.device.api.system.Application; javax.microedition.io.*; javax.microedition.io.file.*; 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());

63


Development Guide

}

}

}

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

64

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

Storing data on the device


Development Guide

Glossary

Glossary

8

API application programming interface GPS Global Positioning System HTTP Hypertext Transfer Protocol IT information technology Java ME Java速 Platform, Micro Edition JSR Java速 Specification Request MIDP Mobile Information Device Profile MIME Multipurpose Internet Mail Extensions MMS Multimedia Messaging Service PAP Push Access Protocol PIN personal identification number PPG Push Proxy Gateway QR quick response RMS Record Management System

65


Development Guide

SMS Short Message Service WAP Wireless Application Protocol WLAN wireless local area network XML Extensible Markup Language

66

Glossary


Development Guide

Provide feedback

Provide feedback

9

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

67


Development Guide

Legal notice

Legal notice

10

息2010 Research In Motion Limited. All rights reserved. BlackBerry速, RIM速, Research In Motion速, and related trademarks, names, and logos are the property of Research In Motion Limited and are registered and/or used in the U.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 trademark of Eclipse Foundation, Inc. GSM is a trademark of GSM MOU Association. Java and JavaScript are trademarks of Oracle America, Inc. Microsoft is a trademark of Microsoft Corporation. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are the property of their respective owners. This documentation including all documentation incorporated by reference herein such as documentation provided or made available at www.blackberry.com/go/docs is provided or made accessible "AS IS" and "AS AVAILABLE" and without condition, endorsement, guarantee, representation, or warranty of any kind by Research In Motion Limited and its affiliated companies ("RIM") and RIM assumes no responsibility for any typographical, technical, or other inaccuracies, errors, or omissions in this documentation. In order to protect RIM proprietary and confidential information and/or trade secrets, this documentation may describe some aspects of RIM technology in generalized terms. 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 this documentation to you in a timely manner or at all. This documentation might contain references to third-party sources of information, hardware or software, products or services including components and content such as content protected by copyright and/or third-party web sites (collectively the "Third Party Products and Services"). RIM does not control, and is not responsible for, any Third Party Products and Services including, without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Services in this documentation does not imply endorsement by RIM of the Third Party Products and Services or the third party in any way. EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS OR WARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NON-INFRINGEMENT, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROM THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE CLAIM. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL RIM BE LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NONPERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES 68


Development Guide

Legal notice

REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL, PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGES FOR LOSS OF PROFITS OR REVENUES, FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH RIM PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OF SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN IF 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 OTHER OBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY. THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THE CAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO BREACH OF CONTRACT, NEGLIGENCE, TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B) TO RIM AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIME SERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIR RESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS. IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY DIRECTOR, EMPLOYEE, AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF RIM OR ANY AFFILIATES OF RIM HAVE ANY LIABILITY ARISING FROM OR RELATED TO THE DOCUMENTATION. Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to ensure that your airtime service provider has agreed to support all of their features. Some airtime service providers might not offer Internet browsing functionality with a subscription to the BlackBerry速 Internet Service. Check with your service provider for availability, roaming arrangements, service plans and features. Installation or use of Third Party Products and Services with RIM's products and services may require one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third party rights. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licenses are required to do so. If required you are responsible for acquiring them. You should not install or use Third Party Products and Services until all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIM's products and services are provided as a convenience to you and are provided "AS IS" with no express or implied conditions, endorsements, guarantees, representations, or warranties of any kind by RIM and RIM assumes no liability whatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties, except to the extent expressly covered by a license or other agreement with RIM. Certain features outlined in this documentation require a minimum version of BlackBerry速 Enterprise Server, BlackBerry速 Desktop Software, and/or BlackBerry速 Device Software.

69


Development Guide

Legal notice

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

Research In Motion Limited 295 Phillip Street Waterloo, ON N2L 3W8 Canada Research In Motion UK Limited Centrum House 36 Station Road Egham, Surrey TW20 9LF United Kingdom Published in Canada

70


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.