You are on page 1of 133

BlackBerry Java SDK

Integration Version: 6.0


Development Guide

Published: 2010-12-23 SWD-1244681-1224095254-001

Contents
1 Integrating with BlackBerry Device Software applications............................................................................... Invoke a BlackBerry Device Software application............................................................................................. 2 Unified search................................................................................................................................................... Making data findable........................................................................................................................................ Exposing your application data.................................................................................................................. Passing queries to other search engines................................................................................................... Define an EntityBasedSearchable class for your SearchableEntity objects...................................................... Customizing the appearance of your data in search results...................................................................... Specify an icon in the EntityBasedSearchable or SearchableEntity class.................................................. Encapsulate your data in the SearchableEntity class........................................................................................ Register your EntityBasedSearchable object with the Unified Search Service................................................. Notify the Unified Search Service about changes to your data........................................................................ Listening for responses from the Unified Search Service................................................................................. Removing your data from the content repository............................................................................................ Using other search engines............................................................................................................................... Ensure that a device runs a single instance of your application....................................................................... Inserting data when a device starts.................................................................................................................. Searching.......................................................................................................................................................... Configure and start a search...................................................................................................................... Process search results................................................................................................................................ 3 Device interaction support............................................................................................................................... Device Capability API........................................................................................................................................ Cradle detection............................................................................................................................................... Cradle handling................................................................................................................................................. Working with sensors on a device.................................................................................................................... Check for a sensor on the device............................................................................................................... Check the state of a sensor....................................................................................................................... Notify an application when the state of a sensor changes........................................................................ Code sample: Working with a sensor........................................................................................................ 4 Message list...................................................................................................................................................... Create a new blank SMS text message............................................................................................................. Create a new populated text message............................................................................................................. Create a new blank MMS message................................................................................................................... Create a new blank email message................................................................................................................... Create a new populated email message........................................................................................................... 6 6 7 7 7 9 10 12 13 13 15 16 16 17 18 20 22 22 22 23 25 25 25 27 28 28 29 30 31 34 34 34 34 35 35

Create a new blank PIN message...................................................................................................................... Create a new populated PIN message.............................................................................................................. Receive a message notification......................................................................................................................... Add a listener to the message store................................................................................................................. Add a listener to the message store for batch updates.................................................................................... Add a listener to a folder.................................................................................................................................. Retrieve the total count of unread email messages in all folders in the store................................................. Open a message................................................................................................................................................ Retrieving the body of an email message......................................................................................................... Retrieve the plain text and HTML content in the body of an email message using a recursive method ................................................................................................................................................................... Retrieve the plain text content of an email message................................................................................ Retrieve the HTML content of an email message...................................................................................... Notify a BlackBerry device application that an email message is about to be sent.......................................... Notify a BlackBerry device application that an MMS message is about to be sent.......................................... Notify a BlackBerry device application that an SMS message is about to be sent........................................... Send a message................................................................................................................................................ Reply to a message........................................................................................................................................... Forward a message........................................................................................................................................... Work with message folders.............................................................................................................................. 5 Custom messages............................................................................................................................................. Using custom messages and folders in the message list.................................................................................. Creating a module for background processes.................................................................................................. Creating a module for the UI............................................................................................................................ Create a module for background processes..................................................................................................... Start the module for background processes or the module for the UI............................................................. Create an icon for a custom message............................................................................................................... Create a custom folder in the message list....................................................................................................... Send a notification when a custom folder changes.......................................................................................... Create a custom indicator................................................................................................................................. Hide an indicator............................................................................................................................................... Remove a custom indicator.............................................................................................................................. 6 Attachments..................................................................................................................................................... Create an attachment handler.......................................................................................................................... Retrieve the contents of an attachment........................................................................................................... Retrieve information about an attachment...................................................................................................... Send a message with an attachment................................................................................................................

35 36 36 37 37 38 38 38 39 40 42 43 46 46 47 47 49 50 51 53 53 53 53 53 54 55 56 57 58 58 59 60 60 61 61 61

Download attachments automatically.............................................................................................................. 7 Calendar............................................................................................................................................................ Open the calendar............................................................................................................................................ View or change a calendar entry...................................................................................................................... Open a new populated calendar entry............................................................................................................. Update calendar entry information.................................................................................................................. Retrieve calendar entry information................................................................................................................ Export a calendar entry.................................................................................................................................... Import a calendar entry.................................................................................................................................... Retrieve multiple lists of calendar entries........................................................................................................ Notify a BlackBerry device application when a list of calendar entries changes.............................................. Notify a BlackBerry device application when the default list of calendar entries changes.............................. Update a calendar entry with no notification................................................................................................... Remove a calendar entry with no notification................................................................................................. 8 Contact list........................................................................................................................................................ Multiple contact lists support........................................................................................................................... Open the contacts application.......................................................................................................................... Open the contacts application by using contact data....................................................................................... Open the contacts application with a specific contact list............................................................................... Create a contact and assign it to a contact list................................................................................................. Retrieve contact information............................................................................................................................ Retrieve a contact list UID................................................................................................................................ Export a contact................................................................................................................................................ Import a contact............................................................................................................................................... Delete a contact................................................................................................................................................ Notify an application when a contact list changes........................................................................................... Creating and removing contact lists................................................................................................................. Create a contact list................................................................................................................................... Remove a contact list................................................................................................................................ Retrieve the contact that is associated with an active call............................................................................... Retrieve the contact that is associated with a completed call......................................................................... Retrieve contacts by phone number................................................................................................................ Linking third-party contacts with contacts in the Contacts application........................................................... Link a contact............................................................................................................................................. Remove a link............................................................................................................................................ Creating menu items for linked contacts................................................................................................... Create menu items for linked contacts.....................................................................................................

62 64 64 64 64 65 67 68 69 69 70 70 71 72 74 74 74 75 75 77 78 79 79 80 81 82 83 83 85 86 87 88 89 90 91 91 92

Create an information provider for a linked contact................................................................................. 9 Task list............................................................................................................................................................. View or change a task....................................................................................................................................... Create a new blank task.................................................................................................................................... Create a new populated task............................................................................................................................ Open a task list................................................................................................................................................. Create a task..................................................................................................................................................... Add task information........................................................................................................................................ Change task information................................................................................................................................... Save a task........................................................................................................................................................ Retrieve task information................................................................................................................................. Export a task..................................................................................................................................................... Import a task..................................................................................................................................................... Delete a task..................................................................................................................................................... Close the task list.............................................................................................................................................. Notify a BlackBerry device application when a list of tasks changes................................................................ 10 Phone................................................................................................................................................................ Making a call from a BlackBerry device application......................................................................................... Make a call from a BlackBerry device application (single-line environment)................................................... Make a call from a BlackBerry device application (multi-line environment).................................................... Add DTMF tones to the send queue................................................................................................................. BlackBerry DTMF tones..................................................................................................................................... Listen for and handle phone events................................................................................................................. Listen for and handle multi-line events............................................................................................................ Retrieve call information by using call logs....................................................................................................... Retrieve a call participant................................................................................................................................. Retrieve call information.................................................................................................................................. Retrieve the phone number of a BlackBerry device......................................................................................... Retrieve a call by call ID.................................................................................................................................... Displaying content on a call screen................................................................................................................... Display content on a phone screen........................................................................................................... Code sample: Displaying content on a phone screen................................................................................ Displaying content on devices that operate on a CDMA network.............................................................

93 96 96 96 96 97 97 98 98 99 99 100 100 101 101 102 103 103 103 103 104 104 104 105 106 106 106 107 107 108 108 110 111

11 BlackBerry Browser........................................................................................................................................... 113 Retrieve a BlackBerry Browser session............................................................................................................. 113 Retrieve a non-default BlackBerry Browser session......................................................................................... 113

Request a web page.......................................................................................................................................... Enhanced support for web content in BlackBerry device applications............................................................ Display HTML content in a browser field................................................................................................... Display HTML content from a web page in a browser field....................................................................... Display HTML content from a resource in your application...................................................................... Configure a browser field.......................................................................................................................... Send form data to a web address in a browser field.................................................................................

113 113 114 115 116 117 118

12 Menu items....................................................................................................................................................... 120 Adding menu items to BlackBerry Device Software applications..................................................................... 120 Create and register a menu item...................................................................................................................... 120 13 Find more information...................................................................................................................................... 122 14 Glossary............................................................................................................................................................ 123 15 Provide feedback.............................................................................................................................................. 125 16 Document revision history................................................................................................................................ 126 17 Legal notice....................................................................................................................................................... 129

Development Guide

Integrating with BlackBerry Device Software applications

Integrating with BlackBerry Device Software applications

This section describes how to invoke a BlackBerry Device Software application, such as the contacts application, the phone application, and the media application. For more information about integrating your application with BlackBerry Device Software applications, see the Application Integration category overview in the API reference for the BlackBerry Java Development Environment.

Invoke a BlackBerry Device Software application


You can create BlackBerry device applications that invoke BlackBerry Device Software applications such as the messages application, the phone application, and the media application. When your application invokes a BlackBerry Device Software application, the application can make the BlackBerry Device Software application perform an action or display information. 1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.invoke.CalendarArguments; net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.MapsArguments; net.rim.blackberry.api.invoke.MessageArguments; net.rim.blackberry.api.invoke.PhoneArguments;

2.

Invoke the Invoke.invokeApplication() method and use the appropriate parameters. For example: To start the messages application and create a new blank SMS message, invoke the Invoke.invokeApplication() and use the following parameters: Invoke.APP_TYPE_MESSAGES and a MessageArguments object that uses the ARG_NEW_SMS field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_SMS) );

To start the calendar, invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments). To start the phone application, invoke Invoke.invokeApplication (APP_TYPE_PHONE,PhoneArguments). To start BlackBerry Maps and display the default map view, invoke Invoke.invokeApplication() and provide as parameters Invoke.APP_TYPE_MAPS and a new MapsArguments object.
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments() );

For more information about using the net.rim.blackberry.api.invoke.Invoke class, see the API reference for the BlackBerry Java Development Environment.

Development Guide

Unified search

Unified search

The Unified Search Service is a search engine that is included with BlackBerry Device Software 6.0 and later. BlackBerry device users interact with the Unified Search Service primarily from the Universal search feature by clicking the search icon on the Home screen. Developers can use Unified Search Service through the Unified Search API. You can use the API to include your application data in the Service's content repository, and search the content index from your application. For example, imagine that you have a large collection of books and you loan them to people frequently. It might be useful to create an application that allows you to catalog your books, and keep a list of people to whom you loan them. If this application used the Unified Search API, you could search for a book from the Home screen, or any application, to find the book and contact details for the person who holds it. As a developer, you control whether your data appears in searches that users perform from the Home screen of a BlackBerry device, other applications on the device, or your application only. In addition, you can search data from other applications when that data is registered in the Unified Search Service.

Making data findable


There are two ways to include your data in search results from the Unified Search Service. If you want to expose the data in your application, you need to implement the EntityBasedSearchable interface. In this scenario, you must wrap your data in a class that implements the SearchableEntity interface. If you want to pass a search query to your own search engine, located on a network server or within your application, you need to implement the ExternalSearchProvider interface. Search engines that are available on a server might be located behind an organization's firewall or be a public web service.

Exposing your application data


The Unified Search Service maintains an index of content on a BlackBerry device. Your application uses the SearchRegistry, AppContentManager, and AppContentListener classes to communicate with the Unified Search Service. To make the data in your application findable, you need to complete five tasks. Task Define an
EntityBasedSearchable class for your SearchableEntity

objects.

Encapsulate your data in a SearchableEntity object.

Description An EntityBasedSearchable object represents your searchable data to the Unified Search Service. When you register your EntityBasedSearchable, the Service requests that your application prepare data for submission by calling EntityBasedSearchable.load (). When your application data is ready for submission, you should invoke completed() on the NotificationListener parameter passed to load(). A SearchableEntity object is the smallest unit of data that an application can submit to the Unified Search Service. Your EntityBasedSearchable object sends your SearchableEntity objects to the Service when asked. You need to encapsulate your application
7

Development Guide

Making data findable

Task

Description data in a SearchableEntity object. The Service indexes the metadata that is exposed by these objects for consideration during search operations. Also, SearchableEntity objects are returned in search results from the Service. The Unified Search Service may need interrupt your load operation if the BlackBerry device is busy, or has a low battery power level. If an interruption is necessary, the Service invokes EntityBasedSearchable.pause(). When the Service detects that your operation can continue, it invokes EntityBasedSearchable.resume(). Respond to these events in a timely manner so that your application does not cause disruption to other applications on the device. After you notify the Unified Search Service that your data is ready, it calls EntityBasedSearchable.getSearchableEntities() to index your data. The Service may invoke load() and getSearchableEntities() again if it detects that its content index and your data are not synchronized. After you prepare your data for search, and define how it will be indexed, you must register your EntityBasedSearchable with the Unified Search Service. Pass your EntityBasedSearchable when you invoke SearchRegistry.register(). The Service then retrieves and indexes your data for inclusion in search results. To notify the content index about changes to your application data, use the insert(), delete(), and update() methods in the AppContentManager object. When you notify the Unified Search Service about changes to your application data, you should provide an AppContentListener object where the Service can notify your application about the result of your request.

Register your
EntityBasedSearchable object

with the Unified Search Service.

Notify the Unified Search Service about changes to your data. Listening for responses from the Unified Search Service.

The following diagram illustrates the relationship between the components that are used in the previous tasks.

Development Guide

Making data findable

Passing queries to other search engines


You can use the ExternalSearchProvider interface to pass queries to another search engine. For example, an application on a BlackBerry device that has an efficient way to search its own data could give users and other applications access to its data by implementing the ExternalSearchProvider. Alternatively, an insurance company may have an application that allows sales representatives to search an insurance policy database. The company could provide its sales representatives with access to the policy search engine behind the firewall, from a BlackBerry device, by implementing theExternalSearchProvider. Users can extend a search in two ways. The Universal search feature from the Home screen lists external search providers at the end of the search result list. If a user clicks the icon for your application in the search result, the Unified Search Service invokes search() from your ExternalSearchProvider object. Your application is then responsible for creating a connection to the search provider (another application, or over a network), passing the query string, and displaying any results that you retrieve. Other applications can invoke your application in a similar way. The UnifiedSearchServices.getSearchProviders() method returns a list of all external search providers that installed on a BlackBerry device. In this way, an application can find and use your ExternalSearchProvider specifically, or allow the user to choose one from the list. To ensure that your application appears in the list of external search providers, you must register your ExternalSearchProvider with the Unified Search Service. Pass your ExternalSearchProvider object when you invoke SearchRegistry.register(). The following diagram shows the relationship between some of the components that required to implement ExternalSearchProvider.

Development Guide

Define an EntityBasedSearchable class for your SearchableEntity objects

Define an EntityBasedSearchable class for your SearchableEntity objects


Your implementation of the EntityBasedSearchable interface manages the relationship between the Unified Search Service and the searchable entities that you create. Each EntityBasedSearchable object manages a group of SearchableEntity objects that have the same searchable properties. 1. Import the required classes and interfaces.
import net.rim.device.api.unifiedsearch.SearchField; import net.rim.device.api.unifiedsearch.searchables.EntityBasedSearchable; import net.rim.device.api.unifiedsearch.searchables.SearchableContentTypeConstants; import net.rim.device.api.unifiedsearch.searchables.Searchable;

2.

Create instance variables to store information that is relevant to your EntityBasedSearchable.


private private private private private private MySearchableEntity[] _myEntities; // You will need this in steps 8 and 11 long _registrationID; SearchField[] _searchFields; Image _icon; final Object _monitor = new Object(); boolean _wait = false;

3.

In the constructor, create an array of SearchField objects. Each SearchField stores the name of one searchable property of your data. In the following code sample, the application data objects that are managed by this class have three searchable properties. For example, if your application data modeled books, these fields might include the title, the publisher, and number of pages.
class MyEBS implements EntityBasedSearchable { _searchFields = new SearchField[3];

4.

Assign a meaningful name to each SearchField.

10

Development Guide

Define an EntityBasedSearchable class for your SearchableEntity objects

_searchFields[0] = new SearchField("Title"); _searchFields[1] = new SearchField("Publisher"); _searchFields[2] = new SearchField("Number of pages");

5.

6.

Create an icon to appear in search results that include searchable entities managed by this EntityBasedSearchable. For more information about creating icons, see "Customizing the appearance of your data in search results." Implement getType(). Return the content type that best matches your application data. For a list of valid content types, see the net.rim.device.api.unifiedsearch.searchables.SearchableContentTypeConstants interface in the API reference.
public long getType() { return SearchableContentTypeConstants.CONTENT_TYPE_MEMO;

7.

Choose the search initiators that should receive search results from your application. For more information about exposing your data to searches, see net.rim.device.api.unifiedsearch.entity.ExposureLevel class in the API reference.
public int getPrivacyLevel() { return ExposureLevel.LEVEL_PUBLIC; }

8.

Implement load(). If the BlackBerry device is busy, or the battery power level is low, you may need to pause the operation of this method, and resume it when requested. a. For your EntityBasedSearchable, determine how many data objects currently exist in your application.
public void load (NotificationListener observer, int loadType) { Vector myObjects = MyObjectManager.getDataObjects(); if (myObjects != null) { int size = myObjects.size() if(size < 1) { _myEntities = new MySearchableEntity[0]; } else { _myEntities = new MySearchableEntity[size]; } } else { // handle the condition where you have no data objects }

b.

Use a while loop to populate an array of searchable entities.


Enumeration objects = myObjects.elements(); int count = 0; while (objects.hasMoreElements()) {

c.

Check whether the Unified Search Service has sent a pause command. If so, pause the operation that populates your arrray of searchable entities and notify the Service.
if (_wait){ try { synchronized(_monitor) { 11

Development Guide

Define an EntityBasedSearchable class for your SearchableEntity objects

observer.partiallyCompleted(this, null, NotificationListener.TYPE_SEARCHABLE); _monitor.wait(); } } catch (InterruptedException e){ observer.error(e); return; } }

d.

When your application has control of the thread again, continue to populate your array of searchable entities.
MyObject dataObject = (MyObject) objects.nextElement(); _myEntities[count++] = new MySearchableEntity(dataObject, this);

e.

Notify the Unified Search Service that your are done loading your data.
} observer.completed(this, NotificationListener.TYPE_SEARCHABLE);

9.

The Unified Search Service invokes getSearchableEntities() next to retrieve the array you populated. In pause(), change the value of the _wait variable to true. The Unified Search Service calls this method when it wants your application to stop loading data.
public void pause() { _wait = true; }

10. In resume(), change the value of the _wait variable to false. Also, notify the load() method that it can resume execution. The Unified Search Service invokes resume() when it wants your application to resume loading data.
public void resume() { _wait = false; synchronized(_monitor) { _monitor.notifyAll(); } }

11. In getSearchableEntities(), return the _myEntities array that you created in step 8.
public SearchableEntity[] getSearchableEntities() { return _myEntities; }

Customizing the appearance of your data in search results


The getIcon() method, in the EntityBasedSearchable and SearchableEntity interfaces, specifies the icon that appears in search results. In the Universal search feature on the Home screen, search results are grouped by application. The EntityBasedSearchable.getIcon() method specifies the icon that appears for the group.

12

Development Guide

Encapsulate your data in the SearchableEntity class

You can also specify an icon for different categories of related searchabe entities. For example, if you create an application that catalogs books you might want to have different icons for different categories of books, such as best sellers, oversized, and first editions. These categories are all types of books, so they would logically fall under one EntityBasedSearchable object that managed books. However, an application that displays them might want to give a visual cue to help a user quickly determine whether to find a book on a regular shelf, a large shelf, or in an environmentally controlled room. In this case, you could create three SearchableEntity classes to wrap three different kinds of book objects, each with its own implementation of getIcon() . All three classes would still be managed by a single EntityBasedSearchable.

Specify an icon in the EntityBasedSearchable or SearchableEntity class


Before you begin: Include a suitable graphic file for use as an icon in your project's resource folder. For more information about designing graphics for BlackBerry devices, see UI Guidelines. 1. Import the required classes.
import net.rim.device.api.ui.image.Image; import net.rim.device.api.ui.image.ImageFactory; import net.rim.device.api.system.Bitmap;

2. 3. 4.

Create an instance variable to store the icon.


private Image _icon;

Import the graphic into your application from your resource folder.
Bitmap img = Bitmap.getBitmapResource("icon.png")

Check whether the import was successful, then create an icon.


if(img != null) { _icon = ImageFactory.createImage(img); } else { _icon = null; }

5.

In getIcon(), return the image.


public Image getIcon() { return _icon; }

Encapsulate your data in the SearchableEntity class


The Unified Search Service indexes the metadata that is exposed by a SearchableEntity object. The Service also returns a SearchableEntity as the content of a search result. You must prepare your application data for the Service by encapsulating it in your SearchableEntity class. 1. Import the required classes and interfaces.

13

Development Guide

Encapsulate your data in the SearchableEntity class

import import import import import

net.rim.device.api.unifiedsearch.SearchField; net.rim.device.api.unifiedsearch.SearchFieldCriteria; net.rim.device.api.unifiedsearch.SearchFieldCriteriaList; net.rim.device.api.unifiedsearch.entity.SearchableEntity; net.rim.device.api.unifiedsearch.searchables.Searchable;

2. 3.

Retrieve an array of SearchField objects from your EntityBasedSearchable.


SearchField[] searchfields = mySearchable.defineSupportedSearchFields();

Create a SearchFieldCriteria object for each of your searchable properties. In the following code sample, the application data object myObject has a getProperty() method that returns a string for a given index. For example, if myObject described a book, then indicies 0, 1, and 2 of getProperty() could return the name, the publisher, and the number of pages in the book.
int size = searchfields.length SearchFieldCriteria[] criteria = new SearchFieldCriteria[size]; for (int i = size -1; i >= 0; --i) { criteria[i] = new SearchFieldCriteria(searchfields[i], new String[] {myObject.getProperty(i)}); }

4.

Create and populate a SearchFieldCriteriaList object to hold your search field criteria.
SearchFieldCriteriaList _sfcl = new SearchFieldCriteriaList(); for (int i = size -1; i >= 0; --i) { sfcl.addCriteria(criteria[i]); }

5.

Implement getSearchCriteria() to return your SearchFieldCriteriaList.


pubic SearchFieldCriteriaList getSearchCriteria() { return _sfcl; }

6.

In getData(), return your application data object. To continue with the book example, this method would return an object that represents the book.
public Object getData() { return myObject; }

7.

In getTitle(), assign a title to this searchable entity. The title text appears in search results. To continue with the book example, myObject.getName() could return the name of a book.
public String getTitle() { return myObject.getName(); }

8.

In getSummary() provide a summary of the data in this searchable entity. The summary text appears in search results. Continuing with the book example, myObject.getDescription() could return a description of the book.
public String getSummary() { return myObject.getDescription(); }

14

Development Guide

Register your EntityBasedSearchable object with the Unified Search Service

9.

Implement getSearchable(). Retrieve the EntityBasedSearchable that your application creates to manage this object, and return it.
public Searchable getSearchable() { return myPublisher.getSearchable(); }

10. Define what options should appear on the context menu when a BlackBerry device user clicks on your entity in a list of search results. For more information, see "Specify what users can do with your data in search results". 11. If you want this SearchableEntity to display a different icon than your application icon, provide the icon in getIcon(). For more information, see "Customize the appearance of your data in search results".

Register your EntityBasedSearchable object with the Unified Search Service


After you have defined your SearchableEntity class, and created an EntityBasedSearchable class to represent your searchable entities to the Unified Search Service, use the SearchRegistry to register them with the Unified Search Service. 1. Import the required classes and interfaces.
import net.rim.device.api.unifiedsearch.registry.RegistrationToken; import net.rim.device.api.unifiedsearch.registry.SearchRegistry;

2.

Create your EntityBasedSearchable.


public class MyClass { private MySearchable _searchable; private RegistryToken _regToken; public MyClass() { _searchable = new MySearchable()

3. 4.

Register your EntityBasedSearchable with the Unified Search Service.


_regToken = SearchRegistry.getInstance().register(_searchable);

It is a good practice to test whether the registration was successful.


if (! _regToken.isValid()) { // Action to take if the registration is not valid. }

Note: The registration token is unique to your EntityBasedSearchable until the BlackBerry device restarts. You should store your registration token and reuse it when you update content using the AppContentManager class.

15

Development Guide

Notify the Unified Search Service about changes to your data

Notify the Unified Search Service about changes to your data


When your application changes, deletes, or creates new searchable data, you can notify the Unified Search Service about the changes by using the AppContentManager object. Before you begin: Retrieve a registration token to communicate with the Unified Search Service. An application retrieves a registration token when it registers an EntityBasedSearchable object. Define a variable (such as _myListener in the following code sample) for an AppContentListener implementation. For more information, see "Listening for responses from the Unified Search Service". 1. 2. Import the required classes and interfaces.
import net.rim.device.api.unifiedsearch.content.AppContentManager;

To update a SearchableEntity object that the Unified Search Service has already indexed, invoke updateContent().
public void updateUSS(MyEntity entity, RegistrationToken regToken) { MyEntity[] toUpdate = new MyEntity[1]; toUpdate[0] = entity; AppContentManager.getInstance().updateContent(toUpdate, _myListener, regToken); }

3.

To delete a SearchableEntity object, invoke deleteContent().


public void deleteUSS(MyEntity entity, RegistrationToken regToken) { MyEntity[] toDelete = new MyEntity[1]; toDelete[0] = entity; AppContentManager.getInstance().deleteContent(toDelete, _myListener, regToken); }

4.

To insert a new SearchableEntity, invoke the insertContent() method.


public void insertUSS(MyEntity entity, RegistrationToken regToken) { MyEntity[] toInsert = new MyEntity[1]; toInsert[0] = entity; AppContentManager.getInstance().insertContent(toInsert, _myListener, regToken); }

Listening for responses from the Unified Search Service


When you manipulate content with AppContentManager methods, you should specify class that implements the AppContentListener interface. After the Unified Search Service has processed your request, it notifies the AppContentListener method that corresponds to the operation that you requested. Each AppContentManager method has a parameter that tells you how many objects were affected by the operation. If the operation fails, the value of the parameter is 0.

16

Development Guide

Removing your data from the content repository

Code sample: Implementing the AppContentListener interface


public class MyListener implements AppContentListener { public void onDeleteComplete(int delCount) { // Action to take after records deleted. } public void onInsertComplete(int insertCount) { // Action to take after new records inserted. } public void onUpdateComplete(int updCount) { // Action to take after records updated. }

Removing your data from the content repository


Depending on your application life cycle, you might need to remove all of your application data from the Unified Search Service content repository. For example, a BlackBerry device user may have multiple accounts for your application. It may make sense for the application data to appear in search results only if the user is currently authenticated by your application. Alternatively, your application may need to respond to locale changes. In this case, you should remove data from the content repository, then repopulate it with the data that is appropriate to the current locale. The following table describes two approaches to remove all of your application data from the Unified Search Service content repository. Approach Deregister an Description This approach removes your EntityBasedSearchable object, and all EntityBasedSearchable object. data associated with it, from the Unified Search Service content index. Your EntityBasedSearchable no longer appears in the list of registered searchable data sources on the BlackBerry device. To deregister an EntityBasedSearchable, invoke SearchRegistry.deregister(), and pass the registration token returned when that EntityBasedSearchable was registered. Remove all data from the content repository for an EntityBasedSearchable object. This approach removes all of your application data from the repository. You can use this approach when you need to remove all data, but you expect that you will continue to populate the repository with new data in the near future.

17

Development Guide

Using other search engines

Approach

Description To remove all data from the content repository for an EntityBasedSearchable, invoke UnifiedSearchServices.removeAllData() and pass the registration token that was returned when that EntityBasedSearchable was registered.

Using other search engines


The ExternalSearchProvider interface lets BlackBerry users search data outside of the Unified Search Service. If a user receives an unsatisfactory search result, can click on other external search providers when using the Universal search feature from the Home screen. These search providers implement the ExternalSearchProvider interface. When a user clicks a search provider, the Universal search feature invokes search() for that ExternalSearchProvider. The search provider is responsible for creating a network connection or interprocess communication connection, invoking a search on the remote server, retrieving the results, and displaying them to the user. If your application uses a remote search engine, you can consider inserting the search results in the Unified Search Service content repository to improve speed and efficiency for subsequent searches. Some predefined external search providers include YouTube and Google. Third-party applications can also access external search providers. The UnifiedSearchServices.getSearchProviders() method returns a list of registered ExternalSearchProvider objects where an application can send a search. Similar to EntityBasedSearchable objects, an ExternalSearchProvider must be registered with the Unified Search Service by using the SearchRegistry object. For more information, see "Register your EntityBasedSearchable object with the Unified Search Service". Code sample: Implementing the ExternalSearchProvider interface

import net.rim.device.api.ui.image.Image; import net.rim.device.api.ui.image.ImageFactory; import net.rim.device.api.unifiedsearch.searchables.ExternalSearchProvider; import net.rim.device.api.unifiedsearch.searchables.SearchableContentTypeConstants; public class MySearchProvider implements ExternalSearchProvider { // A unique registration ID for this provider. private long _regId; // The external search provider icon. private Image _icon; // Constructor public MySearchProvider() { // Read the icon from the resource bundle

18

Development Guide

Using other search engines

Bitmap img = Bitmap.getBitmapResource("myicon.png"); if(img != null) { _icon = ImageFactory.createImage(img); } else { _icon = null; }

// The provider name to be displayed. public String getProviderName() { return "Sample External Search Provider"; } // The provider icon to be displayed. public Image getProviderIcon() { return _icon; } // The content type this provider offers. public long getContentType() { return SearchableContentTypeConstants.CONTENT_TYPE_MEDIA_MEMO; } // The search initiator will pass control to your application using this method. public void search(String keywords) { // Create network or IPC connections, send search keywords, and display the results. } // Allows the Unified Search Service and your application to keep track of // this searchable's registration public long getRegistrationID() { return _regId; } public setRegistrationID(long id) { _regId = id; }

19

Development Guide

Ensure that a device runs a single instance of your application

Ensure that a device runs a single instance of your application


To improve the efficiency of your application, you should make sure that the BlackBerry device runs only one instance when search() is invoked in your ExternalSearchProvider implementation. 1. In your implementation of ExternalSearchProvider, import packages to help you discover which applications are running on the device.
import import import import net.rim.device.api.system.ApplicationDescriptor; net.rim.device.api.system.ApplicationManager; net.rim.device.api.system.ApplicationManagerException; net.rim.device.api.system.CodeModuleManager;

2.

In search(), retrieve a handle for your application.


public void search(String keywords) { int modHandle = CodeModuleManager.getModuleHandle("MyApplication");

3.

Retrieve an array of objects that represent the applications that are running on the device.
ApplicationDescriptor[] allApps = ApplicationManager.getApplicationManager ().getVisibleApplications();

4.

Examine each element of the array to determine whether your application is running on the device.
for(int i = allApps.length -1; i >= 0; --i) { if(allApps[i].getModuleHandle() == modHandle) {

5.

If your application is running, send the search keywords to it. Invoke postGlobalEvent() to send your application a message that it should display a screen with the results for the new keywords. You need to detect a global event that is posted to your GUID in your application's constructor, .
int procID = ApplicationManager.getApplicationManager().getProcessId (allApps[i]); ApplicationManager.getApplicationManager().postGlobalEvent(procID, your application's GUID, 0, 0, keywords, null); } }

6.

If your application is not running on the device, retrieve an ApplicationDescriptor object that represents your application.
ApplicationDescriptor[] myAppDes = (modHandle); CodeModuleManager.getApplicationDescriptors

7.

Start your application. Pass the search keywords as an argument. In your application's constructor, you need to detect whether there is an argument that contains search keywords.
try { ApplicationManager.getApplicationManager().runApplication(new ApplicationDescriptor(myAppDes[0], new String[]{keywords})); } catch(ApplicationManagerException e)

20

Development Guide

Ensure that a device runs a single instance of your application

{ } }

// Process the error condition

8.

In your application class, import the net.rim.device.api.system.GlobalEventListener package to listen for global events.
import net.rim.device.api.system.GlobalEventListener;

9.

Import the UiApplication class.


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

10. Register your application to listen for global events, such as the one that you created in step 5, and display your first screen.
public class MySearchProviderApp extends UiApplication implements GlobalEventListener { public MySearchProviderApp(String searchKeywords) { addGlobalEventListener(this); pushScreen(new MySearchScreen(searchKeywords)); }

11. Implement eventOccured() to respond to global events.


public void eventOccurred(long guid, int data0, int data1, Object object0, Object object1) {

12. If your application is running on the device, close the existing screen and display another screen.
if(guid == G53DDE84S97JHVEK390) { if(object0 instanceof String) { popScreen(); pushScreeen(new MySearchScreen((String) object0)); requestForeground(); } }

13. Test for search keywords in the arguments for the main method. Start your application with the keywords that are given, or with an empty string if no keywords are given.
public static void main(String[] args) { String searchKeywords = ""; if(args != null && args.length > 0) { searchKeywords = args[0]; } MySearchProviderApp app = new MySearchProviderApp(searchKeywords); app.enterEventDispatcher(); }

21

Development Guide

Inserting data when a device starts

Inserting data when a device starts


Each time a BlackBerry device restarts (for example, when the battery is removed), the Unified Search Service starts with an empty registry and content repository. If you want your application data to appear in search results before your application runs, you should create an alternate entry point that registers your searchable entities when the device starts.

Searching
You can use the UnifiedSearchServices class to configure and start a search operation from your application. In the simplest case, you can search all data sources when you submit a keyword to the Unified Search Service. However, you can limit your search to particular searchable data sources, and search fields within those sources. When your search is complete, the Unified Search Service returns a SearchResponse object that contains searchable entities that matched your search criteria. The Service returns the data organized by searchable data source and search field. The structure of the result allows you to look at the metadata that is related to the result. In this way, you can make more detailed decisions about the relevance of search results to your users.

Configure and start a search


This task demonstrates how to start a search that is limited to the searchable entities that your application creates. The UnifiedSearchServices.search() method blocks thread execution, so doSearch() below invokes it in a separate thread. 1. Import the required classes and interfaces.
import net.rim.device.api.unifiedsearch.*; import net.rim.device.api.unifiedsearch.searchables.*; import java.util.*;

2.

Create an instance variable to store a reference to the UnifiedSearchServices object.


public class MySearchScreen() { UnifiedSearchServices _uss = UnifiedSearchServices.getInstance();

3.

Retrieve a reference to your EntityBasedSearchable object and assign it to an instance variable. When you retrieve a list of searchable applications on the device, change the SearchableContentTypeConstants value to one that is appropriate for your search. Make sure you take some kind of action if your EntityBasedSearchable is not found in the deviceSearchables vector.
MySearchable _searchable = null; Vector deviceSearchables = _uss.getDeviceSearchables (SearchableContentTypeConstants.CONTENT_TYPE_MEMO); for(int i = deviceSearchables.size() -1; i >=0; --i) { if(deviceSearchables.elementAt(i).getName().equals("name of your searchable")) { _searchable = (MySearchable) deviceSearchables.elementAt(i);

22

Development Guide

Searching

} } // Do something if _searchable is still null

4.

Create a method to start the search. Accept the search keyword as a parameter, where your application specifies the search keywords that the BlackBerry device user provides. This method invokes a new thread, so declare the String parameter as final.
private void doSearch(final String keyword) {

5.

Create the Thread object that will run your search.


Thread searchThread = new Thread(new Runnable() { public void run() { try {

6.

Start the search and retrieve the results, if any. If there is a result, send it to another method to be parsed.
SearchResponse results = null; results = _uss.search(keyword, _searchable); if(results != null) { parseResponse(results); }

7.

Catch any errors that are thrown.


} catch (Exception e) { // Do something about the error }

8.

Complete the Thread definition and run it.


}, "Search Thread"); searchThread.start();

After you finish: Implement parseResponse. For more information see "Process search results."

Process search results


The SearchResponse object that you receive from the Unified Search Service structures your search results by the EntityBasedSearchable and search fields that matched your keywords. To access the data, you need to parse this object. Before you begin: Ensure that UnifiedSearchServices.search() returned a SearchResponse object with data. Pass the SearchResponse to parseResponse(). 1. Import the required classes and interfaces.
import import import import net.rim.device.api.unifiedsearch.entity.*; net.rim.device.api.util.Arrays; net.rim.device.api.system.Application; java.util.*;

2.

Create an instance variable to store searchable entities to display to the BlackBerry device user.

23

Development Guide

Searching

MySearchableEntity[] _myEntities;

3.

Implement parseResponse. This method runs after your search thread terminates, so declare the SearchResponse parameter as final.
private void parseResponse(final SearchResponse searchResult) {

4.

Configure this method to run when your application regains control of the event thread.
Application.getApplication().invokeLater(new Runnable() { public void run() {

5.

From the search results, retrieve a Hashtable object that contains search fields and searchable entities for your EntityBasedSearchable.
final Hashtable results = searchResult.getSearchResult(_searchable);

6.

Retrieve an Enumeration object that contains the values in the Hashtable, and declare an array to store unique values from the enumeration.
Enumeration values = results.elements(); Object[] searchableEntities;

7. 8.

Initialize your array of searchable entities to display.


_myEntities = new MySearchableEntity[0];

Iterate through the values enumeration and add unique values to searchableEntities.
while(values.hasMoreElements()) { searchableEntities = (Object[]) values.nextElement(); for(int i = searchableEntities - 1; i >= 0; --i) { if(!Arrays.contains(_myEntities, searchableEntities[i]) { Arrays.add(_myEntities, searchableEntities[i]); } } }

});

The _myEntities array contains a set of unique MySearchableEntity objects that you can use to display the search results to the user.

24

Development Guide

Device interaction support

Device interaction support


Device Capability API

You can query the capabilities of a BlackBerry device by using the Device Capability API that is provided in the net.rim.device.api.system.capability package. You can use the DeviceCapability class to query whether specific features, such as a virtual keyboard or a physical keyboard, are supported on the device, whether the feature is currently available to the BlackBerry device user (for example, if the slider on a device is open and the user can use the physical keyboard), and whether your application can currently access the feature. For example, DeviceCapability.isVirtualKeyboardAvailable() returns true if the device has a virtual keyboard currently displayed. Otherwise the method returns false. You can define a listener to notify your application of changes to the specified capabilities of the device by implementing the DeviceCapabilityListener interface. For an example of how to use the Device Capability API, see Cradle detection. For more information about the Device Capability API, see the API reference for the BlackBerry Java SDK.

Cradle detection
You can detect when a BlackBerry device is connected to a cradle (such as a car kit cradle) by using the DeviceCapability.TYPE_CRADLE capability type that is part of the Device Capability API. You can use DeviceCapability.isSupported() and DeviceCapability.isAvailable() to detect the cradle status. Devices that are running BlackBerry Device Software 6.0 return true for isSupported (DeviceCapability.TYPE_CRADLE). When a device that is running BlackBerry Device Software 6.0 is connected to a cradle, isAvailable(DeviceCapability.TYPE_CRADLE) returns true. When you detect a cradle connection, you can use the CradleProtocol class to detect the cradle type and properties. CradleProtocol is provided in the net.rim.device.api.accessory package. The class provides fields for a cradle's type (such as a car kit cradle, a holster, or a charging pod) and a cradle's properties (such as whether a cradle has a light or buttons that can be changed programmatically).
CradleProtocol.getCradleType() returns the cradle type that the cradle itself provides. A cradle might not provide its precise type. For example, a car kit cradle might return CradleProtocol.TYPE_SIMPLE, instead of CradleProtocol.TYPE_CAR_KIT.

Code sample: Detecting if a device is connected to a cradle The following code sample tests whether the device is connected to a cradle. If it is, the type of cradle is displayed.
import import import import net.rim.device.api.accessory.CradleProtocol; net.rim.device.api.system.capability.DeviceCapability; net.rim.device.api.ui.component.RichTextField; net.rim.device.api.ui.container.MainScreen;

25

Development Guide

Cradle detection

class CradleDemoScreen extends MainScreen { public CradleDemoScreen() { setTitle("Cradle Demo"); RichTextField statusField = new RichTextField(); add(statusField); boolean isConnected = DeviceCapability.isAvailable(DeviceCapability.TYPE_CRADLE); if (isConnected) { CradleProtocol myCradle = CradleProtocol.getInstance(); int cradleType = myCradle.getCradleType(); switch (cradleType) { case CradleProtocol.TYPE_CAR_KIT: statusField.setText("Device is connected to a car kit cradle."); break; case CradleProtocol.TYPE_AUDIO: statusField.setText("Device is connected to an audio cradle."); break; case CradleProtocol.TYPE_BEDSIDE: statusField.setText("Device is connected to a charging pod cradle."); break; case CradleProtocol.TYPE_CHARGER: statusField.setText("Device is connected to a charger cradle."); break; case CradleProtocol.TYPE_DESKTOP: statusField.setText("Device is connected to a desktop cradle."); break; case CradleProtocol.TYPE_HOLSTER: statusField.setText("Device is connected to a holster cradle."); break; case CradleProtocol.TYPE_MULTIMEDIA: statusField.setText("Device is connected to a multimedia cradle."); break; case CradleProtocol.TYPE_SIMPLE: statusField.setText("Device is connected to a simple cradle."); break; default: statusField.setText("Can't determine type of cradle."); } } else { statusField.setText("Device is not connected."); }

26

Development Guide

Cradle handling

Cradle handling
You can register your application as a cradle handler. A cradle handler is an application that can start when a BlackBerry device is connected to a cradle of a specified type. For example, if your application provides local travel information, you might want to register it as a handler for a car kit cradle, so that it can start automatically when the device is connected to a car kit cradle. To register your application as a cradle handler, use CradleHandlerRegistry.registerHandler(). The CradleHandlerRegistry class is provided in the net.rim.blackberry.api.cradle package. When you

register your application, you specify the type of cradle that you want to handle and your application descriptor. Cradle types are defined as fields in the CradleProtocol class that is provided in the net.rim.device.api.accessory package. Registration as a cradle handler is persistent. You need to register your application only once after it is installed on the device. If any handlers are registered for a cradle type, the user is presented with a dialog box when that type of cradle is connected.

The user can select which handler to use, if any, and the selected handler application is started. The user can also indicate that the selected handler application should start automatically the next time the cradle of the specified type is connected.

27

Development Guide

Working with sensors on a device

The user can change the cradle handler settings on the device by clicking Options > Third Party Applications on the Home screen. Code sample: Registering a cradle handler The following code sample registers the current application as a handler for car kit cradles.
CradleHandlerRegistry.registerHandler( CradleProtocol.TYPE_CAR_KIT, ApplicationDescriptor.currentApplicationDescriptor());

Working with sensors on a device


You can use the Sensor class that is included in the net.rim.device.api.system package, to determine the existence and the states of sensors on a BlackBerry device. Sensors that you can work with include the holster sensors, slider sensors, and flip sensors. You can use the SensorListener class that is also included in net.rim.device.api.system, to let a BlackBerry device application receive notifications when the state of a sensor changes.

Check for a sensor on the device


Sensors on the BlackBerry device that you can work with include the holster sensors, slider sensors, and flip sensors. 1. 2. Import the required classes and interfaces.
import net.rim.device.api.system.Sensor;

Invoke Sensor.isSupported() and specify the type of sensor that you want to check for. The sensor types are defined as constants in the Sensor class. The following code sample checks to see whether a device has a slider.
boolean hasSliderSensor; hasSliderSensor = Sensor.isSupported(Sensor.SLIDE);

The method returns true if the device contains the specified sensor, and returns false otherwise. Code sample: Checking for a sensor on the device The following code sample checks whether the device has a holster sensor, slider sensor, or flip sensor.
class SensorDemoScreen extends MainScreen { private RichTextField statusField; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField = new RichTextField();

28

Development Guide

Working with sensors on a device

add(statusField); boolean hasHolsterSensor, hasSliderSensor, hasFlipSensor; hasHolsterSensor = Sensor.isSupported(Sensor.HOLSTER); hasSliderSensor = Sensor.isSupported(Sensor.SLIDE); hasFlipSensor = Sensor.isSupported(Sensor.FLIP); statusField.setText("Holster: " + hasHolsterSensor + "\nSlider: " + hasSliderSensor + "\nFlip: " + hasFlipSensor);

Check the state of a sensor


1. 2. Import the required classes and interfaces.
import net.rim.device.api.system.Sensor;

Invoke Sensor.getState() and specify the type of sensor that you want to check. The sensor types are defined as constants in the Sensor class. The following code sample checks the state of the slider on a BlackBerry device.
int sliderState = Sensor.getState(Sensor.SLIDE);

The method returns the sensor's state as an int constant. The constants that can be returned are defined in the Sensor class. You can use the following methods to determine whether the sensor is in a given state: Sensor.isSlideClosed(), Sensor.isSlideOpen(), Sensor.isSlideInTransition(). Code sample: Displaying the state of the device's slider
class SensorDemoScreen extends MainScreen implements SensorListener { private RichTextField statusField; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField = new RichTextField(); add(statusField); if (Sensor.isSupported(Sensor.SLIDE)) { int sliderState = Sensor.getState(Sensor.SLIDE); switch (sliderState) { case Sensor.STATE_SLIDE_CLOSED: // do something if slider is closed statusField.setText("Slider is closed."); break; case Sensor.STATE_SLIDE_IN_TRANSITION: // do something if slider in transition statusField.setText("Slider is between open and closed."); 29

Development Guide

Working with sensors on a device

break; case Sensor.STATE_SLIDE_OPEN: // do something if slider is open statusField.setText("Slider is open."); break; default: statusField.setText("Can't determine state of slider.");

Notify an application when the state of a sensor changes


1. Import the required classes and interfaces.
import net.rim.device.api.system.Sensor; import net.rim.device.api.system.SensorListener;

2.

Create a class that implements the SensorListener interface.


class SensorDemoScreen extends MainScreen implements SensorListener { }

3.

In the class, implement SensorListener.onSensorUpdate() and perform actions based on the type of sensor (the method's first parameter) and the new state of the sensor (the second parameter). The following code sample checks the state of the slider on a BlackBerry device.
public void onSensorUpdate(int sensorID, int update) { if (sensorID == Sensor.SLIDE) { if (update == Sensor.STATE_SLIDE_OPEN) { // do something if slider is now open statusField.setText("Slider is now open."); } else if (update == Sensor.STATE_SLIDE_IN_TRANSITION) { // do something if slider is now in transition statusField.setText("Slider state is now in transition."); } else if (update == Sensor.STATE_SLIDE_CLOSED) { // do something if slider is now closed statusField.setText("Slider is now closed."); } } }

4.

Invoke SensorListener.addListener() to add the listener to your application. Specify the application, the listener to add, and the types of sensor changes to listen for. The following code sample adds a listener for slider changes to the current application. You can invoke Sensor.removeListener() to remove a listener.

30

Development Guide

Working with sensors on a device

Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE);

5.

To listen for changes to multiple sensors, update the third argument of addListener() to add additional sensor state flags. The following code sample listens for changes to the flip sensor or slider sensor.
Sensor.addListener(Application.getApplication(), this, Sensor.FLIP | Sensor.SLIDE);

Code sample: Listening for changes to the state of the device's slider
class SensorDemoScreen extends MainScreen implements SensorListener { private RichTextField statusField; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField = new RichTextField(); add(statusField); Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE); } public void onSensorUpdate(int sensorID, int update) { if (sensorID == Sensor.SLIDE) { if (update == Sensor.STATE_SLIDE_OPEN) { // do something if slider is now open statusField.setText("Slider is now open."); } else if (update == Sensor.STATE_SLIDE_IN_TRANSITION) { // do something if slider is now in transition statusField2.setText("Slider state is now in transition."); } else if (update == Sensor.STATE_SLIDE_CLOSED) { // do something if slider is now closed statusField.setText("Slider is now closed."); } } }

Code sample: Working with a sensor


import import import import net.rim.device.api.system.*; net.rim.device.api.ui.UiApplication; net.rim.device.api.ui.component.RichTextField; net.rim.device.api.ui.container.MainScreen;

public class SensorDemo extends UiApplication

31

Development Guide

Working with sensors on a device

public SensorDemo() { SensorDemoScreen screen = new SensorDemoScreen(); pushScreen(screen); } public static void main(String[] args) { SensorDemo app = new SensorDemo(); app.enterEventDispatcher(); } class SensorDemoScreen extends MainScreen implements SensorListener { private RichTextField statusField1; private RichTextField statusField2; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField1 = new RichTextField(); statusField2 = new RichTextField(); add(statusField1); add(statusField2); // Check for the presence of a sensor boolean hasFlipSensor, hasHolsterSensor, hasSliderSensor; hasFlipSensor = Sensor.isSupported(Sensor.FLIP); hasHolsterSensor = Sensor.isSupported(Sensor.HOLSTER); hasSliderSensor = Sensor.isSupported(Sensor.SLIDE); statusField1.setText("Flip: " + hasFlipSensor + "\nHolster: " + hasHolsterSensor + "\nSlider: " + hasSliderSensor + "\n"); // Check for the state of a sensor if (Sensor.isSupported(Sensor.SLIDE)) { int sliderState = Sensor.getState(Sensor.SLIDE); switch (sliderState) { case Sensor.STATE_SLIDE_CLOSED: // do something if slider is closed statusField2.setText("Slider is closed."); break; case Sensor.STATE_SLIDE_IN_TRANSITION: // do something if slider in transition statusField2.setText("Slider is between open and closed."); break; case Sensor.STATE_SLIDE_OPEN: // do something if slider is open statusField2.setText("Slider is open."); break; default: statusField2.setText("Can't determine state of slider."); } } // Listen for changes to a sensor Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE);

32

Development Guide

Working with sensors on a device

} // implementation of SensorListener.onSensorUpdate() // only checks for slider changes public void onSensorUpdate(int sensorID, int update) { if (sensorID == Sensor.SLIDE) { if (update == Sensor.STATE_SLIDE_OPEN) { // do something if slider is now open statusField2.setText("Slider is now open."); } else if (update == Sensor.STATE_SLIDE_IN_TRANSITION) { // do something if slider is now transitioning statusField2.setText("Slider state is changing."); } else if (update == Sensor.STATE_SLIDE_CLOSED) { // do something if slider is now closed statusField2.setText("Slider is now closed."); } } }

33

Development Guide

Message list

Message list
This section describes how to use the messaging capabilities of the BlackBerry device. For more information, see the Messaging category overview in the API reference for the BlackBerry Java Development Environment.

Create a new blank SMS text message


1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.MessageArguments;

2.

Invoke Invoke.invokeApplication(). Use the following parameters: the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_SMS field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_SMS));

Create a new populated text message


Use the API items in the javax.wireless.messaging package (JSR 120). 1. Import the required classes and interfaces.
import import import import import javax.microedition.io.Connector; javax.wireless.messaging.MessageConnection; javax.wireless.messaging.TextMessage; net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.MessageArguments;

2.

Create and populate a new TextMessage object.


MessageConnection mc = (MessageConnection)Connector.open("sms://"); TextMessage m = (TextMessage)mc.newMessage( MessageConnection.TEXT_MESSAGE ); m.setAddress("sms://5558888"); m.setPayloadText("An SMS message for you");

3.

Invoke Invoke.invokeApplication() with the following parameters: APP_TYPE_MESSAGES: a constant parameter MessageArguments: a new MessageArguments object that uses the new TextMessage object.
Invoke.invokeApplication( Invoke.APP_TYPE_MESSAGES, new MessageArguments(m) );

Create a new blank MMS message


1. Import the required classes and interfaces.

34

Development Guide

Create a new blank email message

import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.MessageArguments;

2.

Invoke Invoke.invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_MMS field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_MMS));

Create a new blank email message


1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.MessageArguments;

2.

Invoke Invoke.invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW));

Create a new populated email message


1. Import the required classes and interfaces.
import import import import net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.MessageArguments; net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.Message;

2.

Create and populate a new email Message object.


Message m = new Message(); Address a = new Address("mLi@rim.com", "Ming Li"); Address[] addresses = {a}; m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses); m.setContent("A message for you..."); m.setSubject("Email for you");

3.

Invoke Invoke.invokeApplication()with the following parameters: APP_TYPE_MESSAGES a MessageArguments object that uses the new Message object.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));

Create a new blank PIN message


1. Import the required classes and interfaces.

35

Development Guide

Create a new populated PIN message

import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.MessageArguments;

2.

Invoke Invoke.invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_PIN field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_PIN));

Create a new populated PIN message


1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.MessageArguments; net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.PINAddress;

2.

Create and populate a new PIN message.


Message m = new Message(); PINAddress pa = new PINAddress("ABCDEF99", "Mark Chapters"); Address[] addresses = {pa}; m.addRecipients( net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses ); m.setContent("A message for you..."); m.setSubject("PIN message for you");

3.

Invoke Invoke.invokeApplication() with the following parameters: APP_TYPE_MESSAGES a MessageArguments object that uses the new PIN message.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));

Receive a message notification


1. Import the required classes and interfaces.
import net.rim.blackberry.api.mail.event.FolderListener; import net.rim.blackberry.api.mail.event.StoreListener; import net.rim.device.api.system.ControlledAccessException;

2. 3.

Implement the FolderListener and StoreListener interfaces.


public class MailTest implements FolderListener, StoreListener { ... }

Check for a ControlledAccessException if your application accesses an object that you do not have permission to access.

36

Development Guide

Add a listener to the message store

Add a listener to the message store


1. Import the required classes and interfaces.
import net.rim.blackberry.api.mail.NoSuchServiceException; import net.rim.blackberry.api.mail.Session; import net.rim.blackberry.api.mail.Store;

2.

Create a try-catch block to manage a NoSuchServiceException.


try { } catch (NoSuchServiceException e) { System.out.println(e.toString()); }

3.

Within the try-catch block, invoke Session.waitForDefaultSession().getStore() to retrieve the Store object.
try {

Store store = Session.waitForDefaultSession().getStore(); } catch (NoSuchServiceException e) { System.out.println(e.toString()); }

4.

Store object.

After the try-catch block, invoke store.addStoreListener() to add a StoreListener instance to the
store.addStoreListener(this);

Add a listener to the message store for batch updates


1. Import the required classes and interfaces.
import net.rim.blackberry.api.mail.event.StoreListener; import net.rim.blackberry.api.mail.Store;

2.

Implement the StoreListener interface.


void batchOperation(StoreEvent e) { // Perform action when messages added or removed in batch operation. }

37

Development Guide

Add a listener to a folder

Add a listener to a folder


1. Import the required classes and interfaces.
import net.rim.blackberry.api.mail.event.FolderListener; import net.rim.blackberry.api.mail.Folder; import net.rim.blackberry.api.mail.Store;

2.

Implement FolderListener.messagesAdded() and FolderListener.messagesRemoved().


void messagesAdded(FolderEvent e) { // Perform processing on added messages. } void messagesRemoved(FolderEvent e) { // Perform processing on removed messages. }

3.

Retrieve the Folder object for which you want to receive new message notifications.
Folder[] folders = store.list(Folder.INBOX); Folder inbox = folders[0];

4.

Register the class that implements FolderListener with the folder.


inbox.addFolderListener(this);

Retrieve the total count of unread email messages in all folders in the store
1. 2. Import the required class.
import net.rim.blackberry.api.mail.Store;

Invoke Store.getUnreadMessageCount().
int numUnread = store.getUnreadMessageCount();

Open a message
1. Import the required classes and interfaces.
import import import import import import java.util.Date; net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store;

2.
38

Invoke Session.waitForDefaultSession.getStore() to retrieve the message store.

Development Guide

Retrieving the body of an email message

Store store = Session.waitForDefaultSession.getStore();

3. 4.

Invoke Store.getFolder() to retrieve the folder that contains the message.


Folder folder = Store.getFolder("SampleFolder");

Invoke folder.getMessages() to retrieve the message objects and store the message objects in a Message array. Iterate through the array and retrieve information, such as the sender and subject, to display to the BlackBerry device user.
Message[] msgs = folder.getMessages();

5.

When a user selects a message from the list, invoke methods on the Message object to retrieve the appropriate fields and body contents to display to the user.
Message msg = msgs[0]; // Retrieve the first message Address[] recipients = msg.getRecipients(Message.RecipientType.TO); Date sent = msg.getSentDate(); Address from = msg.getFrom(); String subject = msg.getSubject(); Object o = msg.getContent(); // Verify that the message is not multipart if ( o instanceof String ) { String body = (String)o; } //...

6.

Invoke Message.getBodyText() on a message to retrieve the plain text contents as a String. If the message does not contain plain text, the method returns null.

Retrieving the body of an email message


An email message can contain plain text, HTML, or both. The content and the order of the content in the email message can vary. A BlackBerry device application can use the MimeBodyPart class to retrieve the HTML content, or use the TextBodyPart class to retrieve the plain text content. You can use a MultiPart object to retrieve objects from both the MimeBodyPart class and the TextBodyPart class. For example, you might retrieve the content of an email message to translate the content into a different language. Support for text and HTML was introduced in BlackBerry Device Software 4.5 for BlackBerry devices associated with BlackBerry Enterprise Server 4.1 Service Pack 6 (4.1.6) or the BlackBerry Internet Service 2.5.

39

Development Guide

Retrieving the body of an email message

Retrieve the plain text and HTML content in the body of an email message using a recursive method
Create a recursive method to retrieve all the parts of the body of an email message including plain text and HTML. 1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.mail.MimeBodyPart; net.rim.blackberry.api.mail.Multipart; net.rim.blackberry.api.mail.SupportedAttachmentPart; net.rim.blackberry.api.mail.TextBodyPart; net.rim.blackberry.api.mail.UnsupportedAttachmentPart;

2. 3.

Create the method signature for the recursive method.


void findEmailBody(Object obj) {...}

Create local variables that indicate if the BlackBerry Attachment Service supports the message attachment type.
boolean _hasSupportedAttachment; boolean _hasUnsupportedAttachment;

4.

Initialize the local variables.


_hasSupportedAttachment = false; _hasUnsupportedAttachment = false;

5.

If the method parameter is a Multipart object, the object has multiple BodyPart objects. On each BodyPart object, invoke the recursive method that searches through the body of an email message.
if(obj instanceof Multipart) { _Multipart mp = (Multipart)obj; //Extract all of the parts within the Multipart message. for(int count=0; count < mp.getCount(); ++count) { findEmailBody(mp.getBodyPart(count)); }

6.

If the BodyPart object is a TextBodyPart, retrieve the plain text body of the message.
else if (obj instanceof TextBodyPart) { //This message only has a text body. TextBodyPart tbp = (TextBodyPart) obj; readEmailBody(tbp); }

7. 8.

Check if the BodyPart object is a MimeBodyPart.


else if (obj instanceof MimeBodyPart) {...}

If the BodyPart object is a MimeBodyPart, perform the following actions:

40

Development Guide

Retrieving the body of an email message

a. b.

Cast the BodyPart object as a MimeBodyPart.


MimeBodyPart mbp = (MimeBodyPart) obj;

If the MimeBodyPart object does not contain attachments, retrieve the body of the message using the MimeBodyPart object as a parameter.
if (mbp.getContentType().indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) { readEmailBody(mbp); }

c.

If the MimeBodyPart object does contain attachments, invoke a method that retrieves the body of the message.
else if (mbp.getContentType().equals(ContentType.TYPE_MULTIPART_MIXED_STRING) || mbp.getContentType().equals (ContentType.TYPE_MULTIPART_ALTERNATIVE_STRING)) { findEmailBody(mbp.getContent()); }

9.

If the BodyPart is an attachment that the BlackBerry Attachment Service supports, change the appropriate local variable to true.
else if (obj instanceof SupportedAttachmentPart) { _hasSupportedAttachment = true; }

10. If the BodyPart is an attachment that the BlackBerry Attachment Service does not support, change the appropriate local variable to true.
else if (obj instanceof UnsupportedAttachmentPart) { _hasUnsupportedAttachment = true; }

Code sample: Retrieving the content of an email message


private void findEmailBody(Object obj) { //Reset the attachment flags. _hasSupportedAttachment = false; _hasUnsupportedAttachment = false; if(obj instanceof Multipart) { Multipart mp = (Multipart)obj; for(int count=0; count < mp.getCount(); ++count) { findEmailBody(mp.getBodyPart(count)); } 41

Development Guide

Retrieving the body of an email message

} else if (obj instanceof TextBodyPart) { TextBodyPart tbp = (TextBodyPart) obj; readEmailBody(tbp); } else if (obj instanceof MimeBodyPart) { MimeBodyPart mbp = (MimeBodyPart)obj; if (mbp.getContentType().indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) { readEmailBody(mbp); } } else if (mbp.getContentType().equals(ContentType.TYPE_MULTIPART_MIXED_STRING) || mbp.getContentType().equals(ContentType.TYPE_MULTIPART_ALTERNATIVE_STRING)) { //The message has attachments or we are at the top level of the message. //Extract all of the parts within the MimeBodyPart message. findEmailBody(mbp.getContent()); } else if (obj instanceof SupportedAttachmentPart) { _hasSupportedAttachment = true; } else if (obj instanceof UnsupportedAttachmentPart) { _hasUnsupportedAttachment = true; }

Retrieve the plain text content of an email message


In the following task, an exception may be thrown when you invoke the Transport.more() method. 1. Import the required classes and interfaces.
import import import import net.rim.blackberry.api.mail.BodyPart; net.rim.blackberry.api.mail.TextBodyPart; net.rim.blackberry.api.mail.Transport; net.rim.device.api.ui.component.Dialog;

2. 3.

Create a method that takes a TextBodyPart object as a parameter.


void readEmailBody(TextBodyPart tbp);

Cast the value that TextBodyPart.getContent() returns as a String to get the plain text part of the body of the message.
_plainTextMessage = (String)tbp.getContent();

42

Development Guide

Retrieving the body of an email message

4.

Invoke TextBodyPart.hasMore() and TextBodyPart.moreRequestSent() to identify if more of the TextBodyPart object is available on the server.
if (tbp.hasMore() && !tbp.moreRequestSent()) {

5.

If more data is available for the TextBodyPart object, invoke Transport.more() to retrieve the rest of the TextBodyPart object.
Transport.more((BodyPart)tbp, true);

Code sample: Retrieving the plain text content of an email message


private void readEmailBody(TextBodyPart tbp) { _plainTextMessage = (String)tbp.getContent(); if (tbp.hasMore() && !tbp.moreRequestSent()) { try { Transport.more((BodyPart)tbp, true); } catch (Exception ex) { Dialog.alert("Exception: " + ex.toString()); } }

Retrieve the HTML content of an email message


In the following task, an exception may be thrown when you invoke the Transport.more() method. 1. Import the required classes and interfaces.
import import import import net.rim.blackberry.api.mail.BodyPart; net.rim.blackberry.api.mail.MimeBodyPart; net.rim.blackberry.api.mail.Transport; net.rim.device.api.ui.component.Dialog;

2.

Create a method that takes a MimeBodyPart object as a parameter.


void readEmailBody(MimeBodyPart mbp) {

3.

Invoke MimeBodyPart.getContent() and MimeBodyPart.getContentType() to retrieve the content of the MimeBodyPart object.
Object obj = mbp.getContent(); String mimeType = mbp.getContentType();

4.

Create a String variable to hold the String representation of the MimeBodyPart object.

43

Development Guide

Retrieving the body of an email message

String body = null;

5.

If the BlackBerry device can convert the HTML body of a message to a String, the MimeBodyPart object will be a String. Cast the MimeBodyPart object as a String and assign it to the String representation of the body part of the message.
if (obj instanceof String) { body = (String)obj; }

6.

If the BlackBerry device cannot convert the HTML body of a message to a String, the MimeBodyPart object will be a byte array. Create a new instance of String using as a parameter the MimeBodyPart object cast as a byte array. Assign the String to the String representation of the body part of the message.
else if (obj instanceof byte[]) { body = new String((byte[])obj); }

7.

Check to see if the String representation of the content of the MimeBodyPart object contains ContentType.TYPE_TEXT_PLAIN_STRING to determine if the MimeBodyPart object is the plain text body part of the message.
if (mimeType.indexOf(ContentType.TYPE_TEXT_PLAIN_STRING) != -1) {

8.

Invoke MimeBodyPart.hasMore() and MimeBodyPart.moreRequestSent() to determine if all of the text body part is present in the MimeBodyPart object.
if (mbp.hasMore() && !mbp.moreRequestSent()) {

9.

If more data is available for the MimeBodyPart object, invoke Transport.more() to retrieve the rest of the data for the MimeBodyPart object.
Transport.more((BodyPart)mbp, true);

10. Check to see if the String representation of the content of the MimeBodyPart object contains ContentType.TYPE_TEXT_HTML_STRING to detemine if the MimeBodyPart object is the HTML body part of the message.
else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) {

11. Invoke MimeBodyPart.hasMore() and MimeBodyPart.moreRequestSent() to determine if all of the HTML body part is present in the MimeBodyPart object.
if (mbp.hasMore() && !mbp.moreRequestSent()) {

12. If more data is available for the MimeBodyPart object, invoke Transport.more() to retrieve the rest of the MimeBodyPart object.

44

Development Guide

Retrieving the body of an email message

Transport.more((BodyPart)mbp, true);

Code sample: Retrieving the HTML content of an email message


private void readEmailBody(MimeBodyPart mbp) { //Extract the content of the message. Object obj = mbp.getContent(); String mimeType = mbp.getContentType(); String body = null; if (obj { body } else if { body } instanceof String) = (String)body; (obj instanceof byte[]) = new String((byte[])obj);

if (mimeType.indexOf(ContentType.TYPE_TEXT_PLAIN_STRING) != -1) { _plainTextMessage = body; //Determine if all of the text body part is present. if (mbp.hasMore() && !mbp.moreRequestSent()) { try { Transport.more((BodyPart)mbp, true); } catch (Exception ex) { Dialog.alert("Exception: " + ex.toString()); } }

else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) { _htmlMessage = body; //Determine if all of the HTML body part is present. if (mbp.hasMore() && !mbp.moreRequestSent()) { try { Transport.more((BodyPart)mbp, true); } catch (Exception ex) { Dialog.alert("Exception: " + ex.toString()); }

45

Development Guide

Notify a BlackBerry device application that an email message is about to be sent

Notify a BlackBerry device application that an email message is about to be sent


1. Import the required classes and interfaces.
import import import import net.rim.blackberry.api.mail.NoSuchServiceException; net.rim.blackberry.api.mail.SendListener; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store;

2. 3. 4.

Implement the SendListener interface.


public class MailSendListener implements SendListener{...}

Create an instance of the class that implements the SendListener interface.


MailSendListener mailSL = new mailSendListener();

In a try block, invoke Session.waitForDefaultSession().getStore() to retrieve the Store object.


try { }

Store store = Session.waitForDefaultSession().getStore();

5.

In a catch block, manage a NoSuchServiceException.


catch (NoSuchServiceException e) { System.out.println(e.toString()); }

6.

Invoke Store.addSendListener(MailSendListener) to add a SendListener instance.


store.addSendListener(mailSL);

Notify a BlackBerry device application that an MMS message is about to be sent


1. Import the required classes and interfaces.
import net.rim.blackberry.api.mms.SendListener; import net.rim.blackberry.api.mms.MMS;

2.

Implement the SendListener interface.


public class MMSSendListener implements SendListener{...}

46

Development Guide

Notify a BlackBerry device application that an SMS message is about to be sent

3. 4.

Create an instance of the class that implements the SendListener interface.


MMSSendListener mmsSL = new mmsSendListener();

Add a SendListener instance.


MMS.addSendListener(mmsSL);

Notify a BlackBerry device application that an SMS message is about to be sent


1. Import the required classes and interfaces.
import net.rim.blackberry.api.sms.SendListener; import net.rim.blackberry.api.sms.SMS;

2. 3. 4.

Create a class that implements the SendListener interface.


public class smsSendListener implements SendListener{...}

Create an instance of the class that implements the SendListener interface.


smsSendListener smsSL = new smsSendListener();

Add a SendListener.
SMS.addSendListener(smsSL);

Send a message
1. Import the required classes and interfaces.
import import import import import import import import net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.AddressException; net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.MessagingException; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store; net.rim.blackberry.api.mail.Transport;

2. 3.

Declare a Message object.


Message msg;

Specify a folder in which to save a copy of the sent message.


Store store = Session.getDefaultInstance().getStore(); Folder[] folders = store.list(Folder.SENT); Folder sentfolder = folders[0]; msg = new Message(sentfolder);

4.

Create an array of Address objects.


47

Development Guide

Send a message

Address toList[] = new Address[1];

5.

In a try block, add each address to the array.


try { }

toList[0]= new Address("ming.li@example.com", "Ming Li");

6.

In a catch block, manage a AddressException, which is thrown if an address is invalid.


catch(AddressException e) { System.out.println(e.toString()); }

7. 8.

Invoke Message.addRecipients() and provide the type of recipient (TO, CC, or BCC) and the array of addresses to add as parameters to the method. If the message has multiple types of recipients, invoke Message.addRecipients() once for each recipient type.
msg.addRecipients(Message.RecipientType.TO, toList);

9.

Invoke Message.setFrom(Address).
Address from = new Address("ming.li@example.com", "Ming Li"); msg.setFrom(from);

10. Invoke Message.setSubject(String).


msg.setSubject("Test Message");

11. Invoke Message.setContent(String). (Typically, the BlackBerry device application retrieves content from text that a BlackBerry device user types in a field.)
try {

msg.setContent("This is a test message."); } catch(MessagingException e) { System.out.println(e.getMessage()); }

12. Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();

13. Invoke Transport.send(Message) to send the message.


try {

trans.send(msg); } catch(MessagingException e)

48

Development Guide

Reply to a message

{ }

System.out.println(e.getMessage());

Reply to a message
1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store; net.rim.blackberry.api.mail.Transport;

2.

Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();

3. 4. 5. 6.

Invoke Session.waitForDefaultSession().getStore() to retrieve the Store object.


Store store = Session.waitForDefaultSession().getStore();

Invoke Store.list(INBOX) to retrieve all the folders in the INBOX folder. Store the folders in a Folder array.
Folder[] folders = store.list(INBOX);

Specify a specific array element to retrieve the inbox folder.


Folder inbox = folders[0];

Invoke Folder.getMessages() to retrieve the messages in the inbox folder. Store the messages in a Message array.
Message[] messages = inbox.getMessages();

7.

Invoke Message.reply(Boolean) and specify true to reply to all message recipients or false to reply to only the sender.
if( messages.length > 0 ) { Message msg = messages[0]; } Message reply = msg.reply(true);

8.

Invoke Transport.send(Message) to send the reply.


try {

trans.send(reply); } catch(MessagingException e) { System.out.println(e.getMessage()); }

49

Development Guide

Forward a message

Forward a message
1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.MessagingException; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Transport;

2.

Invoke Message.forward() on an existing Message object. The subject line of a forwarded message is set automatically to FW:original_subject.
Message fwdmsg = msg.forward();

3. 4. 5. 6.

Create an array of addresses.


Address toList[] = new Address[1];

Add a new Address object to the array.


toList[0]= new Address("ming.li@example.com", "Ming Li");

Invoke Message.addRecipients(int, Address[]) to add recipients to the Message.


fwdmsg.addRecipients(Message.RecipientType.TO, toList);

Invoke Message,setContent(String) to set the content of the message that appears before the original message.
try {

fwdmsg.setContent("This is a forwarded message."); } catch(MessagingException e) { System.out.println(e.getMessage()); }

7.

Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();

8.

Invoke Transport.send(Message).
try {

trans.send(fwdmsg); } catch(MessagingException e) { System.out.println(e.getMessage()); }

50

Development Guide

Work with message folders

Work with message folders


1. Import the required classes and interfaces.
import import import import import import import net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.MessageArguments; net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.FolderNotFoundException; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store;

2. 3.

Retrieve the store.


Store store = Session.waitForDefaultSession().getStore();

Complete any of the following actions: Task Open a folder view Steps a. Retrieve a list of folders.
Store store = null; store = Session.waitForDefaultSession().getStore(); Folder[] folders = store.list();

b.

Invoke Invoke.invokeApplication() to view a folder from the list.


Invoke.invokeApplication (Invoke.APP_TYPE_MESSAGES, new MessageArguments( folders[0]));

List the folders in a mailbox store

Invoke Store.list().
Folder[] folders = store.list();

Retrieve an array of folders by type

Invoke Store.list(int) and provide as a parameter the folder type.


Folder[] folders = store.list(INBOX); Folder inbox = folders[0];

Retrieve an array of folders through a search Retrieve a folder by its name a.

Invoke Store.findFolder(String).
Folder[] folders = store.findFolder("Inbox");

Invoke Store.getFolder(String) and provide as a parameter the absolute path to the folder.

51

Development Guide

Work with message folders

Task

Steps
Folder folder = store.getFolder("Mailbox - Yan Wang/Inbox/ Projects");

b. Retrieve a folder by its ID a. b.

Create code to manage a FolderNotFoundException exception if the folder does not exist. Invoke Folder.getID() to retrieve the folder ID. Invoke Store.getFolder() with the ID as a parameter.
Folder[] folders = store.list(); long id = folders[0].getId(); Folder f2 = store.getFolder(id);

File a message

Invoke Folder.appendMessage(Message) on a Folder object.


Message msg = new Message(); // populate the message Folder folder = store.getFolder("Inbox"); folder.appendMessage(msg);

52

Development Guide

Custom messages

Custom messages
Using custom messages and folders in the message list

You can use the net.rim.blackberry.api.messagelist package to create custom messages and folders for a BlackBerry device application. To use custom folders and messages in an application, you must create an application with the following modules: A UI module to interact with a BlackBerry device user A service module to interact with an application server and perform other actions in the background

Both modules are part of the same application but have different application entry points. You must determine the functionality that is part of each module. For example, a menu item that lets the user delete a message or mark a message as read should be part of the service module. A menu item that lets the user open or reply to a message should be part of the UI module. See the Message List Demo sample application that is included in the BlackBerry Java SDK for a demonstration on how to use this API.

Creating a module for background processes


A service module interacts with an application server and performs other actions in the background. It starts automatically when the BlackBerry device starts and runs without input from a BlackBerry device user. The service module can send messages to and receive messages from an application server and can add messages to the message list. The messages that it sends can use any protocol you want (for example, a native protocol, an email message protocol, or an SMS text message protocol). The user cannot stop the service module. When the device starts, the service module should register an application folder and listen for updates to the folder, such as when the user deletes a message or marks a message as read or unread.

Creating a module for the UI


The UI module contains UI components and is used to interact with a BlackBerry device user. Typically, the UI module starts automatically when the user interacts with a custom message. For example, if the user highlights a custom message in the Messages application and clicks the trackpad or touches the touch screen, the UI module should start and display the message content. If the UI module is not running and the user attempts to open a custom message, the UI module starts automatically. The UI module can also let users reply to a message and compose a new message.

Create a module for background processes


1. Create a project with settings that start the application automatically. In the BlackBerry Java Plug-in for Eclipse, select the Auto-run on startup check box in the BlackBerry Application Descriptor. For more information, see the BlackBerry Java Plug-in for Eclipse Development Guide.

53

Development Guide

Start the module for background processes or the module for the UI

2. 3. 4.

Create a class with the fields and methods for the module. Compile the project into a .jad file. Include the .jad file with the .jad files for the UI module and the main part of the application.

Start the module for background processes or the module for the UI
1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*;

Create a main method for the BlackBerry device application.


public static void main( String[] args ) { try {

3.

In main(), check if the value of the args parameter indicates that the application should start the service module or the UI module.
if( args.length == 1 && args[ 0 ].equals( "service" ) ) { } } else if( args.length == 1 && args[ 0 ].equals( "gui" ) ) { }

4.

If the application should start the service module, in the first if statement, create an instance of a class that contains the service functionality and items. Obtain a reference to an ApplicationMessageFolderRegistry object.
MLSampleService service = new MLSampleService(); ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();

5.

If the application should start the UI module, in the else if statement, create an instance of a class that contains the UI functionality and items. For example, the UI module should start if the BlackBerry device user clicks the application icon on the Home screen or opens a custom message in the Messages application. Display the UI for the application and add the application to the event dispatcher.
MLSampleGui gui = new MLSampleGui(); gui.showGui(); gui.enterEventDispatcher();

Code sample: Starting the module for background processes or the module for the UI
import net.rim.blackberry.api.messagelist.*; public static void main( String[] args ) { try 54

Development Guide

Create an icon for a custom message

if( args.length == 1 && args[ 0 ].equals( "service" ) ) { MLSampleService service = new MLSampleService(); ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance(); } else if( args.length == 1 && args[ 0 ].equals( "gui" ) ) { MLSampleGui gui = new MLSampleGui(); gui.showGui(); gui.enterEventDispatcher(); }

Create an icon for a custom message


You can associate icons with a custom message. You associate an icon with a custom message's type and status. For example, you can associate one icon with an unopened message and a different icon with an opened message. The icon appears on the left side of a message in the Messages application. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*; import net.rim.device.api.system.EncodedImage;

2.

Invoke EncodedImage.getEncodedImageResource() to create an icon based on an encoded image. Pass in the file name as an argument.
ApplicationIcon newIcon = new ApplicationIcon( EncodedImage.getEncodedImageResource( "ml_sample_new.png" ) ); ApplicationIcon openedIcon = new ApplicationIcon( EncodedImage.getEncodedImageResource ( "ml_sample_opened.png" ) );

3.

Invoke ApplicationMessageFolderRegistry.registerMessageIcon() to assign a status and an icon to a custom message. Specify the following as arguments: a value for the message type for a BlackBerry device application, a message status by using a field from the ApplicationMessage.Status interface, and an instance of the ApplicationIcon class.
int MESSAGE_TYPE = 0; int STATUS_NEW = ApplicationMessage.Status.UNOPENED; int STATUS_OPENED = ApplicationMessage.Status.OPENED; reg.registerMessageIcon( MESSAGE_TYPE, STATUS_NEW, newIcon ); reg.registerMessageIcon( MESSAGE_TYPE, STATUS_OPENED, openedIcon );

55

Development Guide

Create a custom folder in the message list

Create a custom folder in the message list


Custom messages are maintained in custom folders. To perform operations on custom messages, your BlackBerry device application must register at least one custom folder. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*; import net.rim.device.api.collection.ReadableList;

2. 3.

Create a class that implements the ApplicationMessage interface.


public class MLSampleMessage implements ApplicationMessage

Obtain a reference to an ApplicationMessageFolderRegistry object.


ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();

4.

Invoke ApplicationMessageFolderRegistry.registerFolder() to register a custom folder for each collection of messages.


// collections of MLSampleMessage instances ReadableList inboxMessages = messages.getInboxMessages(); ReadableList deletedMessages = messages.getDeletedMessages(); ApplicationMessageFolder inboxFolder = reg.registerFolder( INBOX_FOLDER_ID, "Inbox", inboxMessages ); ApplicationMessageFolder deletedFolder = reg.registerFolder( DELETED_FOLDER_ID, "Deleted Messages", deletedMessages, false );

5.

Invoke ApplicationMessageFolder.addListener() to add a listener so that your application can be notified when specific folder events occur. In the following code sample, the application listens for deleted messages. For a list of all actions that you can listen for, see the documentation for the ApplicationMessageFolderListener class in the API reference for the BlackBerry Java SDK.
deletedFolder.addListener( this, ApplicationMessageFolderListener.MESSAGE_DELETED );

6.

Create a class that implements the ApplicationMessageFolderListener interface.


public class AppFolderListener implements ApplicationMessageFolderListener

7.

Implement ApplicationMessageFolderListener.actionPerformed() to perform actions when a folder event occurs.


public void actionPerformed( int action, ApplicationMessage[] messages, ApplicationMessageFolder folder )

56

Development Guide

Send a notification when a custom folder changes

// check if action was performed on multiple messages if( messages.length == 1 ) { switch( action ) { case ApplicationMessageFolderListener.MESSAGE_DELETED: messageStore.deleteInboxMessage( message ); ...

8.

Invoke ApplicationMessageFolderRegistry.setRootFolderName() to specify the name of the root folder for your application's custom folders. The name of the root folder appears in the View Folder dialog box of the Messages application when an application registers more than one application message folder.
reg.setRootFolderName( "ML Sample" );

Send a notification when a custom folder changes


After your BlackBerry device application adds custom messages to the message list, you must manage the messages. For example, a BlackBerry device user might open the application and delete a message there, or the application might synchronize with a server and get more messages to display in the message list. To keep the message list synchronized with the custom messages in a custom folder, an application needs to be notified when a custom folder changes. 1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*;

Invoke ApplicationMessageFolder.fireElementAdded() to notify an application when a message is added to a custom folder.


inboxFolder.fireElementAdded( newMessage );

3.

Invoke ApplicationMessageFolder.fireElementRemoved() to notify an application when a message is removed from a custom folder.
inboxFolder.fireElementRemoved( deletedMessage );

4.

Invoke ApplicationMessageFolder.fireElementUpdated() to notify an application when a message in a custom folder is updated.


inboxFolder.fireElementUpdated( updatedMessage );

5.

Invoke ApplicationMessageFolder.fireReset() to notify an application when more than one message in a custom folder changes.
inboxFolder.fireReset();

57

Development Guide

Create a custom indicator

Create a custom indicator


A custom indicator appears on the Home screen along with other indicators, such as the new message indicator and calendar reminders. You can use the ApplicationIndicator class to create and manage an indicator for custom messages. For example, you can create an indicator to display the number of unread custom messages in the message list. Indicators are visible even when the BlackBerry device is locked. Your application can register only one indicator and must register the indicator every time that the BlackBerry device starts. The size of an indicator can vary depending on the device and theme. For more information on the size of an indicator, see the UI Guidelines for BlackBerry Smartphones. 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( "clowds.gif" ); ApplicationIcon icon = new ApplicationIcon( image );

4.

Register the icon 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, false, true);

5.

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

Retrieve the registered indicator by invoking

6.

Set the icon 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 );

Hide an indicator
1. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*;

58

Development Guide

Remove a custom indicator

2.

To temporarily hide an indicator, invoke ApplicationIndicator.setVisible() and provide false as the argument.
appIndicator.setVisible( false );

Remove a custom indicator


You can remove a custom indicator from the Home screen by unregistering it. 1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*;

Remove the custom indicator by invoking ApplicationIndicatorRegistry.unregister().


reg.unregister();

59

Development Guide

Attachments

Attachments

You can use the Mail API in the net.rim.blackberry.api.mail package to manage attachments in incoming email messages and include attachments in outgoing email messages on a BlackBerry device. An attachment is represented as a separate BodyPart object on a Multipart message.

Create an attachment handler


You can use the AttachmentHandler interface to manage an attachment to an email message that appears in the message list on the BlackBerry device. Note: The BlackBerry Attachment Service receives all attachments first. Third-party attachment handlers cannot override this default behavior. For more information about the BlackBerry Attachment Service, see the BlackBerry Enterprise Server Administration Guide. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.mail.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.ui.component.*;

2. 3.

Implement the AttachmentHandler interface to create a custom attachment handler.


public class AttachTest implements AttachmentHandler {...}

Implement the supports(String) method, to specify the content type of the attachment supported by your handler.
public boolean supports(String contentType) { return (contentType.toLowerCase().indexOf("contenttype") != -1 ? true : false); }

4.

Implement the menuString() method, to specify the text of the menu item that displays when a user selects an attachment.
public String menuString() { return "Custom Attachment Viewer"; }

5.

Implement the run() method to specify what should happen when a user clicks the menu item. In the following code sample, a new screen uses the RichTextField class to display a String representation of the content of the attachment.
public void run(Message m, SupportedAttachmentPart p) { MainScreen view = new MainScreen(); view.setTitle("Attachment Viewer"); view.add(new RichTextField(new String((byte[])p.getContent()))); }

60

Development Guide

Retrieve the contents of an attachment

6.

Invoke AttachmentHandlerManager.addAttachmentHandler(), to register the attachment handler with the manager. Note that the attachment name must be prefixed with "x-rimdevice" for the attachment to be sent and stored on the BlackBerry device.
AttachmentHandlerManager m = AttachmentHandlerManager.getInstance(); CustomAttachmentHandler ah = new CustomAttachmentHandler(); m.addAttachmentHandler(ah);

Retrieve the contents of an attachment


1. 2. Import the net.rim.blackberry.api.mail.SupportedAttachmentPart class. Invoke SupportedAttachmentPart.getContent().
String s = new String((byte[])p.getContent());

Retrieve information about an attachment


1. 2. Import the net.rim.blackberry.api.mail.SupportedAttachmentPart class. Invoke the methods of the SupportedAttachmentPart class. The SupportedAttachmentPart class represents an attachment with a corresponding viewer on the BlackBerry device. The UnsupportedAttachmentPart class represents an attachment that does not have a viewer on the BlackBerry device.

Send a message with an attachment


1. Import the required classes and interfaces.
import import import import import import net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.MessagingException; net.rim.blackberry.api.mail.Multipart; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.SupportedAttachmentPart; net.rim.blackberry.api.mail.Transport;

2.

Create a new Multipart object to create a multipart message.


byte[] data = new byte[256]; MultiPart multipart = new MultiPart();

3.

Create a SupportedAttachmentPart object, designating the Multipart object as its parent, to create each component of the screen.
SupportedAttachmentPart attach = new SupportedAttachmentPart( multipart, "application/x-example", "filename", data);

4.

Invoke MultiPart.addBodyPart(SupportedAttachmentPart) to add each supportedAttachmentPart object to the multipart object.

61

Development Guide

Download attachments automatically

multipart.addBodyPart(attach);

5.

Invoke Message.setContent(Multipart) and provide as a parameter the Multipart object to set the content of the attachment.
msg.setContent(multipart);

6.

Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();

7.

Invoke Transport.send(Message).
try {

trans.send(msg); } catch(MessagingException e) { System.out.println(e.getMessage()); }

Download attachments automatically


When a message arrives in the messages application on the BlackBerry device with an attachment, you can automatically download the attachment and store it on the BlackBerry device. Before downloading attachments, the AttachmentDownloadManager class validates the attachment. AttachmentDownloadManager throws exceptions if any of the following conditions occur. the application attempts to invoke the download while a download is already in progress the application attempts to download zero length files. the size of the attachment is larder than permitted by the application IT policy or service books attachments are encrypted there is not enough space available on the BlackBerry device or SD card

The AttachmentDownloadManager.download() method performs verification during the download process. If verification errors are found, the method throws an exception. For a list of possible verification errors, see the API reference for the BlackBerry Java Development Environment. Note: The BlackBerry Attachment Service receives all attachments first. Third-party attachment handlers cannot override this default behavior. For more information about the BlackBerry Attachment Service, see the BlackBerry Enterprise Server Administration Guide. 1. Import the required classes and interfaces.
import java.io.IOException; import net.rim.blackberry.api.mail.*;

62

Development Guide

Download attachments automatically

2.

Implement the DownloadProgressListener interface. Create an instance of the AttachmentDownloadManager class.


public class AutoAttachTest implements DownloadProgressListener { AttachmentDownloadManager _adm = new AttachmentDownloadManager();

3.

Use the methods available in AttachmentDownloadManager to determine information about the attachment.
public public public public String String String String fileSize fileName fileType filePath = = = = getFileSize(BodyPart bodyPart); getFileName(BodyPart bodyPart); getFileContentType(BodyPart bodyPart); getDownloadedFileName(BodyPart bodyPart);

4. 5.

Invoke AttachmentDownloadManager.download(), to download the attachment.


_adm.download(bodyParts, null, this);

Override the DownloadProgressListener callback methods, to provide updates about the status of the download of the attachment.
private void downloadCancelled(String msg) { BodyPart bodyPart = (BodyPart) element; _screen.displayProgress("Failed to download " + _adm.getFileName(bodyPart)); } private void downloadCompleted(Object element) { BodyPart bodyPart = (BodyPart) element; _screen.displayProgress(_adm.getFileName(bodyPart) + " downloaded."); } public void updateProgress(Object element, int current, int total) { }

63

Development Guide

Calendar

Calendar
Open the calendar
1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.CalendarArguments; import net.rim.blackberry.api.invoke.Invoke; import net.rim.device.api.system.ControlledAccessException;

2. 3.

Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments). Check for a ControlledAccessException if your application does not have permission to access the application that it invokes.

View or change a calendar entry


1. Import the required classes and interfaces.
import import import import import import import java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.Event; javax.microedition.pim.EventList; net.rim.blackberry.api.invoke.CalendarArguments; net.rim.blackberry.api.invoke.Invoke; net.rim.device.api.system.ControlledAccessException;

2.

Retrieve an Event from the list of events.


Event e = null; EventList el = (EventList)PIM.getInstance().openPIMList( PIM.EVENT_LIST, PIM.READ_WRITE ); Enumeration events = el.items(); e = (Event)events.nextElement();

3.

Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments) using the CalendarArguments object created using the ARG_VIEW_DEFAULT field and the retrieved Event.
Invoke.invokeApplication( Invoke.APP_TYPE_CALENDAR, new CalendarArguments ( CalendarArguments.ARG_VIEW_DEFAULT, e ) );

4.

Check for a ControlledAccessException if your application does not have permission to access the application that it invokes.

Open a new populated calendar entry


1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import javax.microedition.pim.Event; import javax.microedition.pim.EventList; 64

Development Guide

Update calendar entry information

import net.rim.blackberry.api.invoke.CalendarArguments; import net.rim.blackberry.api.invoke.Invoke; import net.rim.device.api.system.ControlledAccessException;

2.

Create a new Event using an EventList object.


EventList el = (EventList)PIM.getInstance().openPIMList( PIM.EVENT_LIST, PIM.READ_WRITE ); Event e = el.createEvent();

3.

Add information to the Event object.


e.addString( Event.SUMMARY, 0, "Go For A Walk" ); e.addString( Event.LOCATION, 0, "The Park" ); long start = System.currentTimeMillis() + 8640000; e.addDate( Event.START, 0, start ); e.addDate( Event.END, 0, start + 72000000 );

4.

Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments) using the CalendarArguments object created using the ARG_NEW field and the Event.
Invoke.invokeApplication( Invoke.APP_TYPE_CALENDAR, new CalendarArguments ( CalendarArguments.ARG_NEW, e ) );

Update calendar entry information


1. Import the required classes and interfaces.
import import import import import java.util.Date; javax.microedition.pim.Event; javax.microedition.pim.EventList; javax.microedition.pim.PIM; javax.microedition.pim.RepeatRule;

2.

Invoke openPIMList() to open a list of calendar entries. Provide the following as parameters: the type of list to open (PIM.EVENT_LIST) and the mode in which to open the list: READ_WRITE READ_ONLY WRITE_ONLY
EventList eventList = null; try { eventList = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); } catch (PimException e) { // Handle exception. }

3.

To update calendar information, perform any of the following tasks:

65

Development Guide

Update calendar entry information

Task Create an appointment Add appointment information

Steps Invoke createEvent() on an event list.


Event event = eventList.createEvent();

Invoke Event.isSupportedField(int) to verify that an item supports a field.


if (event.isSupportedField(Event.SUMMARY)) { event.addString(Event.SUMMARY, Event.ATTR_NONE, "Meet with customer"); } if (event.isSupportedField(Event.LOCATION)) { event.addString(Event.LOCATION, Event.ATTR_NONE, "Conference Center"); } Date start = new Date(System.currentTimeMillis() + 8640000); if (event.isSupportedField(Event.START)) { event.addDate(Event.START, Event.ATTR_NONE, start); } if (event.isSupportedField(Event.END)) { event.addDate(Event.END, Event.ATTR_NONE, start + 72000000); } if (event.isSupportedField(Event.ALARM)) { if (event.countValues(Event.ALARM) > 0) { event.removeValue(Event.ALARM,0); event.setInt(Event.ALARM, 0, Event.ATTR_NONE, 396000); } }

Create a recurring appointment

a.

Create a RepeatRule object. The RepeatRule class defines fields for the properties and values that you can set, such as COUNT, FREQUENCY, and INTERVAL. Invoke RepeatRule.getFields() to retrieve an array of supported fields.

b.

66

Development Guide

Retrieve calendar entry information

Task

Steps c. Invoke RepeatRule.setInt(int, int) or


RepeatRule.setDate (int, int, int, long) on a new RepeatRule object to define a recurring pattern. RepeatRule recurring = new RepeatRule(); recurring.setInt(RepeatRule.FREQUENCY, RepeatRule.MONTHLY); recurring.setInt(RepeatRule.DAY_IN_MONTH, 14);

d.

Invoke Event.setRepeat(RepeatRule) on an event to assign a recurrence pattern to an appointment.


EventList eventList = (EventList)PIM.getInstance().openPIMList (PIM.EVENT_LIST, PIM.READ_WRITE); Event event = eventList.createEvent(); event.setRepeat(recurring);

Change appointment information

a. b. c.

Invoke the appropriate set method, such as setString() to replace an existing value with a new one. Invoke Event.countValues() to determine if a value is already set for the field. Use the corresponding set method, such as setString() to change an existing value.
if (event.countValues(Event.LOCATION) > 0) { event.setString(Event.LOCATION, 0, Event.ATTR_NONE, "Board Room"); }

Save an appointment

a.

Before you save the appointment, to identify appointment fields that have changed since the appointment was last saved, invoke Event.isModified(). Invoke Event.commit().
if(event.isModified()) { event.commit(); }

b.

Retrieve calendar entry information


1. Import the required classes and interfaces.

67

Development Guide

Export a calendar entry

javax.microedition.pim.Event javax.microedition.pim.EventList javax.microedition.pim.PIM

2.

Invoke EventList.items() to retrieve an enumeration of appointments.


EventList eventList = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_ONLY); Enumeration e = eventList.items();

3.

Invoke PIMItem.getFields() to retrieve an array of IDs of fields that have data for a particular task. Invoke PIMItem.getString() to retrieve the field values.
while (e.hasMoreElements()) { Event event = (Event)e.nextElement(); int[] fieldIds = event.getFields(); int id; for(int index = 0; index < fieldIds.length; ++index) { id = fieldIds[index]; if(e.getPIMList().getFieldDataType(id) == STRING) { for(int j=0; j < event.countValues(id); ++j) { String value = event.getString(id, j); System.out.println(event.getFieldLable(id) + "=" + value); } } } }

Export a calendar entry


1. Import the required classes and interfaces.
import import import import import java.io.ByteArrayOutputStream; java.util.Enumeration; javax.microedition.pim.Event; javax.microedition.pim.EventList; javax.microedition.pim.PIM;

2.

Invoke PIM.supportedSerialFormats() specifying the list type (PIM.EVENT_LIST), to retrieve a string array of supported serial formats.
String[] dataFormats = PIM.supportedSerialFormats(PIM.EVENT_LIST);

3. 4.

Use an output stream writer to export calendar entries from the BlackBerry device to a supported serial format, such as iCal. Invoke toSerialFormat() to write an item in serial format. The enc parameter specifies the character encoding to use when writing to the output stream. Supported character encodings include UTF8, ISO-8859-1, and UTF-16BE. This parameter cannot be null.

68

Development Guide

Import a calendar entry

EventList eventList = (EventList)PIM.getInstance().openPIMList( PIM.EVENT_LIST, PIM.READ_ONLY ); ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); Enumeration e = eventList.items(); while (e.hasMoreElements()) { Event event = (Event)e.nextElement(); PIM.getInstance().toSerialFormat(event, bytestream, "UTF8", dataFormats[0]); }

Import a calendar entry


1. Import the required classes and interfaces.
import import import import import java.io.ByteArrayInputStream; java.io.ByteArrayOutputStream; javax.microedition.pim.Event; javax.microedition.pim.EventList; javax.microedition.pim.PIM;

2. 3.

Invoke PIM.getInstance().fromSerialFormat() to return an array of PIMItem objects. Invoke EventList.importEvent() to add a new calendar entry.
// Convert an existing entry into a iCal and then // import the iCal as a new entry String[] dataFormats = PIM.supportedSerialFormats(); // Write entry to iCal ByteArrayOutputStream os = new ByteArrayOutputStream(); PIM.getInstance().toSerialFormat(event, os, "UTF8", dataFormats[0]); // Import entry from iCal ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); PIMItem[] pi = PIM.getInstance().fromSerialFormat(is, "UTF8"); EventList eventList = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); Event event2 = eventList.importEvent((Event)pi[0]);

Retrieve multiple lists of calendar entries


The first element in the array of lists is the default list. 1. 2. Import the javax.microedition.pim.PIM class. Invoke PIM.listPIMLists(int pimListType).
String[] allLists = PIM.listPIMLists(PIM.EVENT_LIST);

69

Development Guide

Notify a BlackBerry device application when a list of calendar entries changes

Notify a BlackBerry device application when a list of calendar entries changes


1. Import the required classes and interfaces.
import import import import javax.microedition.pim.EventList; javax.microedition.pim.PIM; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.blackberry.api.pdap.PIMListListener;

2. 3.

Implement the PIMListListener interface.


public class MyEventListListener implements PIMListListener {...}

Invoke BlackBerryPIMList.addListener() to register to receive notifications of changes to a list of calendar entries.


BlackBerryPIMList eventList = (BlackBerryPIMList)PIM.getInstance().openPIMList (PIM.EVENT_LIST, PIM.READ_WRITE); eventList.addListener(new MyEventListListener());

Notify a BlackBerry device application when the default list of calendar entries changes
When an update occurs to the list of services on a BlackBerry device, the list of PIM databases on a device may change. This action may result in the creation of a new default list of calendar entries. 1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import net.rim.blackberry.api.pdap.BlackBerryPIM; import net.rim.blackberry.api.pdap.ListChangeListener;

2. 3.

Implement the ListChangeListener interface.


public class MyListChangeListener implements ListChangeListener {...}

Invoke BlackBerryPIM.addListChangeListener() to register to receive notifications of changes to a default PIM list.


ListChangeListener listener = new MyListChangeListener(); ((BlackBerryPIM) PIM.getInstance()).addListChangeListener(listener);

4.

To have the application always use the default PIMList, store a reference to the desired PIMList and design the ListChangeListener.defaultListChanged() method to update the reference when the default list changes.

70

Development Guide

Update a calendar entry with no notification

Update a calendar entry with no notification


You can update a calendar entry on a BlackBerry device without sending notifications to the entry's participants. 1. Import the required classes and interfaces.
import import import import import java.util.*; javax.microedition.pim.*; net.rim.blackberry.api.pdap.BlackBerryEvent; net.rim.blackberry.api.pdap.BlackBerryEventList; net.rim.blackberry.api.pdap.BlackBerryPIMItem;

2.

Invoke PIM.openPIMList() to open a list of calendar entries as a BlackBerryEventList object.


BlackBerryEventList eventList = null; try { eventList = (BlackBerryEventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); } catch (PIMException e) { // Handle exception }

3.

Retrieve a BlackBerryEvent object from the list of entries.


Enumeration events = eventList.items(); BlackBerryEvent event = (BlackBerryEvent) events.nextElement();

4.

Modify the entry.


if (eventList.isSupportedField(Event.SUMMARY)) { event.addString(Event.NOTE, Event.ATTR_NONE, "Remember to bring food"); }

5.

Invoke BlackBerryPIMItem.commit() and specify the flag BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES to save your changes.
if(event.isModified()) { try { int result; result = ((BlackBerryPIMItem) event).commit(BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES); } catch (PIMException e) { // Handle exception } }

71

Development Guide

Remove a calendar entry with no notification

If you specify BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES when committing changes to a calendar entry, notification is not sent unless the calendar entry is a new meeting or meeting participants have been added since the last update (meeting participants must be notified about the meeting in order to accept the meeting invitation). If notification was sent, BlackBerryPIMItem.commit() returns BlackBerryEvent.MEETING_RECORD_NOT_FOUND or BlackBerryEvent.INVITEE_LIST_CHANGED. Code sample
BlackBerryEventList eventList = null; try { eventList = (BlackBerryEventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); Enumeration events = eventList.items(); BlackBerryEvent event = (BlackBerryEvent) events.nextElement(); if (eventList.isSupportedField(Event.SUMMARY)) { event.addString(Event.NOTE, Event.ATTR_NONE, "Remember to bring food"); } if(event.isModified()) { int result; result = ((BlackBerryPIMItem) event).commit(BlackBerryEvent .DO_NOT_NOTIFY_ATTENDEES); }

} catch (PIMException e) { // Handle exception }

Remove a calendar entry with no notification


You can remove a calendar entry on a BlackBerry device without sending notifications to the entry's participants. 1. Import the required classes and interfaces.
import import import import java.util.*; javax.microedition.pim.*; net.rim.blackberry.api.pdap.BlackBerryEvent; net.rim.blackberry.api.pdap.BlackBerryEventList;

2.

Invoke PIM.openPIMList() to open a list of calendar entries as a BlackBerryEventList object.


BlackBerryEventList eventList = null; try { eventList = (BlackBerryEventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE);

72

Development Guide

Remove a calendar entry with no notification

} catch (PIMException e) { // Handle exception }

3.

Retrieve a BlackBerryEvent object from the list of entries.


Enumeration events = eventList.items(); BlackBerryEvent event = (BlackBerryEvent) events.nextElement();

4.

Invoke BlackBerryEventList.removeElement() and specify the flag BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES to remove the entry without notification.
try {

eventList.removeEvent(event, BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES); } catch (PIMException e) { // handle exception {

If an error occurs when you try to remove the event, the method throws a PIMException. Code sample
BlackBerryEventList eventList = null; try { eventList = (BlackBerryEventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); Enumeration events = eventList.items(); BlackBerryEvent event = (BlackBerryEvent) events.nextElement(); eventList.removeEvent(event, BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES); } catch (PIMException e) { // Handle exception }

73

Development Guide

Contact list

Contact list

You can use an instance of the ContactList class or BlackBerryContactList class in your application to add and view contact information in the contacts application on the BlackBerry device. You can create Contact or BlackBerryContact objects to store information for individual contacts such as the name, phone number, email address, and street address. Your application can perform tasks such as adding, deleting, and changing contact list entries.

Multiple contact lists support


Support for multiple contact lists is available in BlackBerry Java Development Environment 5.0 or later. Each contact list has a system-assigned contact list name and a UID that you can use to retrieve the list. You can change the contact list name by using the BlackBerry Desktop Manager to change the name of the service that is associated with the contact list name. You cannot change the UID. When deciding how you want to open a contact list, you should consider persistence on the BlackBerry device. If your application requires the contact list name to persist across OS updates, use the UID to open the contact list. If your application requires the contact list name to persist only across BlackBerry device restarts, you can use the contact list name. Because a contact list name can change, you can register a listener for name change events by invoking BlackBerryPIM.addListChangeListener(ListChangeListener listener). You can retrieve the names of the contact lists that are installed on a BlackBerry device by invoking PIM.listPIMLists(int pimListType) and passing in PIM.CONTACT_LIST as pimListType. The String array that is returned provides the system-assigned names for the contact lists on the device. The contact list name that is at index 0 of the returned String array is the default contact list. You can retrieve the UID of a contact list on a BlackBerry device by invoking BlackBerryPIMList.getPIMListUID(). You can open a contact list by its name by invoking PIM.openPIMList(int pimListType, int mode, String name). You can open a contact list by its UID by invoking BlackBerryPIM.openPIMList(int pimListType, int mode, long uid). You can open a list that combines multiple contact lists on a device by invoking one of the BlackBerryPIM.openUnifiedPIMList() methods.

Open the contacts application


You can open the contacts application on the BlackBerry device by using the Invoke.invokeApplication() method, and passing in the relevant arguments. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.AddressBookArguments; import net.rim.device.api.system.ControlledAccessException;

2.

Invoke Invoke.invokeApplication(APP_TYPE_ADDRESSBOOK, AddressBookArguments).


AddressBookArguments abArg = new AddressBookArguments(); Invoke.invokeApplication(Invoke.APP_TYPE_ADDRESSBOOK, abArg);

74

Development Guide

Open the contacts application by using contact data

3.

Check for a ControlledAccessException if your application does not have permission to access the application that it invokes.

Open the contacts application by using contact data


You can open the contacts application on a BlackBerry device and display a contact by using the Invoke.invokeApplication() method, and passing in contact data as a parameter of an AddressBookArguments object. 1. Import the required classes and interfaces.
import import import import import import import net.rim.blackberry.api.invoke.AddressBookArguments; net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.device.api.system.ControlledAccessException; javax.microedition.pim.PIM; javax.microedition.pim.PIMException;

2.

Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList(int, int) to open the default contact list, passing in as parameters the type of list to open (PIM.CONTACT_LIST) and the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). To open a named contact list, you can instead invoke PIM.openPIMList(int, int, String).
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

3. 4. 5.

Invoke BlackBerryContactList.getByUID(String uid) to retrieve a contact from the contact list.


BlackBerryContact contact = contactList.getByUID("1XKIOD898");

Create an instance of the AddressBookArguments class, passing in a Contact object as a parameter.


AddressBookArguments abArg = new AddressBookArguments("ARG_VIEW", contact);

Invoke Invoke.invokeApplication(APP_TYPE_ADDRESSBOOK, AddressBookArguments) and use the AddressBookArguments object for the contact.
Invoke.invokeApplication(Invoke.APP_TYPE_ADDRESSBOOK, abArg);

6.

Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.

Open the contacts application with a specific contact list


You can open the contacts application on a BlackBerry device and display a specific contact list by invoking the BlackBerryContactList.choose() method. 1. Import the required classes and interfaces.

75

Development Guide

Open the contacts application with a specific contact list

import import import import import import import import import

net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactGroup; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIM; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.device.api.system.ControlledAccessException; javax.microedition.pim.PIM; javax.microedition.pim.PIMException; javax.microedition.pim.PIMItem;

2.

Invoke PIM.listPIMLists(int pimListType) to return an array of String objects. The returned array provides the system-assigned names, one for each PIM list of the specified type. The default list of the specified type is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);

3. 4. 5.

Iterate over the array that is returned from PIM.listPIMLists() to search for the system-assigned name for the contact list that you want to display. Invoke BlackBerryPIMList.getPIMListUID() to return the UID for contact list.
long uid = cl.getPIMListUID();

Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList(int, int, long) to open the contact list, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the UID.
BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, uid);

6.

Invoke BlackBerryContactList.choose() to return a BlackBerryContact or a BlackBerryContactGroup PIMItem.


PIMItem item = list.choose(); if (item instanceof BlackBerryContact) { BlackBerryContact contact = (BlackBerryContact) item; int values = contact.countValues(BlackBerryContact.EMAIL); String email = contact.getString(BlackBerryContact.EMAIL, 0); System.out.println("Email is: " + email); } else if (item instanceof BlackBerryContactGroup) { ... }

7.

Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.

76

Development Guide

Create a contact and assign it to a contact list

Create a contact and assign it to a contact list


You can create a contact and assign it to either the default contact list or another contact list on a BlackBerry device. 1. Import the required classes and interfaces.
import import import import import import import import net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.device.api.system.ControlledAccessException; javax.microedition.pim.PIM; javax.microedition.pim.PIMList; javax.microedition.pim.PIMException; javax.microedition.pim.ContactList;

2.

To add the new contact to the default contact list, invoke PIM.openPIMList(int, int) to open the default contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST) and the PIM.READ_WRITE access mode. Proceed to step 4.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

3.

To add the new contact to a contact list that is not the default contact list, perform the following actions: a. Invoke PIM.listPIMLists(int), passing in as the parameter the type of list (PIM.CONTACT_LIST), to return an array of String objects. The returned array provides the system-assigned names for each contact list. The default contact list is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);

b. c.

Iterate over the array that PIM.listPIMLists() returns to search for the system-assigned name for the contact list that you want to open. Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the PIM.READ_WRITE access mode, and the contact list name.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);

4. 5.

Invoke ContactList.createContact() to add the new contact to the contact list.


BlackBerryContact contact = contactList.createContact();

Invoke one or more of the following methods to add information for the new contact. For more information about PIMItem methods, see the API reference for the BlackBerry Java Development Environment. addString() addStringArray() addDate() addInt() addBoolean() addBinary()
77

Development Guide

Retrieve contact information

6.

Invoke the following methods to verify that the information meets the size requirements and type requirements for the specified contact field. Invoke ContactList.isSupportedField(int) to verify that the item supports the field type. Invoke ContactList.isSupportedAttribute(int, int) to verify that the field supports the specified attribute. Invoke PIMList.maxValues(int field) to verify the number of values that the field supports. Invoke Contact.commit() to commit the changes.
if(contact.isModified()) { contact.commit(); }

7.

8.

Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.

Retrieve contact information


You can retrieve information from a contact list on a BlackBerry device by invoking one of the PIMList.items () methods. These methods return an enumeration of all the contacts in a specific contact list. You can invoke the BlackBerryContactList.items() methods to return contact groups. 1. Import the required classes and interfaces.
import import import import import import import net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIMList; java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.PIMException; javax.microedition.pim.PIMItem;

2.

Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList() to open a contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the name if you are not opening the default contact list.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

3. 4.

Invoke PIMList.items() to retrieve an enumeration of items in a contact list.


Enumeration _enum = contactList.items();

Invoke one of the PIMItem getter methods to retrieve contact information. To retrieve an array of fields that contain the data for a specified contact, invoke PIMItem.getFields(). To retrieve a String that represents the value for a specified contact field, invoke PIMItem.getString (int field, int index).

78

Development Guide

Retrieve a contact list UID

To retrieve a date that represents the value for a specified contact field, invoke PIMItem.getDate(int field, int index).
while (_enum.hasMoreElements()) { BlackBerryContact c = (BlackBerryContact)_enum.nextElement(); int[] fieldIds = c.getFields(); int id; for(int index = 0; index < fieldIds.length; ++index) { id = fieldIds[index]; if(c.getPIMList().getFieldDataType(id) == BlackBerryContact.STRING) { for(int j=0; j < c.countValues(id); ++j) { String value = c.getString(id, j); System.out.println(c.getPIMList().getFieldLabel(id) + "=" + value); } } } }

Retrieve a contact list UID


You can open a contact list on a BlackBerry device by specifying a system-assigned name or a UID. The UID is associated with a BlackBerry Enterprise Server account and persists across all BlackBerry device changes, including OS updates. You can open the contact list by its UID by invoking BlackBerryPIM.openPIMList(int pimListType, int mode, long uid). 1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIMList; javax.microedition.pim.PIM; javax.microedition.pim.PIMException; javax.microedition.pim.PIMItem;

2. 3.

Access the contact list that you want to work with. Invoke BlackBerryPIMList.getPIMListUID() to retrieve the UID of the contact list.
long uid = list.getPIMListUID();

Export a contact
You can export contact information from a contact list on a BlackBerry device to an output stream. The export process converts a PIM item to a stream of bytes that another application can import. You can export PIM data to a supported serial format by invoking PIM.toSerialFormat(PIMItem, OutputStream, String, String),

79

Development Guide

Import a contact

and passing in as arguments the PIMItem, the OutputStream to which the serialized PIMItem is written, the character encoding format to use when writing to the output stream, and the supported serial format to convert to, such as vCard. 1. Import the required classes and interfaces.
import import import import import import java.io.UnsupportedEncodingException; java.util.Enumeration; javax.microedition.pim.Contact; javax.microedition.pim.ContactList; javax.microedition.pim.PIM; javax.microedition.pim.PIMException;

2.

Invoke PIM.supportedSerialFormats() and specify the list type (PIM.CONTACT_LIST) to retrieve a string array of the supported serial formats.
ContactList contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); String[] dataFormats = PIM.getInstance().supportedSerialFormats(PIM.CONTACT_LIST);

3.

Invoke PIM.getInstance().toSerialFormat(item, stream, enc, dataFormat)to write an item to a supported serial format. Use the enc parameter to specify the character encoding format to use when writing to the output stream. Supported character encoding formats include UTF8, ISO-8859-1, and UTF-16BE. If the enc parameter is null, the method uses UTF-8.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Enumeration e = contactList.items(); while (e.hasMoreElements()) { try { Contact c = (Contact)e.nextElement(); PIM.getInstance().toSerialFormat(c, byteStream, "UTF8", dataFormats[0]); } catch (UnsupportedEncodingException ex) { System.out.println(ex.toString()); } }

Import a contact
You can import contact information from a compatible input stream to a contact list on a BlackBerry device. You can import contact information by invoking fromSerialFormat(InputStream, String), and passing in as arguments the InputStream from which the PIMItem is written and the character encoding format to use. Supported character encoding formats include UTF8, ISO-8859-1, and UTF-16BE. 1. Import the required classes and interfaces.

80

Development Guide

Delete a contact

import import import import import

java.io.ByteArrayOutputStream; javax.microedition.pim.Contact; javax.microedition.pim.ContactList; javax.microedition.pim.PIM; javax.microedition.pim.PIMItem;

2.

Invoke PIM.getInstance().fromSerialFormat() to return an array of PIM items.


ByteArrayInputStream istream = new ByteArrayInputStream(outputStream.toByteArray()); PIMItem[] pi = PIM.getInstance().fromSerialFormat(istream, "UTF8");

3.

Open a contact list and invoke ContactList.importContact() to create a new contact by using a PIM item.
ContactList contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); Contact contact2 = contactList.importContact((Contact) pi[0]); contact2.commit();

Delete a contact
You can delete a contact from the default contact list or another contact list on a BlackBerry device. 1. Import the required classes and interfaces.
import import import import import import import net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.device.api.system.ControlledAccessException; javax.microedition.pim.Contact; javax.microedition.pim.ContactList; javax.microedition.pim.PIM; javax.microedition.pim.PIMException;

2.

To delete a contact from the default contact list, invoke PIM.openPIMList(int, int) to open the default contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), and the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). Proceed to step 4.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

3.

To delete a contact from a contact list that is not the default contact list, perform the following actions: a. Invoke listPIMLists(int pimListType) to return an array of String objects. The returned array provides the system-assigned name for each contact list. The default contact list is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);

b.

Iterate over the array that PIM.listPIMLists() returns to search for the system-assigned name for the contact list that you want to delete.

81

Development Guide

Notify an application when a contact list changes

c.

Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the contact list name.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);

4. 5.

Invoke BlackBerryContactList.removeContact() to delete the contact from the contact list.


contactList.removeContact(contact);

Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.

Notify an application when a contact list changes


You can register your application to receive notification of changes to the contact lists on a BlackBerry device by implementing the PIMListListener interface. The PIMListListener interface provides the following methods: 1.
itemAdded(PIMItem item), which is invoked when an item is added to a contact list itemUpdated(PIMItem oldItem, PIMItem newItem), which is invoked when an item changes itemRemoved(PIMItem item), which is invoked when an item is deleted from a contact list

Import the required classes and interfaces.


import import import import import import import net.rim.blackberry.api.pdap.BlackBerrryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.blackberry.api.pdap.PIMListListener; net.rim.device.api.system.ControlledAccessException; javax.microedition.pim.PIMList; javax.microedition.pim.PIMException;

2.

To receive change notifications for the default contact list, invoke PIM.openPIMList(int, int) to open the default contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), and the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). Proceed to step 4.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

3.

To receive change notifications for a contact list that is not the default contact list, perform the following actions: a. Invoke listPIMLists(int), passing in as the parameter the type of list to open (PIM.CONTACT_LIST), to return an array of String objects. The returned array provides the system-assigned name for each contact list. The default contact list is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);

b.

Iterate over the array that PIM.listPIMLists() returns to search for the system-assigned name for the contact list that you want to receive change notifications for.

82

Development Guide

Creating and removing contact lists

c.

Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the contact list name.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);

4. 5.

Invoke BlackBerryPIMList.addListener() to register a listener for the contact list.


(BlackBerryPIMList) contactList.addListener(new PIMListListener());

Override the PIMListListener.itemAdded(), PIMListListener.itemUpdated(), and PIMListListener.itemRemoved() methods to configure the notification behavior.
public void itemAdded(PIMItem item) { System.out.println("ITEM ADDED: " + (BlackBerryContact) item.getString(BlackBerryContact.UID, 0)); } public void itemUpdated(PIMItem oldItem, PIMItem newItem) { System.out.println("ITEM UPDATED: " + (BlackBerryContact) oldItem.getString(BlackBerryContact.UID, 0) + " to " + (BlackBerryContact) newItem.getString(Contact.UID, 0)); } public void itemRemoved(PIMItem item) { System.out.println("ITEM REMOVED: " + (BlackBerryContact) item.getString(BlackBerryContact.UID, 0)); }

6.

Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.

Creating and removing contact lists


You can create contact lists on a BlackBerry device by invoking BlackBerryPIM.createPIMList(). Currently, the PIM list type you specify when you invoke createPIMList() must be PIM.CONTACT_LIST or a PIMException is thrown. You can also remove contact lists by invoking BlackBerryPIM.removePIMList(). Currently, this method supports PIM lists only of type PIM.CONTACT_LIST.

Create a contact list


You can create contact lists on a BlackBerry device. Note the following about contact lists that you create: Each contact list has a unique ID, which is the value that is returned by createPIMList(). The contact lists do not have service records and do not support wireless synchronization.

83

Development Guide

Creating and removing contact lists

1.

Applications can register to listen for changes to your contact list by invoking BlackBerryPIMList.addListener(). Import the required classes and interfaces.
import import import import import import import import javax.microedition.pim.Contact; javax.microedition.pim.PIM; javax.microedition.pim.PIMException; javax.microedition.pim.PIMItem; net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIM; net.rim.blackberry.api.pdap.BlackBerryPIMList;

2. 3.

Retrieve a BlackBerryPIM object.


BlackBerryPIM myPIM = (BlackBerryPIM) PIM.getInstance();

Create the contact list.


long listUID = myPIM.createPIMList(PIM.CONTACT_LIST, "test");

4.

The contact list is named using the name that you provide ("test" in the preceding example), unless there is another contact list with that name on the device, in which case a number is appended to the name to make it unique. To reference the contact list later, you should use the list's UID, which is the value that is returned by createPIMList(). Optionally, populate the contact list.
BlackBerryContactList contactList = (BlackBerryContactList) myPIM.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, listUID); Contact contact = contactList.createContact(); String[] name = new String[contactList.stringArraySize(Contact.NAME)]; name[Contact.NAME_GIVEN] = "Noha"; name[Contact.NAME_FAMILY] = "Toma"; contact.addStringArray(Contact.NAME, PIMItem.ATTR_NONE, name); contact.commit();

5.

Close the contact list.


contactList.close();

Code sample
BlackBerryPIM myPIM = (BlackBerryPIM) PIM.getInstance(); try {

// create a contact list long listUID = myPIM.createPIMList(PIM.CONTACT_LIST, "test"); // add a contact to the list BlackBerryContactList contactList = (BlackBerryContactList) myPIM.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, listUID);

84

Development Guide

Creating and removing contact lists

Contact contact = contactList.createContact(); String[] name = new String[contactList.stringArraySize(Contact.NAME)]; name[Contact.NAME_GIVEN] = "Noha"; name[Contact.NAME_FAMILY] = "Toma"; contact.addStringArray(Contact.NAME, PIMItem.ATTR_NONE, name); contact.addString(Contact.TEL, Contact.ATTR_HOME, "519-555-0151"); contact.addString(Contact.TEL, Contact.ATTR_WORK, "519-555-0199"); contact.commit(); // close the contact list contactList.close();

} catch (PIMException e) { System.out.println(e.getMessage()); }

Remove a contact list


You can remove contact lists from a BlackBerry device. Note the following about removing contact lists: You cannot remove contact lists that have service records. You cannot remove the last remaining contact list on a device. You cannot remove the default contact list (which has the UID -1).

A BlackBerryPIMRemovalException is thrown if an error occurs when you try to remove a contact list. 1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import net.rim.blackberry.api.pdap.BlackBerryPIM; import net.rim.blackberry.api.pdap.BlackBerryPIMRemovalException;

2. 3. 4.

Retrieve a BlackBerryPIM object.


BlackBerryPIM myPIM = (BlackBerryPIM) PIM.getInstance();

If you know the name or UID of the contact list that you want to remove, go to step 6. Retrieve the array of contact lists.
String[] lists = myPIM.listPIMLists(PIM.CONTACT_LIST);

5. 6.

The returned array provides the names that are assigned to each contact list. Iterate through the array to search for the contact list that you want to remove. Remove the contact list by invoking BlackBerryPIM.removePIMList(). You can provide either the name or the UID of the contact list. By default, the method removes a contact list only if the list is empty. If you want to remove a contact list that is not empty, you must provide the parameter BlackBerryPIM.REMOVE_NON_EMPTY_LIST.
try {

myPIM.removePIMList(PIM.CONTACT_LIST, "test",

85

Development Guide

Retrieve the contact that is associated with an active call

BlackBerryPIM.REMOVE_NON_EMPTY_LIST);

catch (BlackBerryPIMRemovalException e) { // handle the exception }

Code sample
BlackBerryPIM myPIM = (BlackBerryPIM) PIM.getInstance(); try { myPIM.removePIMList(PIM.CONTACT_LIST, "test", BlackBerryPIM.REMOVE_NON_EMPTY_LIST); } catch (BlackBerryPIMRemovalException e) { System.out.println(e.getMessage()); }

Retrieve the contact that is associated with an active call


1. Import the required classes and interfaces.
import net.rim.blackberry.api.pdap.BlackBerryContact; import net.rim.blackberry.api.phone.*;

2.

Implement a phone listener.


class MyPhoneListener extends AbstractPhoneListener { }

3.

Invoke PhoneCall.getContact() in a callback method in the phone listener (for example, in callIncoming () for a new call). The getContact() method searches all contact lists on the BlackBerry device and returns a BlackBerryContact that is associated with the current phone number, or null if there is no matching contact.
public void callIncoming(int callId) { PhoneCall call = Phone.getCall(callId); BlackBerryContact contact = call.getContact(); }

4.

Use the retrieved contact information.

Code sample
public void callIncoming(int callID) // in a phone listener { StringBuffer strBuffer = new StringBuffer(); 86

Development Guide

Retrieve the contact that is associated with a completed call

PhoneCall call = Phone.getCall(callID); BlackBerryContact contact = call.getContact(); if(contact != null) { if(contact.countValues(BlackBerryContact.ADDR) > 0) { String[] strArray = contact.getStringArray(BlackBerryContact.ADDR, 0); String city = strArray[BlackBerryContact.ADDR_LOCALITY]; if(city != null && city.length() > 0) { strBuffer.append(city); } String country = strArray[BlackBerryContact.ADDR_COUNTRY]; if(country != null && country.length() > 0) { if(city != null && city.length() > 0) { strBuffer.append(", "); } } strBuffer.append(country);

} } // use the contact info, for example, // display it on the incoming phone screen

Related topics Display content on a phone screen, 108

Retrieve the contact that is associated with a completed call


You can retrieve the contact that is associated with a completed call from the call log on a BlackBerry device. 1. Import the required classes and interfaces.
import javax.microedition.pim.Contact; import net.rim.blackberry.api.pdap.BlackBerryContact; import net.rim.blackberry.api.phone.phonelogs.PhoneCallLogID;

2. 3.

Retrieve the caller ID information for a call from the call log.
PhoneCallLogID callLog = new PhoneCallLogID(phoneNum);

Retrieve the associated contact by invoking PhoneCallLogID.getContact(). The getContact() method searches all contact lists on the BlackBerry device for a contact that matches the caller ID information. The method returns null if there is no matching contact.
BlackBerryContact contact = callLog.getContact();

87

Development Guide

Retrieve contacts by phone number

Code sample
String phoneNum = "519-555-0151"; PhoneCallLogID callLog = new PhoneCallLogID(phoneNum); BlackBerryContact contact = callLog.getContact(); if (contact != null) { String[] name = contact.getStringArray(Contact.NAME, 0); add(new RichTextField("The matching contact is " + name[Contact.NAME_GIVEN] + " " + name[Contact.NAME_FAMILY])); } else { add(new RichTextField("There is no matching contact")); }

Retrieve contacts by phone number


You can search all contact lists or a specified contact list on a BlackBerry device for contacts that match a specified phone number. 1. Import the required classes and interfaces.
import import import import import import import import net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.blackberry.api.phone.Phone; java.util.*; javax.microedition.pim.PIM; javax.microedition.pim.PIMException; javax.microedition.pim.PIMItem;

2.

Do one of the following: a. To search all contacts lists, invoke Phone.getContactsByPhoneNumber(), which returns a Vector object that contains the contacts that match the specified phone number. The Vector is empty if there are no matching contacts.
Vector contacts = Phone.getContactsByPhoneNumber(phoneNum);

b.

To search a specified contact list, invoke BlackBerryContactList.itemsByPhoneNumber(), which returns an Enumeration object of all contacts that match the specified phone number. Each of the items in the Enumeration is a PIMItem object, which you can cast to a BlackBerryContactList object.
BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, "test"); Enumeration myEnum = list.itemsByPhoneNumber(phoneNum);

Code sample

88

Development Guide

Linking third-party contacts with contacts in the Contacts application

try {

BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, "test"); Enumeration myEnum = list.itemsByPhoneNumber(phoneNum); while (myEnum.hasMoreElements()) { Object o = myEnum.nextElement(); if (o instanceof BlackBerryContact) { BlackBerryContact c = (BlackBerryContact) o; String[] name = c.getStringArray(Contact.NAME, 0); add(new RichTextField("A matching contact is " + name[Contact.NAME_GIVEN] + " " + name[Contact.NAME_FAMILY]));

} catch (Exception e) { System.out.println(e.getMessage()); }

Linking third-party contacts with contacts in the Contacts application


You can allow BlackBerry device users to link contact data in your application with contacts in the Contacts application on the BlackBerry device by using the Contact Linking API in the net.rim.blackberry.api.pdap.contactlinking package. For example, you can allow users to link a contact in your CRM application with a contact in the Contacts application. A contact in a third-party application can be linked with only one contact in the Contacts application. However, a contact in the Contacts application can be linked with contacts in multiple third-party applications. When a user tries to link a contact in your application with a contact in the Contacts application, you can use the Contact Linking API to perform some tasks automatically, such as searching for a matching contact and checking whether the contact is already linked. You can create menu items that appear in the Contacts application when a user views a contact that is linked with one of your contacts. The menu items can perform any action you want. For example, you can allow a user to add notes in the Contacts application about the contact in your application. You can define the information to display in the Contacts application when the user is viewing a contact that is linked to one of your contacts. The Contact Linking Demo sample application is included in the BlackBerry Java SDK. The application demonstrates how to use the Contact Linking API.

89

Development Guide

Linking third-party contacts with contacts in the Contacts application

Link a contact
You can link a contact in your application with a contact in the Contacts application on the BlackBerry device. You can decide how to interact with the BlackBerry device user when you link a contact. The steps that follow describe one possible approach. Before you begin: Create the contacts in your application by creating and instantiating a class that implements the LinkableContact interface. Define a class that extends LinkedContactInfoProvider and register the class with your application. For more information, see Create an information provider for a linked contact. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.pdap.*; import net.rim.blackberry.api.pdap.contactlinking.*; import javax.microedition.pim.*;

2.

Check to see whether there is a contact in the Contacts application (a BlackBerryContact object) that is a linking candidate for your contact. The LinkedContactUtilities.getContactLinkCandidate() method returns a BlackBerryContact if it finds a contact in the Contacts application that has the same email address or phone number as the LinkableContact that is passed to it. If there is no matching contact, the method returns null.
BlackBerryContact bbContact = LinkedContactUtilities.getContactLinkCandidate(linkableContact);

3. 4.

If a match is found, link your contact with the BlackBerryContact.


bbContact = LinkedContactUtilities.linkContact(bbContact, linkableContact);

If a match is not found, have the user select a contact in the Contacts application to link to the selected contact.
BlackBerryContactList contacts = null; try { contacts = (BlackBerryContactList) PIM.getInstance(). openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); } catch(PIMException e) { ContactLinkingDemo.errorDialog("Couldn't open contacts list."); return; } Object choice = contacts.choose(); if(choice instanceof BlackBerryContact) { bbContact = (BlackBerryContact)choice; }

5.

Check to see whether the selected contact in the Contacts application is already linked to a contact in your application.

90

Development Guide

Linking third-party contacts with contacts in the Contacts application

LinkedContactUtilities.isContactLinked(bbContact, linkableContact.getApplicationID())

6.

If the selected contact in the Contacts application is not already linked, link it to the contact in your application.
bbContact = LinkedContactUtilities.linkContact(bbContact, linkableContact);

Code sample: Linking a contact To see an example of this approach to linking a contact, see linkContact() in the Contact Linking Demo sample application that is included in the BlackBerry Java SDK.

Remove a link
You can remove a link between a contact in your application and a contact in the Contacts application on the BlackBerry device. 1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.pdap.contactlinking.*;

Retrieve the contact in the Contacts application that is linked to your contact.
BlackBerryContact contact = LinkedContactUtilities.getLinkedContact(linkableContact);

3.

Remove the link between the contacts.


LinkedContactUtilities.unlinkContact(contact, linkableContact.getApplicationID());

Code sample: Removing a link


private void unlinkContact(LinkableContact linkableContact) { BlackBerryContact contact = LinkedContactUtilities.getLinkedContact(linkableContact); if(contact != null) { LinkedContactUtilities.unlinkContact(contact, linkableContact.getApplicationID()); } }

Creating menu items for linked contacts


You can create menu items that are available in the Contacts application on the BlackBerry device when a user views a contact that is linked with a contact in your application by invoking LinkedContactUtilities.registerMenuItems(). You must assign menu items to an application group by using the LinkedContactConstants interface.

91

Development Guide

Linking third-party contacts with contacts in the Contacts application

Application group
COMPOSE_SN_MENU_GROUP COMPOSE_IM_MENU_GROUP COMPOSE_OTHER_MENU_GROUP

Description social networking applications instant messaging applications applications that are not social networking applications or instant messaging applications

If a contact in the Contacts application is linked with contacts in multiple third-party applications, the menu items in the Contacts application are grouped with other applications of the same group. Social networking menu items are grouped under the Social Networking menu item. Instant messaging menu items are grouped under the Instant Messaging menu item. Menu items from other types of applications are grouped under the Contact Using menu item.

The menu items from the third-party applications with linked contacts are integrated with the menu for the Contacts application. Situation A group contains one application with linked contacts. The application contains one menu item. A group contains one application with linked contacts. The application contains multiple menu items. A group contains multiple applications with linked contacts. Result The menu item for the application appears in the menu in the Contacts application. The application's name appears in the menu. Selecting the name displays a dialog box that contains a button for each menu item. The group menu item (such as Social Networking) appears in the menu. Selecting the group menu item displays a dialog box with a button for each application with linked contacts in the group.

Create menu items for linked contacts


You can create menu items that are available in the Contacts application on the BlackBerry device when a user views a contact that is linked with a contact in your application. 1. Import the required classes and interfaces.
import import import import net.rim.blackberry.api.menuitem.ApplicationMenuItem; net.rim.blackberry.api.pdap.contactlinking.LinkedContactConstants; net.rim.blackberry.api.pdap.contactlinking.LinkedContactUtilities; net.rim.device.api.system.ApplicationDescriptor;

2. 3.

Create a class that extends the ApplicationMenuItem class.


public class LinkedMenuItem extends ApplicationMenuItem {...}

Create an application descriptor for your application.

92

Development Guide

Linking third-party contacts with contacts in the Contacts application

ApplicationDescriptor appdesc = new ApplicationDescriptor(ApplicationDescriptor.currentApplicationDescriptor(), "Linking Application", null);

4. 5.

Create a variable to store the unique ID of your application.


public static final long APPLICATION_ID = 0x1eredfe71d34760fdL;

Create an array with one or more menu item instances.


ApplicationMenuItem[] items = new ApplicationMenuItem[1]; items[0] = new LinkedMenuItem();

6.

Invoke LinkedContactUtilities.registerMenuItems() to add the menu items for the linked contact to the menu. Pass in the array of menu items, the unique ID of your application, the application group, and the application descriptor.
LinkedContactUtilities.registerMenuItems(items, APPLICATION_ID, LinkedContactConstants.COMPOSE_SN_MENU_GROUP, appdesc);

Code sample: Creating menu items for linked contacts To see an example of creating menu items for linked contacts, see the SampleMenuItem class and main() in the Contact Linking Demo sample application that is included in the BlackBerry Java SDK.

Create an information provider for a linked contact


You can create a class that extends the abstract LinkedContactInfoProvider class to define information about a linked contact. This information appears in the Contacts application on the BlackBerry device when a user views a contact that is linked with a contact in your application. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.pdap.contactlinking.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*;

2.

Create a class that extends LinkedContactInfoProvider.


public class SampleLinkedContactInfoProvider extends LinkedContactInfoProvider { private Image _image; private String _appName; public SampleLinkedContactInfoProvider(Image image, String appName) { _image = image; _appName = appName; }

3.

Implement getAppImage() and return the icon that represents your application. The method must return an image in order for any information to appear for your linked contact when a user views a contact in the Contacts application.

93

Development Guide

Linking third-party contacts with contacts in the Contacts application

public Image getAppImage() { return _image; }

4.

Implement getAppName() and return the name of your application. The method must return a name in order for information about the linked contact to appear when a user edits a contact in the Contacts application.
public String getAppName() { return _appName; }

5.

To indicate which LinkedContactInfoProvider fields (user name, availability, or status) that your application supports, implement isSupported(). By default, a field is not supported. You need to implement isSupported() only if your application supports any of the fields.
public boolean isSupported(int capability) { switch(capability) { case LinkedContactInfoProvider.STATUS: case LinkedContactInfoProvider.AVAILABILITY: case LinkedContactInfoProvider.USER_NAME: return true; default: return false; } }

6.

Implement requestFields() to specify the information to display for the contact in the Contacts application. The method is invoked by the framework when it needs to display information for the linked contact in the Contacts application. Specify the contact's name, status, and current availability, depending on which fields you defined as supported in isSupported().
public void requestFields(String contactID, final LinkedContactCallback callback, int fields) { LinkableContact contact = ContactListScreen.getUserForID(contactID); if((fields & LinkedContactInfoProvider.AVAILABILITY) != 0) { callback.setAvailability(LinkedContactInfoProvider.AVAILABILITY_ONLINE); } if((fields & LinkedContactInfoProvider.STATUS) != 0) { callback.setStatusString("<Sample contact status>"); } if((fields & LinkedContactInfoProvider.USER_NAME) != 0) { callback.setUserName(contact.toString()); }

7.
94

Register the information provider with your application.

Development Guide

Linking third-party contacts with contacts in the Contacts application

LinkedContactUtilities.registerLinkedContactInfoProvider( new SampleLinkedContactInfoProvider(imageBlue, "Demo App 1"), APPLICATION_ID, LinkedContactConstants.COMPOSE_SN_MENU_GROUP);

This example registers the application as a social networking application, using the COMPOSE_SN_MENU_GROUP field in LinkedContactConstants. When a user displays a contact in the Contacts application that is linked to one of your contacts, the information that you defined in your information provider displays on the contact screen. The framework determines the layout of the information. In this example, because the application was defined as a social networking application, the information displays in the Social Networks section of the contact. Code sample: Creating an information provider for a linked contact To see an example of creating an information provider for a linked contact, see the SampleLinkedContactInfoProvider class in the Contact Linking Demo sample application that is included in the BlackBerry Java SDK.

95

Development Guide

Task list

Task list
View or change a task
1. Import the required classes and interfaces.
import import import import import import java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList; net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.TaskArguments;

2.

Create an instance of a ToDoList and store it in an Enumeration.


ToDoList tdl = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE); Enumeration todos = tdl.items();

3. 4.

Create a ToDo object using an element from the Enumeration.


ToDo todo = (ToDo)todos.nextElement();

Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments object created using the ARG_VIEW field and the ToDo object.
Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments(TaskArguments.ARG_VIEW, todo));

Create a new blank task


1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.TaskArguments;

2.

Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments object created using the ARG_NEW field.
Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments( TaskArguments.ARG_NEW));

Create a new populated task


1. Import the required classes and interfaces.
import java.util.Enumeration; import javax.microedition.pim.PIM; import javax.microedition.pim.ToDo;

96

Development Guide

Open a task list

import javax.microedition.pim.ToDoList; import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.TaskArguments;

2.

Create an instance of a ToDoList.


ToDoList tdl = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE);

3.

Invoke createToDo() to create a new ToDo object and add information to the new ToDo object.
ToDo todo = tdl.createToDo(); todo.addString(ToDo.SUMMARY, 0, "Walk the Dog");

4.

Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments object created using the ARG_NEW field and the new ToDo object.
Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments( TaskArguments.ARG_NEW, todo));

Open a task list


1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import javax.microedition.pim.PIMException; import javax.microedition.pim.ToDoList;

2.

Invoke PIM.openPIMList() and provide as parameters the type of list to open (PIM.TODO_LIST) and the access mode with which to open the list (READ_WRITE, READ_ONLY, or WRITE_ONLY).
ToDoList todoList = null; try { todoList = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE); } catch (PimException e) { // handle exception here }

Create a task
1. Import the required classes and interfaces.
import javax.microedition.pim.ToDo; import javax.microedition.pim.ToDoList;

2.

Invoke ToDoList.createToDo()on a task list.


ToDo task = todoList.createToDo();

97

Development Guide

Add task information

Add task information


1. Import the required classes and interfaces.
import import import import java.util.Date; javax.microedition.pim.PIMList; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;

2. 3. 4.

Before you set or retrieve a field, verify that the item supports the field by invoking ToDoList.isSupportedField(int). Invoke PIMList.getFieldDataType(int) to retrieve the field data type. Invoke one of the following methods to set the field data: addString() addDate() addInt() addBoolean() addBinary()
if (todoList.isSupportedField(ToDo.SUMMARY)) { task.addString(ToDo.SUMMARY, ToDo.ATTR_NONE, "Create project plan"); } if (todoList.isSupportedField(ToDo.DUE)) { Date date = new Date(); task.addDate(ToDo.DUE, ToDo.ATTR_NONE, (date + 17280000)); } if (todoList.isSupportedField(ToDo.NOTE)) { task.addString(ToDo.NOTE, ToDo.ATTR_NONE, "Required for meeting"); } if (todoList.isSupportedField(ToDo.PRIORITY)) { task.addInt(Todo.PRIORITY, ToDo.ATTR_NONE, 2); }

Change task information


1. Import the required classes and interfaces.
import javax.microedition.pim.ToDo; import javax.microedition.pim.ToDoList;

2. 3.
98

To replace an existing value with a new value, invoke the appropriate set method, such as ToDo.setString(). To determine if a value is already set for the field, invoke ToDo.countValues().

Development Guide

Save a task

if (task.countValues(ToDo.SUMMARY) > 0) { task.setString(ToDo.SUMMARY, 0, ToDo.ATTR_NONE, "Review notes"); }

4.

Create code to manage a FieldFullException that a method such as addString() throws when a value already exists.

Save a task
1. Import the required classes and interfaces.
import javax.microedition.pim.ToDo; import javax.microedition.pim.ToDoList;

2. 3.

Before you commit your changes, invoke isModified() to determine whether any task fields have changed since the task was last saved. Invoke commit().
if(task.isModified()) { task.commit(); }

Retrieve task information


1. Import the required classes and interfaces.
import import import import java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;

2.

Invoke ToDoList.items() on the task list to retrieve an enumeration.


ToDoList todoList = (ToDoList)PIM.getInstance().openToDoList(PIM.TODO_LIST, PIM.READ_ONLY); Enumeration enum = todoList.items();

3. 4.

Invoke ToDo.getFields() to retrieve an array of IDs for fields that have data for a particular ToDo item. Invoke PIMItem.getString() to retrieve the field values.
while (enum.hasMoreElements()) { ToDo task = (ToDo)enum.nextElement(); int[] fieldIds = task.getFields(); int id; for(int index = 0; index < fieldIds.length; ++index) { id = fieldIds[index]; if(task.getPIMList().getFieldDataType(id) == STRING) { 99

Development Guide

Export a task

for(int j=0; j < task.countValues(id); ++j) { String value = task.getString(id, j); System.out.println(task.getFieldLable(id) + "=" + value); }

Export a task
1. Import the required classes and interfaces.
import import import import import java.io.ByteArrayOutputStream; java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;

2. 3. 4.

Use an output stream writer to export tasks from the BlackBerry device to a supported serial format. To retrieve a string array of supported serial formats, invoke PIM.supportedSerialFormats(), and then specify the list type (PIM.TODO_List). To write an item to a serial format, invoke PIM.getInstance().toSerialFormat. The enc parameter specifies the character encoding to use when writing to the output stream. Supported character encodings include "UTF8," "ISO-8859-1," and "UTF-16BE." This parameter cannot be null.
ToDoList todoList = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_ONLY); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); String[] dataFormats = PIM.getInstance().supportedSerialFormats(PIM.TODO_LIST); Enumeration e = todoList.items(); while (e.hasMoreElements()) { ToDo task = (ToDo)e.nextElement(); PIM.getInstance().toSerialFormat(task, byteStream, "UTF8", dataFormats[0]); }

Import a task
1. Import the required classes and interfaces.
import import import import import java.io.ByteArrayInputStream; javax.microedition.pim.PIM; javax.microedition.pim.PIMItem; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;

2.

Invoke PIM.getInstance().fromSerialFormat() to return an array of PIMItem objects. The enc parameter specifies the character encoding to use when writing to the output stream. Supported character encodings include "UTF8," "ISO-8859-1," and "UTF-16BE." This parameter cannot be null.

100

Development Guide

Delete a task

3.

Invoke ToDoList.importToDo() to create a new task using the PIM items.


String[] dataFormats = PIM.toDoSerialFormats(); // Write task to serial format ByteArrayOutputStream os = new ByteArrayOutputStream(); PIM.getInstance().toSerialFormat(task, os, "UTF8", dataFormats[0]); // Import task from serial format ByteArrayInputStream is = new ByteArrayInputStream(outputStream.toByteArray()); PIMItem[] pi = PIM.getInstance().fromSerialFormat(is, "UTF8"); ToDoList todoList = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE); ToDo task2 = todoList.importToDo((ToDo)pi[0]); task2.commit();

Delete a task
1. Import the required classes and interfaces.
import import import import java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;

2.

Invoke PIM.getInstance to create a ToDoList object.


ToDoList todoList = (ToDoList)PIM.getInstance().openToDoList(PIM.TODO_LIST, PIM.READ_ONLY);

3.

Invoke ToDoList.removeToDo() to delete the task.


todoList.removeToDo(task);

Close the task list


1. Import the required classes and interfaces.
import javax.microedition.pim.PIMException; import javax.microedition.pim.ToDoList;

2. 3.

Invoke ToDoList.close(). Create code that manages exceptions.


try {

todoList.close(); } catch (PIMException e) { // Handle exception }

101

Development Guide

Notify a BlackBerry device application when a list of tasks changes

Notify a BlackBerry device application when a list of tasks changes


1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import net.rim.blackberry.api.pdap.PIMListListener; import net.rim.blackberry.api.pdap.BlackBeryPIMList;

2. 3.

Implement the PIMListListener interface.


class MyTaskListListener implements PIMListListener {...}

Invoke BlackBerryPIMList.addListener() to register to receive notifications of changes to a task list.


BlackBerryPIMList taskList = (BlackBerryPIMList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE); taskList.addListener(new MyTaskListListener());

102

Development Guide

Phone

Phone

10

The net.rim.blackberry.api.phone package contains the APIs that you can use to access the phone application on the BlackBerry device. You can use this package to make calls, switch between available phone lines, receive notification events, and change phone options.

Making a call from a BlackBerry device application


BlackBerry devices can support multiple types of phone lines, including the cellular lines that are provided by a wireless service provider and work lines that are integrated with an organization's PBX phone system. You can create an application that interacts with the phone lines that are available on a device. You can verify the types of phone lines that are available, and use a specific phone line to make an outgoing call.

Make a call from a BlackBerry device application (singleline environment)


1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.Invoke; import net.rim.blackberry.api.invoke.PhoneArguments;

2.

Create an instance of the PhoneArguments class, passing in the ARG_CALL field, and the destination phone number.
PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL, "519-555-0100");

3.

Invoke Invoke.invokeApplication() to open the phone application from your application, providing the APP_TYPE_PHONE field, and the PhoneArguments instance.
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, call);

4.

Check for IllegalArgumentException.

Make a call from a BlackBerry device application (multi-line environment)


1. Import the required classes and interfaces.
import net.rim.blackberry.api.phone.Phone; import net.rim.device.api.system.RadioException;

2.

Invoke initiateCall() to use a specific phone line to make a call. For the destination number, pass in a hardcoded number or user text. In the following code sample, the application makes a call to the destination number 519-555-0100 and uses the line ID that returns at index 0.
Phone.initiateCall(Phone.getLineIds()[0], "519-555-0100");

103

Development Guide

Add DTMF tones to the send queue

Add DTMF tones to the send queue


1. 2. Import the required class.
import net.rim.blackberry.api.phone.PhoneCall;

To add a single DTMF tone to the send queue, invoke PhoneCall.sendDTMFTone().


PhoneCall pc = new PhoneCall(); boolean added = pc.sendDTMFTone('7');

To add multiple DTMF tones to the send queue, invoke PhoneCall.sendDTMFTones().


PhoneCall ph = new PhoneCall(); boolean added = ph.sendDTMFTones("72");

BlackBerry DTMF tones


Key 1 2 3 4 5 6 7 8 9 0 * # Low Tone (Hz) 697 697 697 770 770 770 852 852 852 941 941 941 High Tone (Hz) 1209 1336 1477 1209 1336 1477 1209 1336 1477 1209 1336 1477

Listen for and handle phone events


You can configure your BlackBerry device application to listen for and automatically handle various phone events by implementing the PhoneListener interface. The PhoneListener interface provides a set of callback methods that you can use to receive notification of phone events. 1. 2. 3. Import the required classes and interfaces.
import net.rim.blackberry.api.phone.*;

Create a class that implements the PhoneListener interface. Register the class that implements PhoneListener by invoking addPhoneListener().

104

Development Guide

Listen for and handle multi-line events

Phone.addPhoneListener(this);

4.

5.

Handle incoming phone events by using the PhoneListener callback methods. For example, to receive notification that a call is disconnected, implement the notification in callDisconnected(int); to receive notification that a new call has arrived, implement the notification in callIncoming(int); and to receive notification that a call is waiting, implement the notification in callWaiting(int). For a complete list of PhoneListener callback methods, see the API reference for the BlackBerry Java Development Environment To deregister the PhoneListener, invoke Phone.removePhoneListener().
Phone.removePhoneListener(this);

Listen for and handle multi-line events


For BlackBerry devices that support multiple phone lines, you can configure your application to listen for and automatically handle multi-line phone events by using the MultiLineListener class. The MultiLineListener class is a helper class that implements the PhoneListener interface and provides a set of callback methods that you can use to receive notification of multi-line phone events. 1. Import the required classes.
import net.rim.blackberry.api.phone.Phone; import net.rim.blackberry.api.phone.MultiLineListener;

2. 3. 4.

Create a class that extends MultiLineListener. Register the class as a PhoneListener by invoking Phone.addPhoneListener().
Phone.addPhoneListener(this);

To handle line switching events, perform the following actions: a. Override the MultiLineListener callback methods to notify the application when a line switching event occurs. This is particularly important when using this feature on devices that operate on CDMA networks, as a delay might occur when the application switches between phone lines.
public void setPreferredLineFailure(int lineId) { _screen.popupMessage("switching failed."); } public void setPreferredLineSuccess(int lineId) { _screen.popupMessage("Switching succeeded to " + Phone.getLineNumber(lineId) + " completed." ); }

b.

Invoke Phone.setPreferredLine(), passing in the line ID of the phone line to switch to. In the following code sample, the application selects the line that returns at index 0.
Phone.setPreferredLine( Phone.getLineIds()[0]);

105

Development Guide

Retrieve call information by using call logs

Retrieve call information by using call logs


Call information on a BlackBerry device is recorded in the call logs which can be accessed from the messages list. The call logs are stored in call log folders that you can access by using the PhoneLogs.FOLDER_NORMAL_CALLS or PhoneLogs.FOLDER_MISSED_CALLS constants. 1. 2. 3. Import the required classes.
import net.rim.blackberry.api.phone.phonelogs.*;

Invoke getInstance() to retrieve an instance of the call log.


PhoneLogs _logs = PhoneLogs.getInstance();

Invoke numberOfCalls() to retrieve the total number of calls in a specified call log folder (FOLDER_MISSED_CALLS or FOLDER_NORMAL_CALLS).
int numberOfCalls = _logs.numberOfCalls(PhoneLogs.FOLDER_NORMAL_CALLS);

4.

Invoke PhoneLogs.callAt() to retrieve call information from a call log, passing in the index for the call log, and the call log folder.
PhoneCallLog phoneLog = (PhoneCallLog)_logs.callAt(0,PhoneLogs.FOLDER_NORMAL_CALLS);

5.

Invoke PhoneCallLog.getType() to retrieve the call type. The possible return values are TYPE_MISSED_CALL_OPENED, TYPE_MISSED_CALL_UNOPENED, TYPE_PLACED_CALL, or TYPE_RECEIVED_CALL.
int phoneType = phoneLog.getType();

Retrieve a call participant


You can use the PhoneCallLogID and ConferencePhoneCallLog classes to retrieve a call participant from a the call log. 1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.phone.phonelogs.*;

Invoke PhoneCallLog.getParticipant() or ConferencePhoneCallLog.getParticipantAt() to retrieve the call particpant information.


PhoneCallLogID participant = myPhoneCallLog.getParticipant(); PhoneCallLogID participant = myConferencePhoneCallLog.getParticipantAt(0);

Retrieve call information


1. Import the required class.

106

Development Guide

Retrieve the phone number of a BlackBerry device

import net.rim.blackberry.api.phone.PhoneCall;

2.

Invoke PhoneCall.getElapsedTime() to retrieve the length of time of the current call. Invoke PhoneCall.getStatus() to retrieve the connection status for the call. Invoke PhoneCall.getDisplayPhoneNumber() to retrieve the phone number of the call. In the following code sample, a status message displays on the screen when the phone call has lasted more than 120 seconds.
int threshold = 120; int elapsedTime = call.getElapsedTime(); int status = call.getStatus(); if ((status == PhoneCall.STATUS_CONNECTED || status == PhoneCall.STATUS_CONNECTING) && call.isOutGoing() && elapsedTime > threshold) { String phoneNumber = call.getDisplayPhoneNumber(); Status.show("Your call to " + call.getDisplayPhoneNumber() + " has lasted more than " + (String)threshold + "."); }

Retrieve the phone number of a BlackBerry device


1. 2. 3. Import the required class.
import net.rim.blackberry.api.phone.Phone;

Invoke Phone.getDevicePhoneNumber(), passing in true to return the phone number in its regional format.
String phNumber = Phone.getDevicePhoneNumber(true);

Check for ControlledAccessException to catch instances where your application does not have permission to access the phone number information.

Retrieve a call by call ID


1. Import the required classes.
import net.rim.blackberry.api.phone.Phone; import net.rim.blackberry.api.phone.PhoneCall;

2.

Invoke Phone.getCall(), passing in the call ID of the call to be retrieved.


PhoneCall ph = Phone.getCall(5);

107

Development Guide

Displaying content on a call screen

Displaying content on a call screen


On BlackBerry devices that are running BlackBerry Device Software 5.0 or later, you can customize the incoming call screen and active call screen to display content by using the Phone Screen API that is provided in the net.rim.blackberry.api.phone.phonegui package. For example, you can display information that is provided by your application when a BlackBerry device user receives a call from a specific caller. 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. The Phone Screen sample application that is included in the BlackBerry Java SDK demonstrates how to use this API.

Display content on a phone screen


In the following code sample, custom content is added to the incoming call screen by overriding AbstractPhoneListener.callIncoming(). You can display content on other call screens by overriding callWaiting(), callInitiated(), and callAnswered(). Before you begin: Make sure that the following sample application runs in the background when the BlackBerry device starts. In the BlackBerry Java Plug-in for Eclipse, change the BlackBerry application descriptor for the sample application. For more information, see the BlackBerry Java Plug-in for Eclipse Development Guide. 1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.phone.*; net.rim.blackberry.api.phone.phonegui.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*;

108

Development Guide

Displaying content on a call screen

2.

Create the application framework by extending the Application class. In the constructor, invoke Phone.addPhoneListener() to register the listener that is created in step 3. In main(), invoke enterEventDispatcher() to enable the application to receive events.
public final class MyPhoneScreen extends Application { public MyPhoneScreen() { Phone.addPhoneListener(new MyPhoneScreenContent()); } public static void main(String[] args) { new MyPhoneScreen().enterEventDispatcher(); } }

3.

Create a class that extends the AbstractPhoneListener class. Create a constructor for this new class.
final class MyPhoneScreenContent extends AbstractPhoneListener { public MyPhoneScreenContent() { } }

4.

In the class that extendsAbstractPhoneListener, override AbstractPhoneListener.callIncoming (). Create an instance of the ScreenModel class. Obtain an instance of the incoming call screen by invoking ScreenModel.getPhoneScreen(). Pass in parameters to specify the call screen orientation and type that

you want to obtain. In the following code sample, the portrait orientation of the incoming call screen is obtained. Because devices with touch screens support portrait and landscape orientations, you pass in the parameter PhoneScreen.LANDSCAPE to obtain the landscape orientation of the incoming call screen.
public void callIncoming(int callId) { ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING);

5.

In callIncoming(), create custom content to add to the call screen. In the following code sample, text is added to the incoming call screen by using label fields. Override LabelField.paint() to change the color of the label field.
LabelField labelField1 = new LabelField("Hello") { public void paint(Graphics g) { g.setColor(Color.GREEN); super.paint(g); } }; LabelField labelField2 = new LabelField(" to the World.") {

109

Development Guide

Displaying content on a call screen

};

public void paint(Graphics g) { g.setColor(Color.RED); super.paint(g); }

6.

In callIncoming(), specify the font for the custom content. In the following code sample, the font from the call screen is used. Invoke PhoneScreen.getCallerInfoFont() to obtain the font that is used by the call screen. Invoke Field.setFont() and pass in the call screen font to specify the font for the label fields that were created in step 5. Invoke PhoneScreen.add() to add the label fields to the call screen.
labelField1.setFont(phoneScreenPortrait.getCallerInfoFont()); labelField2.setFont(phoneScreenPortrait.getCallerInfoFont()); phoneScreenPortrait.add(labelField1); phoneScreenPortrait.add(labelField2);

7.

In callIncoming(), invoke ScreenModel.sendAllDataToScreen() to add the custom content to the incoming call screen.
screenModel.sendAllDataToScreen();

Code sample: Displaying content on a phone screen


import import import import import net.rim.blackberry.api.phone.*; net.rim.blackberry.api.phone.phonegui.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*;

public final class MyPhoneScreen extends Application { public MyPhoneScreen() { Phone.addPhoneListener(new MyPhoneScreenContent()); } public static void main(String[] args) { new MyPhoneScreen().enterEventDispatcher(); } } final class MyPhoneScreenContent extends AbstractPhoneListener { public MyPhoneScreenContent() { } public void callIncoming(int callId) { ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING);

110

Development Guide

Displaying content on a call screen

LabelField labelField1 = new LabelField("Hello") { public void paint(Graphics g) { g.setColor(Color.GREEN); super.paint(g); } }; LabelField labelField2 = new LabelField(" to the World.") { public void paint(Graphics g) { g.setColor(Color.RED); super.paint(g); } }; labelField1.setFont(phoneScreenPortrait.getCallerInfoFont()); labelField2.setFont(phoneScreenPortrait.getCallerInfoFont()); phoneScreenPortrait.add(labelField1); phoneScreenPortrait.add(labelField2); } screenModel.sendAllDataToScreen();

Displaying content on devices that operate on a CDMA network


The Phone application on a BlackBerry device displays the active call screen when a user answers a call or makes a call. After the user answers a call, the user can receive and answer a second call. On devices that operate on a CDMA network, the second call does not invoke the same events that the original call does. For these devices, to display custom content on the active call screen, you must override the AbstractPhoneListener.callAnswered() method and AbstractPhoneListener.callWaiting() method. Method
callAnswered()

callWaiting()

Description To display content on the first active call screen, override AbstractPhoneListener.callAnswered() and obtain call screen objects for the active call. The Phone application invokes this method when the user answers the first call. On devices that operate on a GSM network, the Phone application invokes this method when the user answers the first call and second call. To display content on the second active call screen, override AbstractPhoneListener.callWaiting() and obtain call screen objects for the active call. The Phone application invokes this method when the user answers the second call.

111

Development Guide

Displaying content on a call screen

Code sample: Displaying content on devices that operate on a CDMA network The following code sample demonstrates how to override AbstractPhoneListener.callWaiting(). You can check whether the device operates on a CDMA network by using the RadioInfo class. You obtain the instances of the active call screen by invoking ScreenModel.getPhoneScreen() and passing in PhoneScreen.ACTIVE so that you are only specifying content for the second call.
public void callWaiting(int callId) { // For CDMA devices, specify the content for the active call screen if((RadioInfo.getSupportedWAFs() & RadioInfo.WAF_CDMA) != 0) { ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.ACTIVE); PhoneScreen phoneScreenLandscape = screenModel.getPhoneScreen(PhoneScreen.LANDSCAPE, PhoneScreen.ACTIVE);

} }

// For GSM and CDMA devices, specify the content for the incoming call screen

112

Development Guide

BlackBerry Browser

BlackBerry Browser
Retrieve a BlackBerry Browser session
Retrieving the default session overrides any open sessions on the BlackBerry device. 1. 2.

11

Import the net.rim.blackberry.api.browser.Browser class. Retrieve the default BrowserSession object by invoking the static method Browser.getDefaultSession ().

Retrieve a non-default BlackBerry Browser session


1. 2. Import the net.rim.blackberry.api.browser.Browser class. Invoke Browser.getSession(uid), where uid is the browser's service record UID.

Request a web page


1. 2. Import the net.rim.blackberry.api.browser.BrowserSession class. Invoke BrowserSession.displayPage(String url), specifying the URL that contains the web content.

The following sample creates a menu item that displays a web page in the BlackBerry Browser.
private MenuItem browserItem = new MenuItem(_resources.getString(MENUITEM_BROWSER), 110, 12) { public void run() { BrowserSession visit = Browser.getDefaultSession(); visit.displayPage("http://www.blackberry.com"); } };

Enhanced support for web content in BlackBerry device applications


In BlackBerry Java Development Environment 5.0, the net.rim.device.api.browser.field2 package provides a new set of APIs you can use to embed web content in BlackBerry device applications. In earlier versions of the BlackBerry JDE, the net.rim.device.api.browser.field package provided functionality to add web content to a BlackBerry device application. For more information about using this browser field, see the BrowserFieldDemo sample application that is provided with the BlackBerry JDE. The APIs that are new in BlackBerry JDE 5.0 allow you to perform the following actions:

113

Development Guide

Enhanced support for web content in BlackBerry device applications

load and configure the display settings for web content in Field objects in any application access the DOM for loaded web content control the HTTP handling for connections, SSL, cookies, and caching set callback listeners to monitor the loading progress of web pages

You can create applications that include Java objects and methods that can access and invoke JavaScript code and be accessed and invoked by JavaScript code by using the APIs in the net.rim.device.api.script package, which is new in BlackBerry JDE 5.0.

Display HTML content in a browser field


1. Import the required classes and interfaces.
import net.rim.device.api.browser.field2.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.container.*;

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 BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }

3.

Create the custom screen by extending the MainScreen class.


class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }

4. 5.

In the screen constructor, create an instance of the BrowserField class.


BrowserField myBrowserField = new BrowserField();

In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(myBrowserField);

114

Development Guide

Enhanced support for web content in BlackBerry device applications

6.

In the screen constructor, invoke BrowserField.displayContent() to specify and display the HTML content.
myBrowserField.displayContent("<html><body><h1>Hell o World!</h1></body></html>", "http://localhost");

Display HTML content from a web page in a browser field


1. Import the required classes and interfaces.
import import import import net.rim.device.api.browser.field2.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*;

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 BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }

3.

Create the framework for the custom screen by extending the MainScreen class.
class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }

4. 5. 6.

In the screen constructor, create an instance of the BrowserField class.


BrowserField myBrowserField = new BrowserField();

In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(myBrowserField);

In the screen constructor, invoke BrowserField.requestContent() to specify the location of the HTML content and display it.

115

Development Guide

Enhanced support for web content in BlackBerry device applications

myBrowserField.requestContent("http://www.blackberry.com");

Display HTML content from a resource in your application


1. Import the required classes and interfaces.
import import import import net.rim.device.api.browser.field2.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*;

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 BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }

3.

Create the custom screen by extending the MainScreen class.


class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }

4. 5. 6.

In the screen constructor, create an instance of the BrowserField class.


BrowserField myBrowserField = new BrowserField();

In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(myBrowserField);

In the screen constructor, invoke BrowserField.requestContent() to specify the location of the resource in your application and display the HTML content.
myBrowserField.requestContent("local:///test.html");

Note: The BrowserField class does not access resources using a folder structure. The BrowserField class displays the first resource found that matches the specifed file name.

116

Development Guide

Enhanced support for web content in BlackBerry device applications

Configure a browser field


1. Import the required classes and interfaces.
import net.rim.device.api.browser.field2.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.container.*;

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 BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }

3.

Create the framework for the custom screen by extending the MainScreen class.
class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }

4. 5.

In the screen constructor, create an instance of the BrowserFieldConfig class.


BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();

In the screen constructor, invoke BrowserFieldConfig.setProperty() to specify a property of the BrowserField. The first parameter in setProperty() specifies the property, and the second parameter specifies the value of the property. For example, the following code sample specifies the NAVIGATION_MODE property of a BrowserField object:
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);

6.

In the screen constructor, create an instance of the BrowserField class that uses the configuration that you defined.
BrowserField browserField = new BrowserField(myBrowserFieldConfig);

117

Development Guide

Enhanced support for web content in BlackBerry device applications

Send form data to a web address in a browser field


1. Import the required classes and interfaces.
import import import import import import import net.rim.device.api.browser.field2.*; net.rim.device.api.io.http.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.container.*; java.lang.*; 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 BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }

3.

Create the custom screen by extending the MainScreen class.


class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }

4. 5. 6.

In the screen constructor, create an instance of the BrowserField class.


BrowserField browserField = new BrowserField();

In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(browserField);

In the screen constructor, create a String object that contains the base web address of the web page that you are sending the form data to.
String baseURL = "http://www.blackberry.com";

7.

In the screen constructor, create a String that specifies the form data that your application sends to the web page.

118

Development Guide

Enhanced support for web content in BlackBerry device applications

String postData = "fieldname1=value1&fieldname2=value2";

8. 9.

In the screen constructor, create a Hashtable object to store the header information for the form data.
Hashtable header = new Hashtable();

In the screen constructor, invoke Hashtable.put() to specify the header information for the form data.
header.put("Content-Length", "" + postData.length()); header.put("Content-Type", "application/x-www-form-urlencoded");

10. In the screen constructor, invoke BrowserField.requestContent() to send the form data to the web page and display the web page.
browserField.requestContent(baseURL, postData.getBytes(), new HttpHeaders(header));

119

Development Guide

Menu items

Menu items
Adding menu items to BlackBerry Device Software applications

12

The Application Menu Item API, in the net.rim.blackberry.api.menuitem package, lets you define menu items to display in BlackBerry Device Software applications. The ApplicationMenuItemRepository class lets you add or remove menu items from BlackBerry Device Software applications.

Create and register a menu item


Extend the ApplicationMenuItem class to define a menu item to display in BlackBerry Device Software applications. 1. Import the required classes and interfaces.
import java.lang.IllegalStateException; import net.rim.blackberry.api.menuitem.ApplicationMenuItem; import net.rim.blackberry.api.menuitem.ApplicationMenuItemRepository;

2.

To create and register a menu item, perform the following tasks: Task Define a menu item Steps Extend the ApplicationMenuItem class.
public class SampleMenuItem extends ApplicationMenuItem { ... }

Specify the position of the menu item in the menu

Construct the ApplicationMenuItem. A higher number in the constructor means that the menu item appears lower in the menu.
SampleMenuItem() { super(0x350100); }

Specify the menu item text

Implement toString().
public String toString() { return "My menu item"; }

Specify the behavior of the menu item

Implement run().

120

Development Guide

Create and register a menu item

Task

Steps
public Object run(Object context) { // the menu's action here return null; }

Register the menu item

Invoke ApplicationMenuItemRepository.addMenuItem().
ApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance(); amir.addMenuItem( ApplicationMenuItemRepository.MENUITEM_PHONE, mySampleMenuItem);

Code sample: Creating and registering a menu item


// Create menu item int placement = 0x350100; ApplicationMenuItem ami = new ApplicationMenuItem(placement) { public Object run(Object context) { // do something return null; } public String toString() { return "My menu item"; }

};

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

For more information, see the Application Integration category overview in the API reference for the BlackBerry Java Development Environment.

121

Development Guide

Find more information

Find more information


13

www.blackberry.com/go/apiref: View the latest version of the API reference for the BlackBerry Java SDK. www.blackberry.com/go/devguides: Find development guides, release notes, and sample application overviews for the BlackBerry Java SDK. www.blackberry.com/go/uiguidelines: Find the UI guidelines for BlackBerry smartphones. www.blackberry.com/developers: Visit the BlackBerry Developer Zone for resources about developing BlackBerry device applications. www.blackberry.com/go/developerkb: View knowledge base articles in the BlackBerry Development Knowledge Base. www.blackberry.com/developers/downloads: Find the latest development tools and downloads for developing BlackBerry device applications.

122

Development Guide

Glossary

Glossary
API application programming interface BCC blind carbon copy CC carbon copy CRM customer relationship management DTMF Dual Tone Multiple-frequency JSR Java Specification Request MIME Multipurpose Internet Mail Extensions MEID Mobile Equipment Identifier MMS Multimedia Messaging Service PIM personal information management PIN personal identification number SMS Short Message Service SVG Scalable Vector Graphics UCS Universal Content Stream

14

123

Development Guide

Glossary

UID unique identifier UTF UCS Transformation Format

124

Development Guide

Provide feedback

Provide feedback
To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.

15

125

Development Guide

Document revision history

Document revision history


Date 24 September 2010 Description Changed the following topics:

16

10 September 2010

Create a custom folder in the message list Create an icon for a custom message Create a custom indicator Create a module for background processes Creating a module for background processes Creating a module for the UI Send a notification when a custom folder changes Start the module for background processes or the module for the UI Using custom messages and folders in the message list Added the following topics: Check for a sensor on the device Check the state of a sensor Cradle detection Cradle handling Create a custom folder in the message list Create an icon for a custom message Create a custom indicator Create a module for background processes Creating a module for background processes Creating a module for the UI Custom messages Device Capability API Hide an indicator Notify an application when the state of a sensor changes Remove a custom indicator Send a notification when a custom folder changes Start the module for background processes or the module for the UI Using custom messages and folders in the message list Working with sensors on a device

Added the following code sample: 16 August 2010 Code sample: Working with a sensor Added the following topic:

126

Development Guide

Document revision history

Date

Description Create an information provider for a linked contact Changed the following topics: Linking third-party contacts with contacts in the Contacts application Link a contact

Removed the following topic: 3 August 2010 Create a custom field for linked contacts Added the following topics: Configure and start a search Create a contact list Creating and removing contact lists Customizing the appearance of your data in search results Define an EntityBasedSearchable class for your SearchableEntity objects Displaying content on devices that operate on a CDMA network Encapsulate your data in the SearchableEntity class Ensure that a device runs a single instance of your application Exposing your application data Inserting data when a device starts Listening for responses from the Unified Search Service Making data findable Notify the Unified Search Service about changes to your data Passing queries to other search engines Process search results Register your EntityBasedSearchable object with the Unified Search Service Remove a calendar entry with no notification Remove a contact list Removing your data from the content repository Retrieve contacts by phone number Retrieve the contact that is associated with a completed call Retrieve the contact that is associated with an active call Searching Specify an icon in the EntityBasedSearchable or SearchableEntity class Unified search Update a calendar entry with no notification

127

Development Guide

Document revision history

Date

Description Using other search engines Added the following code samples: Code sample: Displaying content on a phone screen

Changed the following topics: Displaying content on a call screen Display content on a phone screen

128

Development Guide

Legal notice

Legal notice

17

2011 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. Eclipse is a trademark of Eclipse Foundation, Inc. Google and YouTube are trademarks of Google Inc. Java and JavaScript are trademarks of Oracle America, Inc. iCal is a trademark of Apple Inc. vCard is a trademark of the Internet Mail Consortium. 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.

129

Development Guide

Legal notice

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

130

Development Guide

Legal notice

Certain features outlined in this documentation require a minimum version of BlackBerry Enterprise Server, BlackBerry Desktop Software, and/or BlackBerry Device Software. The terms of use of any 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

131

You might also like