133
BlackBerry Java SDK Integration Version: 6.0 Development Guide

Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Embed Size (px)

Citation preview

Page 1: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

BlackBerry Java SDKIntegrationVersion: 6.0

Development Guide

Page 2: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Page 3: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Contents1 Integrating with BlackBerry Device Software applications............................................................................... 6

Invoke a BlackBerry Device Software application............................................................................................. 6

2 Unified search................................................................................................................................................... 7Making data findable........................................................................................................................................ 7

Exposing your application data.................................................................................................................. 7Passing queries to other search engines................................................................................................... 9

Define an EntityBasedSearchable class for your SearchableEntity objects...................................................... 10Customizing the appearance of your data in search results...................................................................... 12Specify an icon in the EntityBasedSearchable or SearchableEntity class.................................................. 13

Encapsulate your data in the SearchableEntity class........................................................................................ 13Register your EntityBasedSearchable object with the Unified Search Service................................................. 15Notify the Unified Search Service about changes to your data........................................................................ 16Listening for responses from the Unified Search Service................................................................................. 16Removing your data from the content repository............................................................................................ 17Using other search engines............................................................................................................................... 18Ensure that a device runs a single instance of your application....................................................................... 20Inserting data when a device starts.................................................................................................................. 22Searching.......................................................................................................................................................... 22

Configure and start a search...................................................................................................................... 22Process search results................................................................................................................................ 23

3 Device interaction support............................................................................................................................... 25Device Capability API........................................................................................................................................ 25Cradle detection............................................................................................................................................... 25Cradle handling................................................................................................................................................. 27Working with sensors on a device.................................................................................................................... 28

Check for a sensor on the device............................................................................................................... 28Check the state of a sensor....................................................................................................................... 29Notify an application when the state of a sensor changes........................................................................ 30Code sample: Working with a sensor........................................................................................................ 31

4 Message list...................................................................................................................................................... 34Create a new blank SMS text message............................................................................................................. 34Create a new populated text message............................................................................................................. 34Create a new blank MMS message................................................................................................................... 34Create a new blank email message................................................................................................................... 35Create a new populated email message........................................................................................................... 35

Page 4: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Create a new blank PIN message...................................................................................................................... 35Create a new populated PIN message.............................................................................................................. 36Receive a message notification......................................................................................................................... 36Add a listener to the message store................................................................................................................. 37Add a listener to the message store for batch updates.................................................................................... 37Add a listener to a folder.................................................................................................................................. 38Retrieve the total count of unread email messages in all folders in the store................................................. 38Open a message................................................................................................................................................ 38Retrieving the body of an email message......................................................................................................... 39

Retrieve the plain text and HTML content in the body of an email message using a recursive method................................................................................................................................................................... 40Retrieve the plain text content of an email message................................................................................ 42Retrieve the HTML content of an email message...................................................................................... 43

Notify a BlackBerry device application that an email message is about to be sent.......................................... 46Notify a BlackBerry device application that an MMS message is about to be sent.......................................... 46Notify a BlackBerry device application that an SMS message is about to be sent........................................... 47Send a message................................................................................................................................................ 47Reply to a message........................................................................................................................................... 49Forward a message........................................................................................................................................... 50Work with message folders.............................................................................................................................. 51

5 Custom messages............................................................................................................................................. 53Using custom messages and folders in the message list.................................................................................. 53Creating a module for background processes.................................................................................................. 53Creating a module for the UI............................................................................................................................ 53Create a module for background processes..................................................................................................... 53Start the module for background processes or the module for the UI............................................................. 54Create an icon for a custom message............................................................................................................... 55Create a custom folder in the message list....................................................................................................... 56Send a notification when a custom folder changes.......................................................................................... 57Create a custom indicator................................................................................................................................. 58Hide an indicator............................................................................................................................................... 58Remove a custom indicator.............................................................................................................................. 59

6 Attachments..................................................................................................................................................... 60Create an attachment handler.......................................................................................................................... 60Retrieve the contents of an attachment........................................................................................................... 61Retrieve information about an attachment...................................................................................................... 61Send a message with an attachment................................................................................................................ 61

Page 5: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Download attachments automatically.............................................................................................................. 62

7 Calendar............................................................................................................................................................ 64Open the calendar............................................................................................................................................ 64View or change a calendar entry...................................................................................................................... 64Open a new populated calendar entry............................................................................................................. 64Update calendar entry information.................................................................................................................. 65Retrieve calendar entry information................................................................................................................ 67Export a calendar entry.................................................................................................................................... 68Import a calendar entry.................................................................................................................................... 69Retrieve multiple lists of calendar entries........................................................................................................ 69Notify a BlackBerry device application when a list of calendar entries changes.............................................. 70Notify a BlackBerry device application when the default list of calendar entries changes.............................. 70Update a calendar entry with no notification................................................................................................... 71Remove a calendar entry with no notification................................................................................................. 72

8 Contact list........................................................................................................................................................ 74Multiple contact lists support........................................................................................................................... 74Open the contacts application.......................................................................................................................... 74Open the contacts application by using contact data....................................................................................... 75Open the contacts application with a specific contact list............................................................................... 75Create a contact and assign it to a contact list................................................................................................. 77Retrieve contact information............................................................................................................................ 78Retrieve a contact list UID................................................................................................................................ 79Export a contact................................................................................................................................................ 79Import a contact............................................................................................................................................... 80Delete a contact................................................................................................................................................ 81Notify an application when a contact list changes........................................................................................... 82Creating and removing contact lists................................................................................................................. 83

Create a contact list................................................................................................................................... 83Remove a contact list................................................................................................................................ 85

Retrieve the contact that is associated with an active call............................................................................... 86Retrieve the contact that is associated with a completed call......................................................................... 87Retrieve contacts by phone number................................................................................................................ 88Linking third-party contacts with contacts in the Contacts application........................................................... 89

Link a contact............................................................................................................................................. 90Remove a link............................................................................................................................................ 91Creating menu items for linked contacts................................................................................................... 91Create menu items for linked contacts..................................................................................................... 92

Page 6: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Create an information provider for a linked contact................................................................................. 93

9 Task list............................................................................................................................................................. 96View or change a task....................................................................................................................................... 96Create a new blank task.................................................................................................................................... 96Create a new populated task............................................................................................................................ 96Open a task list................................................................................................................................................. 97Create a task..................................................................................................................................................... 97Add task information........................................................................................................................................ 98Change task information................................................................................................................................... 98Save a task........................................................................................................................................................ 99Retrieve task information................................................................................................................................. 99Export a task..................................................................................................................................................... 100Import a task..................................................................................................................................................... 100Delete a task..................................................................................................................................................... 101Close the task list.............................................................................................................................................. 101Notify a BlackBerry device application when a list of tasks changes................................................................ 102

10 Phone................................................................................................................................................................ 103Making a call from a BlackBerry device application......................................................................................... 103Make a call from a BlackBerry device application (single-line environment)................................................... 103Make a call from a BlackBerry device application (multi-line environment).................................................... 103Add DTMF tones to the send queue................................................................................................................. 104BlackBerry DTMF tones..................................................................................................................................... 104Listen for and handle phone events................................................................................................................. 104Listen for and handle multi-line events............................................................................................................ 105Retrieve call information by using call logs....................................................................................................... 106Retrieve a call participant................................................................................................................................. 106Retrieve call information.................................................................................................................................. 106Retrieve the phone number of a BlackBerry device......................................................................................... 107Retrieve a call by call ID.................................................................................................................................... 107Displaying content on a call screen................................................................................................................... 108

Display content on a phone screen........................................................................................................... 108Code sample: Displaying content on a phone screen................................................................................ 110Displaying content on devices that operate on a CDMA network............................................................. 111

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

Page 7: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Request a web page.......................................................................................................................................... 113Enhanced support for web content in BlackBerry device applications............................................................ 113

Display HTML content in a browser field................................................................................................... 114Display HTML content from a web page in a browser field....................................................................... 115Display HTML content from a resource in your application...................................................................... 116Configure a browser field.......................................................................................................................... 117Send form data to a web address in a browser field................................................................................. 118

12 Menu items....................................................................................................................................................... 120Adding menu items to BlackBerry Device Software applications..................................................................... 120Create 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

Page 8: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Integrating with BlackBerry Device Softwareapplications

1

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 theApplication Integration category overview in the API reference for the BlackBerry® Java® Development Environment.

Invoke a BlackBerry Device Software applicationYou can create BlackBerry® device applications that invoke BlackBerry Device Software applications such as themessages application, the phone application, and the media application. When your application invokes a BlackBerryDevice Software application, the application can make the BlackBerry Device Software application perform an actionor display information.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.invoke.CalendarArguments;import net.rim.blackberry.api.invoke.Invoke;import net.rim.blackberry.api.invoke.MapsArguments;import net.rim.blackberry.api.invoke.MessageArguments;import 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 aMessageArguments 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() andprovide 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 referencefor the BlackBerry® Java® Development Environment.

Development Guide Integrating with BlackBerry Device Software applications

6

Page 9: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Unified search 2The 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 byclicking the search icon on the Home screen. Developers can use Unified Search Service through the Unified SearchAPI. You can use the API to include your application data in the Service's content repository, and search the contentindex from your application.

For example, imagine that you have a large collection of books and you loan them to people frequently. It might beuseful to create an application that allows you to catalog your books, and keep a list of people to whom you loanthem. If this application used the Unified Search API, you could search for a book from the Home screen, or anyapplication, 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 aBlackBerry device, other applications on the device, or your application only. In addition, you can search data fromother applications when that data is registered in the Unified Search Service.

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

Exposing your application dataThe Unified Search Service maintains an index of content on a BlackBerry® device. Your application uses theSearchRegistry, AppContentManager, and AppContentListener classes to communicate with the UnifiedSearch Service. To make the data in your application findable, you need to complete five tasks.

Task Description

Define anEntityBasedSearchable classfor your SearchableEntityobjects.

An EntityBasedSearchable object represents your searchable data tothe Unified Search Service. When you register yourEntityBasedSearchable, the Service requests that your applicationprepare data for submission by calling EntityBasedSearchable.load(). When your application data is ready for submission, you should invokecompleted() on the NotificationListener parameter passed toload().

Encapsulate your data in aSearchableEntity object.

A SearchableEntity object is the smallest unit of data that an applicationcan submit to the Unified Search Service. YourEntityBasedSearchable object sends your SearchableEntityobjects to the Service when asked. You need to encapsulate your application

Development Guide Unified search

7

Page 10: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Task Description

data in a SearchableEntity object. The Service indexes the metadatathat is exposed by these objects for consideration during search operations.Also, SearchableEntity objects are returned in search results from theService.

The Unified Search Service may need interrupt your load operation if theBlackBerry device is busy, or has a low battery power level. If an interruptionis necessary, the Service invokes EntityBasedSearchable.pause().When the Service detects that your operation can continue, it invokesEntityBasedSearchable.resume(). Respond to these events in atimely manner so that your application does not cause disruption to otherapplications on the device.

After you notify the Unified Search Service that your data is ready, it callsEntityBasedSearchable.getSearchableEntities() to index yourdata. The Service may invoke load() and getSearchableEntities()again if it detects that its content index and your data are not synchronized.

Register yourEntityBasedSearchable objectwith the Unified Search Service.

After you prepare your data for search, and define how it will be indexed,you must register your EntityBasedSearchable with the Unified SearchService. Pass your EntityBasedSearchable when you invokeSearchRegistry.register(). The Service then retrieves and indexesyour data for inclusion in search results.

Notify the Unified Search Serviceabout changes to your data.

To notify the content index about changes to your application data, use theinsert(), delete(), and update() methods in theAppContentManager object.

Listening for responses from theUnified Search Service.

When you notify the Unified Search Service about changes to yourapplication data, you should provide an AppContentListener objectwhere the Service can notify your application about the result of yourrequest.

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

Development Guide Making data findable

8

Page 11: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Passing queries to other search enginesYou can use the ExternalSearchProvider interface to pass queries to another search engine. For example, anapplication on a BlackBerry® device that has an efficient way to search its own data could give users and otherapplications access to its data by implementing the ExternalSearchProvider. Alternatively, an insurancecompany may have an application that allows sales representatives to search an insurance policy database. Thecompany could provide its sales representatives with access to the policy search engine behind the firewall, from aBlackBerry device, by implementing theExternalSearchProvider.

Users can extend a search in two ways. The Universal search feature from the Home screen lists external searchproviders at the end of the search result list. If a user clicks the icon for your application in the search result, theUnified Search Service invokes search() from your ExternalSearchProvider object. Your application is thenresponsible for creating a connection to the search provider (another application, or over a network), passing thequery string, and displaying any results that you retrieve.

Other applications can invoke your application in a similar way. TheUnifiedSearchServices.getSearchProviders() method returns a list of all external search providers thatinstalled on a BlackBerry device. In this way, an application can find and use your ExternalSearchProviderspecifically, 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 yourExternalSearchProvider with the Unified Search Service. Pass your ExternalSearchProvider object whenyou invoke SearchRegistry.register().

The following diagram shows the relationship between some of the components that required to implementExternalSearchProvider.

Development Guide Making data findable

9

Page 12: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Define an EntityBasedSearchable class for yourSearchableEntity objectsYour implementation of the EntityBasedSearchable interface manages the relationship between the UnifiedSearch Service and the searchable entities that you create. Each EntityBasedSearchable object manages a groupof 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 MySearchableEntity[] _myEntities; // You will need this in steps 8 and 11private long _registrationID;private SearchField[] _searchFields;private Image _icon;private final Object _monitor = new Object();private boolean _wait = false;

3. In the constructor, create an array of SearchField objects. Each SearchField stores the name of onesearchable property of your data. In the following code sample, the application data objects that are managedby this class have three searchable properties. For example, if your application data modeled books, these fieldsmight 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.

Development Guide Define an EntityBasedSearchable class for your SearchableEntity objects

10

Page 13: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

5. Create an icon to appear in search results that include searchable entities managed by thisEntityBasedSearchable. For more information about creating icons, see "Customizing the appearance ofyour data in search results."

6. Implement getType(). Return the content type that best matches your application data. For a list of validcontent types, see thenet.rim.device.api.unifiedsearch.searchables.SearchableContentTypeConstants interfacein 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 informationabout exposing your data to searches, seenet.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 pausethe 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 thatpopulates your arrray of searchable entities and notify the Service.

if (_wait){ try { synchronized(_monitor) {

Development Guide Define an EntityBasedSearchable class for your SearchableEntity objects

11

Page 14: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

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

The Unified Search Service invokes getSearchableEntities() next to retrieve the array you populated.

9. In pause(), change the value of the _wait variable to true. The Unified Search Service calls this method whenit 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 canresume execution. The Unified Search Service invokes resume() when it wants your application to resumeloading 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 resultsThe getIcon() method, in the EntityBasedSearchable and SearchableEntity interfaces, specifies the iconthat appears in search results. In the Universal search feature on the Home screen, search results are grouped byapplication. The EntityBasedSearchable.getIcon() method specifies the icon that appears for the group.

Development Guide Define an EntityBasedSearchable class for your SearchableEntity objects

12

Page 15: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Specify an icon in the EntityBasedSearchable or SearchableEntity classBefore you begin: Include a suitable graphic file for use as an icon in your project's resource folder. For moreinformation 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. Create an instance variable to store the icon.

private Image _icon;

3. Import the graphic into your application from your resource folder.

Bitmap img = Bitmap.getBitmapResource("icon.png")

4. 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 classThe Unified Search Service indexes the metadata that is exposed by a SearchableEntity object. The Service alsoreturns a SearchableEntity as the content of a search result. You must prepare your application data for theService by encapsulating it in your SearchableEntity class.

1. Import the required classes and interfaces.

Development Guide Encapsulate your data in the SearchableEntity class

13

Page 16: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

2. Retrieve an array of SearchField objects from your EntityBasedSearchable.

SearchField[] searchfields = mySearchable.defineSupportedSearchFields();

3. 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.lengthSearchFieldCriteria[] 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 wouldreturn 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 withthe 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 searchresults. Continuing with the book example, myObject.getDescription() could return a description of thebook.

public String getSummary() { return myObject.getDescription();}

Development Guide Encapsulate your data in the SearchableEntity class

14

Page 17: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

9. Implement getSearchable(). Retrieve the EntityBasedSearchable that your application creates tomanage 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 entityin 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 ingetIcon(). For more information, see "Customize the appearance of your data in search results".

Register your EntityBasedSearchable object with theUnified Search ServiceAfter you have defined your SearchableEntity class, and created an EntityBasedSearchable class torepresent your searchable entities to the Unified Search Service, use the SearchRegistry to register them withthe 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. Register your EntityBasedSearchable with the Unified Search Service.

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

4. 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. Youshould store your registration token and reuse it when you update content using the AppContentManager class.

Development Guide Register your EntityBasedSearchable object with the Unified Search Service

15

Page 18: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Notify the Unified Search Service about changes to yourdataWhen your application changes, deletes, or creates new searchable data, you can notify the Unified Search Serviceabout the changes by using the AppContentManager object.

Before you begin: Retrieve a registration token to communicate with the Unified Search Service. An applicationretrieves 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. Import the required classes and interfaces.

import net.rim.device.api.unifiedsearch.content.AppContentManager;

2. To update a SearchableEntity object that the Unified Search Service has already indexed, invokeupdateContent().

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 ServiceWhen you manipulate content with AppContentManager methods, you should specify class that implements theAppContentListener interface. After the Unified Search Service has processed your request, it notifies theAppContentListener 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.

Development Guide Notify the Unified Search Service about changes to your data

16

Page 19: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 repositoryDepending on your application life cycle, you might need to remove all of your application data from the UnifiedSearch Service content repository. For example, a BlackBerry® device user may have multiple accounts for yourapplication. It may make sense for the application data to appear in search results only if the user is currentlyauthenticated by your application. Alternatively, your application may need to respond to locale changes. In thiscase, you should remove data from the content repository, then repopulate it with the data that is appropriate tothe current locale.

The following table describes two approaches to remove all of your application data from the Unified Search Servicecontent repository.

Approach Description

Deregister anEntityBasedSearchable object.

This approach removes your EntityBasedSearchable object, and alldata associated with it, from the Unified Search Service content index. YourEntityBasedSearchable no longer appears in the list of registeredsearchable data sources on the BlackBerry device.

To deregister an EntityBasedSearchable, invokeSearchRegistry.deregister(), and pass the registration tokenreturned when that EntityBasedSearchable was registered.

Remove all data from the contentrepository for anEntityBasedSearchable object.

This approach removes all of your application data from the repository. Youcan use this approach when you need to remove all data, but you expectthat you will continue to populate the repository with new data in the nearfuture.

Development Guide Removing your data from the content repository

17

Page 20: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Approach Description

To remove all data from the content repository for anEntityBasedSearchable, invokeUnifiedSearchServices.removeAllData() and pass the registrationtoken that was returned when that EntityBasedSearchable wasregistered.

Using other search enginesThe 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 Universalsearch 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 thatExternalSearchProvider. The search provider is responsible for creating a network connection or interprocesscommunication connection, invoking a search on the remote server, retrieving the results, and displaying them tothe user. If your application uses a remote search engine, you can consider inserting the search results in the UnifiedSearch 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 accessexternal search providers. The UnifiedSearchServices.getSearchProviders() method returns a list ofregistered ExternalSearchProvider objects where an application can send a search.

Similar to EntityBasedSearchable objects, an ExternalSearchProvider must be registered with the UnifiedSearch Service by using the SearchRegistry object. For more information, see "Register yourEntityBasedSearchable 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

Development Guide Using other search engines

18

Page 21: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Using other search engines

19

Page 22: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Ensure that a device runs a single instance of yourapplicationTo improve the efficiency of your application, you should make sure that the BlackBerry® device runs only one instancewhen search() is invoked in your ExternalSearchProvider implementation.

1. In your implementation of ExternalSearchProvider, import packages to help you discover whichapplications are running on the device.

import net.rim.device.api.system.ApplicationDescriptor;import net.rim.device.api.system.ApplicationManager;import net.rim.device.api.system.ApplicationManagerException;import 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 yourapplication a message that it should display a screen with the results for the new keywords. You need to detecta 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 representsyour application.

ApplicationDescriptor[] myAppDes = CodeModuleManager.getApplicationDescriptors(modHandle);

7. Start your application. Pass the search keywords as an argument. In your application's constructor, you need todetect whether there is an argument that contains search keywords.

try { ApplicationManager.getApplicationManager().runApplication(new ApplicationDescriptor(myAppDes[0], new String[]{keywords})); } catch(ApplicationManagerException e)

Development Guide Ensure that a device runs a single instance of your application

20

Page 23: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

{ // Process the error condition } }}

8. In your application class, import the net.rim.device.api.system.GlobalEventListener package tolisten 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 yourfirst 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 thatare 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(); }}

Development Guide Ensure that a device runs a single instance of your application

21

Page 24: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

SearchingYou 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 searchableentities that matched your search criteria. The Service returns the data organized by searchable data source andsearch 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 searchThis 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 aseparate 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 youretrieve a list of searchable applications on the device, change the SearchableContentTypeConstants valueto one that is appropriate for your search. Make sure you take some kind of action if yourEntityBasedSearchable 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);

Development Guide Inserting data when a device starts

22

Page 25: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

}}// 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 specifiesthe search keywords that the BlackBerry® device user provides. This method invokes a new thread, so declarethe 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 resultsThe SearchResponse object that you receive from the Unified Search Service structures your search results by theEntityBasedSearchable and search fields that matched your keywords. To access the data, you need to parsethis object.

Before you begin: Ensure that UnifiedSearchServices.search() returned a SearchResponse object withdata. Pass the SearchResponse to parseResponse().

1. Import the required classes and interfaces.

import net.rim.device.api.unifiedsearch.entity.*;import net.rim.device.api.util.Arrays;import net.rim.device.api.system.Application;import java.util.*;

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

Development Guide Searching

23

Page 26: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

MySearchableEntity[] _myEntities;

3. Implement parseResponse. This method runs after your search thread terminates, so declare theSearchResponse 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 foryour EntityBasedSearchable.

final Hashtable results = searchResult.getSearchResult(_searchable);

6. Retrieve an Enumeration object that contains the values in the Hashtable, and declare an array to storeunique values from the enumeration.

Enumeration values = results.elements(); Object[] searchableEntities;

7. Initialize your array of searchable entities to display.

_myEntities = new MySearchableEntity[0];

8. 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 thesearch results to the user.

Development Guide Searching

24

Page 27: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Device interaction support 3

Device Capability APIYou can query the capabilities of a BlackBerry® device by using the Device Capability API that is provided in thenet.rim.device.api.system.capability package. You can use the DeviceCapability class to querywhether specific features, such as a virtual keyboard or a physical keyboard, are supported on the device, whetherthe feature is currently available to the BlackBerry device user (for example, if the slider on a device is open and theuser 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 virtualkeyboard 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 byimplementing 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 detectionYou can detect when a BlackBerry® device is connected to a cradle (such as a car kit cradle) by using theDeviceCapability.TYPE_CRADLE capability type that is part of the Device Capability API.

You can use DeviceCapability.isSupported() and DeviceCapability.isAvailable() to detect thecradle 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 connectedto 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 andproperties. CradleProtocol is provided in the net.rim.device.api.accessory package. The class providesfields for a cradle's type (such as a car kit cradle, a holster, or a charging pod) and a cradle's properties (such aswhether 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 notprovide its precise type. For example, a car kit cradle might return CradleProtocol.TYPE_SIMPLE, instead ofCradleProtocol.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 net.rim.device.api.accessory.CradleProtocol;import net.rim.device.api.system.capability.DeviceCapability;import net.rim.device.api.ui.component.RichTextField;import net.rim.device.api.ui.container.MainScreen;

Development Guide Device interaction support

25

Page 28: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Cradle detection

26

Page 29: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Cradle handlingYou can register your application as a cradle handler. A cradle handler is an application that can start when aBlackBerry® device is connected to a cradle of a specified type. For example, if your application provides local travelinformation, you might want to register it as a handler for a car kit cradle, so that it can start automatically when thedevice is connected to a car kit cradle.

To register your application as a cradle handler, use CradleHandlerRegistry.registerHandler(). TheCradleHandlerRegistry class is provided in the net.rim.blackberry.api.cradle package. When youregister 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 thenet.rim.device.api.accessory package.

Registration as a cradle handler is persistent. You need to register your application only once after it is installed onthe device.

If any handlers are registered for a cradle type, the user is presented with a dialog box when that type of cradle isconnected.

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

Development Guide Cradle handling

27

Page 30: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

The user can change the cradle handler settings on the device by clicking Options > Third Party Applications on theHome 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 deviceYou can use the Sensor class that is included in the net.rim.device.api.system package, to determine theexistence and the states of sensors on a BlackBerry® device. Sensors that you can work with include the holstersensors, slider sensors, and flip sensors.

You can use the SensorListener class that is also included in net.rim.device.api.system, to let a BlackBerrydevice application receive notifications when the state of a sensor changes.

Check for a sensor on the deviceSensors on the BlackBerry® device that you can work with include the holster sensors, slider sensors, and flip sensors.

1. Import the required classes and interfaces.

import net.rim.device.api.system.Sensor;

2. Invoke Sensor.isSupported() and specify the type of sensor that you want to check for. The sensor typesare defined as constants in the Sensor class. The following code sample checks to see whether a device has aslider.

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

Development Guide Working with sensors on a device

28

Page 31: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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. Import the required classes and interfaces.

import net.rim.device.api.system.Sensor;

2. Invoke Sensor.getState() and specify the type of sensor that you want to check. The sensor types are definedas 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 inthe 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.");

Development Guide Working with sensors on a device

29

Page 32: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 ofsensor (the method's first parameter) and the new state of the sensor (the second parameter). The followingcode 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, thelistener to add, and the types of sensor changes to listen for. The following code sample adds a listener for sliderchanges to the current application. You can invoke Sensor.removeListener() to remove a listener.

Development Guide Working with sensors on a device

30

Page 33: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

5. To listen for changes to multiple sensors, update the third argument of addListener() to add additional sensorstate 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 sensorimport net.rim.device.api.system.*;import net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.component.RichTextField;import net.rim.device.api.ui.container.MainScreen;

public class SensorDemo extends UiApplication

Development Guide Working with sensors on a device

31

Page 34: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Working with sensors on a device

32

Page 35: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

}

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

Development Guide Working with sensors on a device

33

Page 36: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Message list 4This 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 message1. 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 constantparameter 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 messageUse the API items in the javax.wireless.messaging package (JSR 120).

1. Import the required classes and interfaces.

import javax.microedition.io.Connector;import javax.wireless.messaging.MessageConnection;import javax.wireless.messaging.TextMessage;import net.rim.blackberry.api.invoke.Invoke;import 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 message1. Import the required classes and interfaces.

Development Guide Message list

34

Page 37: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 newMessageArguments 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 message1. 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 newMessageArguments object that uses the ARG_NEW field.

Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW));

Create a new populated email message1. Import the required classes and interfaces.

import net.rim.blackberry.api.invoke.Invoke;import net.rim.blackberry.api.invoke.MessageArguments;import net.rim.blackberry.api.mail.Address;import net.rim.blackberry.api.mail.Message;

2. Create and populate a new email Message object.

Message m = new Message();Address a = new Address("[email protected]", "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 message1. Import the required classes and interfaces.

Development Guide Create a new blank email message

35

Page 38: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 newMessageArguments 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 message1. Import the required classes and interfaces.

import net.rim.blackberry.api.invoke.Invoke;import net.rim.blackberry.api.invoke.MessageArguments;import net.rim.blackberry.api.mail.Address;import net.rim.blackberry.api.mail.Message;import 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 notification1. 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. Implement the FolderListener and StoreListener interfaces.

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

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

Development Guide Create a new populated PIN message

36

Page 39: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Add a listener to the message store1. 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 theStore object.

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

4. After the try-catch block, invoke store.addStoreListener() to add a StoreListener instance to theStore object.

store.addStoreListener(this);

Add a listener to the message store for batch updates1. 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.}

Development Guide Add a listener to the message store

37

Page 40: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Add a listener to a folder1. 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 allfolders in the store1. Import the required class.

import net.rim.blackberry.api.mail.Store;

2. Invoke Store.getUnreadMessageCount().

int numUnread = store.getUnreadMessageCount();

Open a message1. Import the required classes and interfaces.

import java.util.Date;import net.rim.blackberry.api.mail.Address;import net.rim.blackberry.api.mail.Folder;import net.rim.blackberry.api.mail.Message;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.Store;

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

Development Guide Add a listener to a folder

38

Page 41: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Store store = Session.waitForDefaultSession.getStore();

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

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

4. Invoke folder.getMessages() to retrieve the message objects and store the message objects in aMessage array. Iterate through the array and retrieve information, such as the sender and subject, to displayto 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 appropriatefields and body contents to display to the user.

Message msg = msgs[0]; // Retrieve the first messageAddress[] 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 multipartif ( 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 messagedoes not contain plain text, the method returns null.

Retrieving the body of an email messageAn email message can contain plain text, HTML, or both. The content and the order of the content in the emailmessage can vary.

A BlackBerry® device application can use the MimeBodyPart class to retrieve the HTML content, or use theTextBodyPart class to retrieve the plain text content. You can use a MultiPart object to retrieve objects fromboth 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 withBlackBerry® Enterprise Server 4.1 Service Pack 6 (4.1.6) or the BlackBerry® Internet Service 2.5.

Development Guide Retrieving the body of an email message

39

Page 42: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Retrieve the plain text and HTML content in the body of an email messageusing a recursive methodCreate 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 net.rim.blackberry.api.mail.MimeBodyPart;import net.rim.blackberry.api.mail.Multipart;import net.rim.blackberry.api.mail.SupportedAttachmentPart;import net.rim.blackberry.api.mail.TextBodyPart;import net.rim.blackberry.api.mail.UnsupportedAttachmentPart;

2. Create the method signature for the recursive method.

void findEmailBody(Object obj) {...}

3. 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 eachBodyPart 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. Check if the BodyPart object is a MimeBodyPart.

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

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

Development Guide Retrieving the body of an email message

40

Page 43: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

a. Cast the BodyPart object as a MimeBodyPart.

MimeBodyPart mbp = (MimeBodyPart) obj;

b. If the MimeBodyPart object does not contain attachments, retrieve the body of the message using theMimeBodyPart 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 themessage.

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

Development Guide Retrieving the body of an email message

41

Page 44: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

} 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 messageIn the following task, an exception may be thrown when you invoke the Transport.more() method.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.BodyPart;import net.rim.blackberry.api.mail.TextBodyPart;import net.rim.blackberry.api.mail.Transport;import net.rim.device.api.ui.component.Dialog;

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

void readEmailBody(TextBodyPart tbp);

3. Cast the value that TextBodyPart.getContent() returns as a String to get the plain text part of the bodyof the message.

_plainTextMessage = (String)tbp.getContent();

Development Guide Retrieving the body of an email message

42

Page 45: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

4. Invoke TextBodyPart.hasMore() and TextBodyPart.moreRequestSent() to identify if more of theTextBodyPart 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 theTextBodyPart 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 messageIn the following task, an exception may be thrown when you invoke the Transport.more() method.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.BodyPart;import net.rim.blackberry.api.mail.MimeBodyPart;import net.rim.blackberry.api.mail.Transport;import 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 ofthe MimeBodyPart object.

Object obj = mbp.getContent();String mimeType = mbp.getContentType();

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

Development Guide Retrieving the body of an email message

43

Page 46: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

String body = null;

5. If the BlackBerry® device can convert the HTML body of a message to a String, the MimeBodyPart object willbe a String. Cast the MimeBodyPart object as a String and assign it to the String representation of thebody 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 objectwill be a byte array. Create a new instance of String using as a parameter the MimeBodyPart object cast asa 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 containsContentType.TYPE_TEXT_PLAIN_STRING to determine if the MimeBodyPart object is the plain text bodypart 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 textbody 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 thedata for the MimeBodyPart object.

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

10. Check to see if the String representation of the content of the MimeBodyPart object containsContentType.TYPE_TEXT_HTML_STRING to detemine if the MimeBodyPart object is the HTML body part ofthe message.

else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1){

11. Invoke MimeBodyPart.hasMore() and MimeBodyPart.moreRequestSent() to determine if all of theHTML 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 theMimeBodyPart object.

Development Guide Retrieving the body of an email message

44

Page 47: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 instanceof String) { body = (String)body; } else if (obj instanceof byte[]) { body = 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()); }

Development Guide Retrieving the body of an email message

45

Page 48: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

} }}

Notify a BlackBerry device application that an emailmessage is about to be sent1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.NoSuchServiceException;import net.rim.blackberry.api.mail.SendListener;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.Store;

2. Implement the SendListener interface.

public class MailSendListener implements SendListener{...}

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

MailSendListener mailSL = new mailSendListener();

4. 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 MMSmessage is about to be sent1. 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{...}

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

46

Page 49: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

MMSSendListener mmsSL = new mmsSendListener();

4. Add a SendListener instance.

MMS.addSendListener(mmsSL);

Notify a BlackBerry device application that an SMSmessage is about to be sent1. Import the required classes and interfaces.

import net.rim.blackberry.api.sms.SendListener;import net.rim.blackberry.api.sms.SMS;

2. Create a class that implements the SendListener interface.

public class smsSendListener implements SendListener{...}

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

smsSendListener smsSL = new smsSendListener();

4. Add a SendListener.

SMS.addSendListener(smsSL);

Send a message1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.Address;import net.rim.blackberry.api.mail.AddressException;import net.rim.blackberry.api.mail.Folder;import net.rim.blackberry.api.mail.Message;import net.rim.blackberry.api.mail.MessagingException;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.Store;import net.rim.blackberry.api.mail.Transport;

2. Declare a Message object.

Message msg;

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

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

47

Page 50: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Address toList[] = new Address[1];

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

try { toList[0]= new Address("[email protected]", "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. Invoke Message.addRecipients() and provide the type of recipient (TO, CC, or BCC) and the array ofaddresses to add as parameters to the method.

8. If the message has multiple types of recipients, invoke Message.addRecipients() once for each recipienttype.

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

9. Invoke Message.setFrom(Address).

Address from = new Address("[email protected]", "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 fromtext 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. TheTransport 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)

Development Guide Send a message

48

Page 51: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Reply to a message1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.Folder;import net.rim.blackberry.api.mail.Message;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.Store;import net.rim.blackberry.api.mail.Transport;

2. Invoke Session.getTransport() and store the returned object in a variable of type Transport. TheTransport object represents the messaging transport protocol.

Transport trans = Session.getTransport();

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

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

4. 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);

5. Specify a specific array element to retrieve the inbox folder.

Folder inbox = folders[0];

6. Invoke Folder.getMessages() to retrieve the messages in the inbox folder. Store the messages in aMessage array.

Message[] messages = inbox.getMessages();

7. Invoke Message.reply(Boolean) and specify true to reply to all message recipients or false to reply toonly 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());}

Development Guide Reply to a message

49

Page 52: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Forward a message1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.Address;import net.rim.blackberry.api.mail.Message;import net.rim.blackberry.api.mail.MessagingException;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.Transport;

2. Invoke Message.forward() on an existing Message object. The subject line of a forwarded message is setautomatically to FW:original_subject.

Message fwdmsg = msg.forward();

3. Create an array of addresses.

Address toList[] = new Address[1];

4. Add a new Address object to the array.

toList[0]= new Address("[email protected]", "Ming Li");

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

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

6. Invoke Message,setContent(String) to set the content of the message that appears before the originalmessage.

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. TheTransport 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());}

Development Guide Forward a message

50

Page 53: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Work with message folders1. Import the required classes and interfaces.

import net.rim.blackberry.api.invoke.Invoke;import net.rim.blackberry.api.invoke.MessageArguments;import net.rim.blackberry.api.mail.Folder;import net.rim.blackberry.api.mail.FolderNotFoundException;import net.rim.blackberry.api.mail.Message;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.Store;

2. Retrieve the store.

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

3. Complete any of the following actions:

Task Steps

Open a folder view 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 thelist.

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

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

Retrieve an array of foldersthrough a search

Invoke Store.findFolder(String).

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

Retrieve a folder by its name a. Invoke Store.getFolder(String) and provide as a parameterthe absolute path to the folder.

Development Guide Work with message folders

51

Page 54: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Task Steps

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

b. Create code to manage a FolderNotFoundException exceptionif the folder does not exist.

Retrieve a folder by its ID a. Invoke Folder.getID() to retrieve the folder ID.

b. 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 messageFolder folder = store.getFolder("Inbox");folder.appendMessage(msg);

Development Guide Work with message folders

52

Page 55: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Custom messages 5

Using custom messages and folders in the message listYou can use the net.rim.blackberry.api.messagelist package to create custom messages and folders for aBlackBerry® 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 deletea message or mark a message as read should be part of the service module. A menu item that lets the user open orreply 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 onhow to use this API.

Creating a module for background processesA service module interacts with an application server and performs other actions in the background. It startsautomatically when the BlackBerry® device starts and runs without input from a BlackBerry device user. The servicemodule can send messages to and receive messages from an application server and can add messages to the messagelist. The messages that it sends can use any protocol you want (for example, a native protocol, an email messageprotocol, 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 UIThe UI module contains UI components and is used to interact with a BlackBerry® device user. Typically, the UI modulestarts automatically when the user interacts with a custom message. For example, if the user highlights a custommessage in the Messages application and clicks the trackpad or touches the touch screen, the UI module should startand 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 processes1. 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 moreinformation, see the BlackBerry Java Plug-in for Eclipse Development Guide.

Development Guide Custom messages

53

Page 56: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

2. Create a class with the fields and methods for the module.

3. Compile the project into a .jad file.

4. 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 modulefor the UI1. Import the required classes and interfaces.

import net.rim.blackberry.api.messagelist.*;

2. 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 servicemodule 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 thatcontains the service functionality and items. Obtain a reference to anApplicationMessageFolderRegistry 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 thatcontains the UI functionality and items. For example, the UI module should start if the BlackBerry device userclicks the application icon on the Home screen or opens a custom message in the Messages application. Displaythe 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

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

54

Page 57: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

{ 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 messageYou can associate icons with a custom message. You associate an icon with a custom message's type and status. Forexample, you can associate one icon with an unopened message and a different icon with an opened message. Theicon 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. Passin 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 iconto a custom message. Specify the following as arguments: a value for the message type for a BlackBerry® deviceapplication, a message status by using a field from the ApplicationMessage.Status interface, and aninstance 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 );

Development Guide Create an icon for a custom message

55

Page 58: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Create a custom folder in the message listCustom 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. Create a class that implements the ApplicationMessage interface.

public class MLSampleMessage implements ApplicationMessage

3. Obtain a reference to an ApplicationMessageFolderRegistry object.

ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();

4. Invoke ApplicationMessageFolderRegistry.registerFolder() to register a custom folder for eachcollection 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 benotified when specific folder events occur. In the following code sample, the application listens for deletedmessages. For a list of all actions that you can listen for, see the documentation for theApplicationMessageFolderListener 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 folderevent occurs.

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

Development Guide Create a custom folder in the message list

56

Page 59: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

{ // 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 rootfolder for your application's custom folders. The name of the root folder appears in the View Folder dialog boxof the Messages application when an application registers more than one application message folder.

reg.setRootFolderName( "ML Sample" );

Send a notification when a custom folder changesAfter 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 applicationmight 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 benotified when a custom folder changes.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.messagelist.*;

2. Invoke ApplicationMessageFolder.fireElementAdded() to notify an application when a message isadded to a custom folder.

inboxFolder.fireElementAdded( newMessage );

3. Invoke ApplicationMessageFolder.fireElementRemoved() to notify an application when a message isremoved from a custom folder.

inboxFolder.fireElementRemoved( deletedMessage );

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

inboxFolder.fireElementUpdated( updatedMessage );

5. Invoke ApplicationMessageFolder.fireReset() to notify an application when more than one messagein a custom folder changes.

inboxFolder.fireReset();

Development Guide Send a notification when a custom folder changes

57

Page 60: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Create a custom indicatorA custom indicator appears on the Home screen along with other indicators, such as the new message indicator andcalendar reminders. You can use the ApplicationIndicator class to create and manage an indicator for custommessages. For example, you can create an indicator to display the number of unread custom messages in the messagelist. Indicators are visible even when the BlackBerry® device is locked. Your application can register only one indicatorand must register the indicator every time that the BlackBerry device starts. The size of an indicator can varydepending on the device and theme. For more information on the size of an indicator, see the UI Guidelines forBlackBerry 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 EncodedImagevariable. 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(). Inthe following code sample, the second parameter specifies that the indicator can have a numeric value associatedwith it (for example, new message count). The third parameter specifies that the indicator should be visible.

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

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

ApplicationIndicator appIndicator = reg.getApplicationIndicator();

6. Set the icon and value for the indicator by invoking ApplicationIndicator.set(). You should consider onlyshowing a value if it is greater than 0.

appIndicator.set( newIcon, newValue );

Hide an indicator1. Import the required classes and interfaces.

import net.rim.blackberry.api.messagelist.*;

Development Guide Create a custom indicator

58

Page 61: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

2. To temporarily hide an indicator, invoke ApplicationIndicator.setVisible() and provide false as theargument.

appIndicator.setVisible( false );

Remove a custom indicatorYou can remove a custom indicator from the Home screen by unregistering it.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.messagelist.*;

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

reg.unregister();

Development Guide Remove a custom indicator

59

Page 62: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Create an attachment handlerYou can use the AttachmentHandler interface to manage an attachment to an email message that appears in themessage list on the BlackBerry® device.

Note: The BlackBerry® Attachment Service receives all attachments first. Third-party attachment handlers cannotoverride this default behavior. For more information about the BlackBerry Attachment Service, see the BlackBerryEnterprise 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. Implement the AttachmentHandler interface to create a custom attachment handler.

public class AttachTest implements AttachmentHandler {...}

3. Implement the supports(String) method, to specify the content type of the attachment supported by yourhandler.

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 selectsan 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 followingcode sample, a new screen uses the RichTextField class to display a String representation of the contentof 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())));}

Development Guide Attachments

60

Page 63: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

6. Invoke AttachmentHandlerManager.addAttachmentHandler(), to register the attachment handler withthe manager. Note that the attachment name must be prefixed with "x-rimdevice" for the attachment to besent and stored on the BlackBerry device.

AttachmentHandlerManager m = AttachmentHandlerManager.getInstance();CustomAttachmentHandler ah = new CustomAttachmentHandler();m.addAttachmentHandler(ah);

Retrieve the contents of an attachment1. Import the net.rim.blackberry.api.mail.SupportedAttachmentPart class.

2. Invoke SupportedAttachmentPart.getContent().

String s = new String((byte[])p.getContent());

Retrieve information about an attachment1. Import the net.rim.blackberry.api.mail.SupportedAttachmentPart class.

2. Invoke the methods of the SupportedAttachmentPart class. The SupportedAttachmentPart classrepresents an attachment with a corresponding viewer on the BlackBerry® device. TheUnsupportedAttachmentPart class represents an attachment that does not have a viewer on the BlackBerrydevice.

Send a message with an attachment1. Import the required classes and interfaces.

import net.rim.blackberry.api.mail.Message;import net.rim.blackberry.api.mail.MessagingException;import net.rim.blackberry.api.mail.Multipart;import net.rim.blackberry.api.mail.Session;import net.rim.blackberry.api.mail.SupportedAttachmentPart;import 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 eachcomponent of the screen.

SupportedAttachmentPart attach = new SupportedAttachmentPart( multipart,"application/x-example", "filename", data);

4. Invoke MultiPart.addBodyPart(SupportedAttachmentPart) to add eachsupportedAttachmentPart object to the multipart object.

Development Guide Retrieve the contents of an attachment

61

Page 64: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

multipart.addBodyPart(attach);

5. Invoke Message.setContent(Multipart) and provide as a parameter the Multipart object to set thecontent of the attachment.

msg.setContent(multipart);

6. Invoke Session.getTransport() and store the returned object in a variable of type Transport. TheTransport 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 automaticallyWhen a message arrives in the messages application on the BlackBerry® device with an attachment, you canautomatically 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. Ifverification errors are found, the method throws an exception. For a list of possible verification errors, see the APIreference for the BlackBerry® Java® Development Environment.

Note: The BlackBerry® Attachment Service receives all attachments first. Third-party attachment handlers cannotoverride this default behavior. For more information about the BlackBerry Attachment Service, see the BlackBerryEnterprise Server Administration Guide.

1. Import the required classes and interfaces.

import java.io.IOException;import net.rim.blackberry.api.mail.*;

Development Guide Download attachments automatically

62

Page 65: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

2. Implement the DownloadProgressListener interface. Create an instance of theAttachmentDownloadManager class.

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

3. Use the methods available in AttachmentDownloadManager to determine information about the attachment.

public String fileSize = getFileSize(BodyPart bodyPart);public String fileName = getFileName(BodyPart bodyPart);public String fileType = getFileContentType(BodyPart bodyPart);public String filePath = getDownloadedFileName(BodyPart bodyPart);

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

_adm.download(bodyParts, null, this);

5. Override the DownloadProgressListener callback methods, to provide updates about the status of thedownload 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){}

Development Guide Download attachments automatically

63

Page 66: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Calendar 7

Open the calendar1. 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. Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments).

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

View or change a calendar entry1. Import the required classes and interfaces.

import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.Event;import javax.microedition.pim.EventList;import net.rim.blackberry.api.invoke.CalendarArguments;import net.rim.blackberry.api.invoke.Invoke;import 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 theCalendarArguments 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 theapplication that it invokes.

Open a new populated calendar entry1. Import the required classes and interfaces.

import javax.microedition.pim.PIM;import javax.microedition.pim.Event;import javax.microedition.pim.EventList;

Development Guide Calendar

64

Page 67: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 theCalendarArguments 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 information1. Import the required classes and interfaces.

import java.util.Date;import javax.microedition.pim.Event;import javax.microedition.pim.EventList;import javax.microedition.pim.PIM;import javax.microedition.pim.RepeatRule;

2. Invoke openPIMList() to open a list of calendar entries. Provide the following as parameters: the type of listto 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:

Development Guide Update calendar entry information

65

Page 68: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Task Steps

Create an appointment Invoke createEvent() on an event list.

Event event = eventList.createEvent();

Add appointment information Invoke Event.isSupportedField(int) to verify that an itemsupports 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 fieldsfor the properties and values that you can set, such as COUNT,FREQUENCY, and INTERVAL.

b. Invoke RepeatRule.getFields() to retrieve an array ofsupported fields.

Development Guide Update calendar entry information

66

Page 69: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Task Steps

c. Invoke RepeatRule.setInt(int, int) orRepeatRule.setDate (int, int, int, long) on a newRepeatRule 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 assigna 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. Invoke the appropriate set method, such as setString() toreplace an existing value with a new one.

b. Invoke Event.countValues() to determine if a value is alreadyset for the field.

c. Use the corresponding set method, such as setString() tochange 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 fieldsthat have changed since the appointment was last saved, invokeEvent.isModified().

b. Invoke Event.commit().

if(event.isModified()) { event.commit();}

Retrieve calendar entry information1. Import the required classes and interfaces.

Development Guide Retrieve calendar entry information

67

Page 70: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

javax.microedition.pim.Eventjavax.microedition.pim.EventListjavax.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. InvokePIMItem.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 entry1. Import the required classes and interfaces.

import java.io.ByteArrayOutputStream;import java.util.Enumeration;import javax.microedition.pim.Event;import javax.microedition.pim.EventList;import javax.microedition.pim.PIM;

2. Invoke PIM.supportedSerialFormats() specifying the list type (PIM.EVENT_LIST), to retrieve a stringarray of supported serial formats.

String[] dataFormats = PIM.supportedSerialFormats(PIM.EVENT_LIST);

3. Use an output stream writer to export calendar entries from the BlackBerry® device to a supported serial format,such as iCal.

4. Invoke toSerialFormat() to write an item in serial format. The enc parameter specifies the characterencoding to use when writing to the output stream. Supported character encodings include “UTF8,”“ISO-8859-1,” and “UTF-16BE”. This parameter cannot be null.

Development Guide Export a calendar entry

68

Page 71: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 entry1. Import the required classes and interfaces.

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import javax.microedition.pim.Event;import javax.microedition.pim.EventList;import javax.microedition.pim.PIM;

2. Invoke PIM.getInstance().fromSerialFormat() to return an array of PIMItem objects.

3. Invoke EventList.importEvent() to add a new calendar entry.

// Convert an existing entry into a iCal and then // import the iCal as a new entryString[] dataFormats = PIM.supportedSerialFormats();

// Write entry to iCalByteArrayOutputStream os = new ByteArrayOutputStream();PIM.getInstance().toSerialFormat(event, os, "UTF8", dataFormats[0]);

// Import entry from iCalByteArrayInputStream 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 entriesThe first element in the array of lists is the default list.

1. Import the javax.microedition.pim.PIM class.

2. Invoke PIM.listPIMLists(int pimListType).

String[] allLists = PIM.listPIMLists(PIM.EVENT_LIST);

Development Guide Import a calendar entry

69

Page 72: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Notify a BlackBerry device application when a list ofcalendar entries changes1. Import the required classes and interfaces.

import javax.microedition.pim.EventList;import javax.microedition.pim.PIM;import net.rim.blackberry.api.pdap.BlackBerryPIMList;import net.rim.blackberry.api.pdap.PIMListListener;

2. Implement the PIMListListener interface.

public class MyEventListListener implements PIMListListener {...}

3. Invoke BlackBerryPIMList.addListener() to register to receive notifications of changes to a list ofcalendar 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 listof calendar entries changesWhen an update occurs to the list of services on a BlackBerry® device, the list of PIM databases on a device maychange. 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. Implement the ListChangeListener interface.

public class MyListChangeListener implements ListChangeListener {...}

3. Invoke BlackBerryPIM.addListChangeListener() to register to receive notifications of changes to adefault 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 designthe ListChangeListener.defaultListChanged() method to update the reference when the default listchanges.

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

70

Page 73: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Update a calendar entry with no notificationYou 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 java.util.*;import javax.microedition.pim.*;import net.rim.blackberry.api.pdap.BlackBerryEvent;import net.rim.blackberry.api.pdap.BlackBerryEventList;import 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 flagBlackBerryEvent.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 }}

Development Guide Update a calendar entry with no notification

71

Page 74: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

If you specify BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES when committing changes to a calendarentry, notification is not sent unless the calendar entry is a new meeting or meeting participants have beenadded since the last update (meeting participants must be notified about the meeting in order to accept themeeting invitation). If notification was sent, BlackBerryPIMItem.commit() returnsBlackBerryEvent.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 notificationYou 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 java.util.*;import javax.microedition.pim.*;import net.rim.blackberry.api.pdap.BlackBerryEvent;import 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);

Development Guide Remove a calendar entry with no notification

72

Page 75: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Remove a calendar entry with no notification

73

Page 76: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Contact list 8You can use an instance of the ContactList class or BlackBerryContactList class in your application to addand view contact information in the contacts application on the BlackBerry® device. You can create Contact orBlackBerryContact objects to store information for individual contacts such as the name, phone number, emailaddress, and street address.

Your application can perform tasks such as adding, deleting, and changing contact list entries.

Multiple contact lists supportSupport for multiple contact lists is available in BlackBerry® Java® Development Environment 5.0 or later. Each contactlist has a system-assigned contact list name and a UID that you can use to retrieve the list. You can change the contactlist name by using the BlackBerry® Desktop Manager to change the name of the service that is associated with thecontact 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. Ifyour application requires the contact list name to persist across OS updates, use the UID to open the contact list. Ifyour application requires the contact list name to persist only across BlackBerry device restarts, you can use thecontact list name. Because a contact list name can change, you can register a listener for name change events byinvoking BlackBerryPIM.addListChangeListener(ListChangeListener listener).

You can retrieve the names of the contact lists that are installed on a BlackBerry device by invokingPIM.listPIMLists(int pimListType) and passing in PIM.CONTACT_LIST as pimListType. The Stringarray that is returned provides the system-assigned names for the contact lists on the device. The contact list namethat is at index 0 of the returned String array is the default contact list. You can retrieve the UID of a contact liston a BlackBerry device by invoking BlackBerryPIMList.getPIMListUID().

You can open a contact list by its name by invoking PIM.openPIMList(int pimListType, int mode, Stringname). 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 theBlackBerryPIM.openUnifiedPIMList() methods.

Open the contacts applicationYou 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);

Development Guide Contact list

74

Page 77: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Open the contacts application by using contact dataYou can open the contacts application on a BlackBerry® device and display a contact by using theInvoke.invokeApplication() method, and passing in contact data as a parameter of anAddressBookArguments object.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.invoke.AddressBookArguments;import net.rim.blackberry.api.invoke.Invoke;import net.rim.blackberry.api.pdap.BlackBerryContact;import net.rim.blackberry.api.pdap.BlackBerryContactList;import net.rim.device.api.system.ControlledAccessException;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;

2. Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList(int, int) to openthe default contact list, passing in as parameters the type of list to open (PIM.CONTACT_LIST) and the accessmode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). To open a namedcontact list, you can instead invoke PIM.openPIMList(int, int, String).

BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

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

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

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

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

5. Invoke Invoke.invokeApplication(APP_TYPE_ADDRESSBOOK, AddressBookArguments) and use theAddressBookArguments object for the contact.

Invoke.invokeApplication(Invoke.APP_TYPE_ADDRESSBOOK, abArg);

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

Open the contacts application with a specific contact listYou can open the contacts application on a BlackBerry® device and display a specific contact list by invoking theBlackBerryContactList.choose() method.

1. Import the required classes and interfaces.

Development Guide Open the contacts application by using contact data

75

Page 78: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

2. Invoke PIM.listPIMLists(int pimListType) to return an array of String objects. The returned arrayprovides the system-assigned names, one for each PIM list of the specified type. The default list of the specifiedtype is returned at index 0 of the array.

String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);

3. Iterate over the array that is returned from PIM.listPIMLists() to search for the system-assigned name forthe contact list that you want to display.

4. Invoke BlackBerryPIMList.getPIMListUID() to return the UID for contact list.

long uid = cl.getPIMListUID();

5. 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), theaccess mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and theUID.

BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, uid);

6. Invoke BlackBerryContactList.choose() to return a BlackBerryContact or aBlackBerryContactGroup 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 havepermission to access the application that it invokes.

Development Guide Open the contacts application with a specific contact list

76

Page 79: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Create a contact and assign it to a contact listYou 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 net.rim.blackberry.api.pdap.BlackBerryContact; import net.rim.blackberry.api.pdap.BlackBerryContactList;import net.rim.blackberry.api.pdap.BlackBerryPIMList;import net.rim.device.api.system.ControlledAccessException;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMList;import javax.microedition.pim.PIMException;import javax.microedition.pim.ContactList;

2. To add the new contact to the default contact list, invoke PIM.openPIMList(int, int) to open the defaultcontact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST) and thePIM.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), toreturn an array of String objects. The returned array provides the system-assigned names for each contactlist. 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 thecontact list that you want to open.

c. Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in asparameters the type of list to open (PIM.CONTACT_LIST), the PIM.READ_WRITE access mode, and thecontact list name.

BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);

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

BlackBerryContact contact = contactList.createContact();

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

Development Guide Create a contact and assign it to a contact list

77

Page 80: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

6. Invoke the following methods to verify that the information meets the size requirements and type requirementsfor 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.

7. Invoke Contact.commit() to commit the changes.

if(contact.isModified()){ contact.commit();}

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

Retrieve contact informationYou 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 theBlackBerryContactList.items() methods to return contact groups.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.pdap.BlackBerryContact;import net.rim.blackberry.api.pdap.BlackBerryContactList;import net.rim.blackberry.api.pdap.BlackBerryPIMList;import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;import javax.microedition.pim.PIMItem;

2. Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList() to open a contactlist instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode withwhich to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the name if you arenot opening the default contact list.

BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

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

Enumeration _enum = contactList.items();

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

Development Guide Retrieve contact information

78

Page 81: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

• To retrieve a date that represents the value for a specified contact field, invoke PIMItem.getDate(intfield, 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 UIDYou can open a contact list on a BlackBerry® device by specifying a system-assigned name or a UID. The UID isassociated with a BlackBerry® Enterprise Server account and persists across all BlackBerry device changes, includingOS updates. You can open the contact list by its UID by invoking BlackBerryPIM.openPIMList(intpimListType, int mode, long uid).

1. Import the required classes and interfaces.

import net.rim.blackberry.api.pdap.BlackBerryContactList;import net.rim.blackberry.api.pdap.BlackBerryPIMList;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;import javax.microedition.pim.PIMItem;

2. Access the contact list that you want to work with.

3. Invoke BlackBerryPIMList.getPIMListUID() to retrieve the UID of the contact list.

long uid = list.getPIMListUID();

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

Development Guide Retrieve a contact list UID

79

Page 82: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

and passing in as arguments the PIMItem, the OutputStream to which the serialized PIMItem is written, thecharacter 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 java.io.UnsupportedEncodingException;import java.util.Enumeration;import javax.microedition.pim.Contact;import javax.microedition.pim.ContactList;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;

2. Invoke PIM.supportedSerialFormats() and specify the list type (PIM.CONTACT_LIST) to retrieve a stringarray 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 toa supported serial format. Use the enc parameter to specify the character encoding format to use when writingto the output stream. Supported character encoding formats include UTF8, ISO-8859-1, and UTF-16BE. If theenc 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 contactYou can import contact information from a compatible input stream to a contact list on a BlackBerry® device. Youcan import contact information by invoking fromSerialFormat(InputStream, String), and passing in asarguments 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.

Development Guide Import a contact

80

Page 83: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

import java.io.ByteArrayOutputStream;import javax.microedition.pim.Contact;import javax.microedition.pim.ContactList;import javax.microedition.pim.PIM;import 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 contactYou 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 net.rim.blackberry.api.pdap.BlackBerryContact; import net.rim.blackberry.api.pdap.BlackBerryPIMList;import net.rim.device.api.system.ControlledAccessException;import javax.microedition.pim.Contact;import javax.microedition.pim.ContactList;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;

2. To delete a contact from the default contact list, invoke PIM.openPIMList(int, int) to open the defaultcontact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), and the accessmode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). Proceed to step4.

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 arrayprovides the system-assigned name for each contact list. The default contact list is returned at index 0 ofthe 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 thecontact list that you want to delete.

Development Guide Delete a contact

81

Page 84: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

c. Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in asparameters 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. Invoke BlackBerryContactList.removeContact() to delete the contact from the contact list.

contactList.removeContact(contact);

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

Notify an application when a contact list changesYou can register your application to receive notification of changes to the contact lists on a BlackBerry® device byimplementing the PIMListListener interface. The PIMListListener interface provides the following methods:

• 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

1. Import the required classes and interfaces.

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

2. To receive change notifications for the default contact list, invoke PIM.openPIMList(int, int) to open thedefault contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), and theaccess mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). Proceedto 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 eachcontact 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 thecontact list that you want to receive change notifications for.

Development Guide Notify an application when a contact list changes

82

Page 85: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

c. Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in asparameters 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. Invoke BlackBerryPIMList.addListener() to register a listener for the contact list.

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

5. Override the PIMListListener.itemAdded(), PIMListListener.itemUpdated(), andPIMListListener.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 havepermission to access the application that it invokes.

Creating and removing contact listsYou 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 aPIMException is thrown.

You can also remove contact lists by invoking BlackBerryPIM.removePIMList(). Currently, this method supportsPIM lists only of type PIM.CONTACT_LIST.

Create a contact listYou 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.

Development Guide Creating and removing contact lists

83

Page 86: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

• Applications can register to listen for changes to your contact list by invokingBlackBerryPIMList.addListener().

1. Import the required classes and interfaces.

import javax.microedition.pim.Contact;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;import javax.microedition.pim.PIMItem;import net.rim.blackberry.api.pdap.BlackBerryContact;import net.rim.blackberry.api.pdap.BlackBerryContactList;import net.rim.blackberry.api.pdap.BlackBerryPIM;import net.rim.blackberry.api.pdap.BlackBerryPIMList;

2. Retrieve a BlackBerryPIM object.

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

3. Create the contact list.

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

The contact list is named using the name that you provide ("test" in the preceding example), unless there isanother contact list with that name on the device, in which case a number is appended to the name to make itunique. To reference the contact list later, you should use the list's UID, which is the value that is returned bycreatePIMList().

4. 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);

Development Guide Creating and removing contact lists

84

Page 87: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 listYou 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. Retrieve a BlackBerryPIM object.

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

3. If you know the name or UID of the contact list that you want to remove, go to step 6.

4. Retrieve the array of contact lists.

String[] lists = myPIM.listPIMLists(PIM.CONTACT_LIST);

The returned array provides the names that are assigned to each contact list.

5. Iterate through the array to search for the contact list that you want to remove.

6. Remove the contact list by invoking BlackBerryPIM.removePIMList(). You can provide either the name orthe UID of the contact list. By default, the method removes a contact list only if the list is empty. If you want toremove a contact list that is not empty, you must provide the parameterBlackBerryPIM.REMOVE_NON_EMPTY_LIST.

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

Development Guide Creating and removing contact lists

85

Page 88: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 call1. 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 returnsa BlackBerryContact that is associated with the current phone number, or null if there is no matchingcontact.

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

Development Guide Retrieve the contact that is associated with an active call

86

Page 89: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 topicsDisplay content on a phone screen, 108

Retrieve the contact that is associated with a completed callYou 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. Retrieve the caller ID information for a call from the call log.

PhoneCallLogID callLog = new PhoneCallLogID(phoneNum);

3. Retrieve the associated contact by invoking PhoneCallLogID.getContact(). The getContact() methodsearches all contact lists on the BlackBerry device for a contact that matches the caller ID information. Themethod returns null if there is no matching contact.

BlackBerryContact contact = callLog.getContact();

Development Guide Retrieve the contact that is associated with a completed call

87

Page 90: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 numberYou can search all contact lists or a specified contact list on a BlackBerry® device for contacts that match a specifiedphone number.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.pdap.BlackBerryContact;import net.rim.blackberry.api.pdap.BlackBerryContactList;import net.rim.blackberry.api.pdap.BlackBerryPIMList;import net.rim.blackberry.api.phone.Phone;import java.util.*;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMException;import javax.microedition.pim.PIMItem;

2. Do one of the following:

a. To search all contacts lists, invoke Phone.getContactsByPhoneNumber(), which returns a Vectorobject that contains the contacts that match the specified phone number. The Vector is empty if thereare no matching contacts.

Vector contacts = Phone.getContactsByPhoneNumber(phoneNum);

b. To search a specified contact list, invoke BlackBerryContactList.itemsByPhoneNumber(), whichreturns an Enumeration object of all contacts that match the specified phone number. Each of the itemsin 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

Development Guide Retrieve contacts by phone number

88

Page 91: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 ContactsapplicationYou can allow BlackBerry® device users to link contact data in your application with contacts in the Contactsapplication on the BlackBerry device by using the Contact Linking API in thenet.rim.blackberry.api.pdap.contactlinking package. For example, you can allow users to link a contactin 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, acontact in the Contacts application can be linked with contacts in multiple third-party applications. When a user triesto link a contact in your application with a contact in the Contacts application, you can use the Contact Linking APIto perform some tasks automatically, such as searching for a matching contact and checking whether the contact isalready linked.

You can create menu items that appear in the Contacts application when a user views a contact that is linked withone of your contacts. The menu items can perform any action you want. For example, you can allow a user to addnotes 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 linkedto one of your contacts.

The Contact Linking Demo sample application is included in the BlackBerry® Java® SDK. The application demonstrateshow to use the Contact Linking API.

Development Guide Linking third-party contacts with contacts in the Contacts application

89

Page 92: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Link a contactYou can link a contact in your application with a contact in the Contacts application on the BlackBerry® device. Youcan decide how to interact with the BlackBerry device user when you link a contact. The steps that follow describeone 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 alinking candidate for your contact. The LinkedContactUtilities.getContactLinkCandidate() methodreturns a BlackBerryContact if it finds a contact in the Contacts application that has the same email addressor phone number as the LinkableContact that is passed to it. If there is no matching contact, the methodreturns null.

BlackBerryContact bbContact = LinkedContactUtilities.getContactLinkCandidate(linkableContact);

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

bbContact = LinkedContactUtilities.linkContact(bbContact, linkableContact);

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

Development Guide Linking third-party contacts with contacts in the Contacts application

90

Page 93: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 sampleapplication that is included in the BlackBerry® Java® SDK.

Remove a linkYou can remove a link between a contact in your application and a contact in the Contacts application on theBlackBerry® device.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.pdap.contactlinking.*;

2. 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 contactsYou can create menu items that are available in the Contacts application on the BlackBerry® device when a userviews a contact that is linked with a contact in your application by invokingLinkedContactUtilities.registerMenuItems(). You must assign menu items to an application group byusing the LinkedContactConstants interface.

Development Guide Linking third-party contacts with contacts in the Contacts application

91

Page 94: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Application group Description

COMPOSE_SN_MENU_GROUP social networking applicationsCOMPOSE_IM_MENU_GROUP instant messaging applicationsCOMPOSE_OTHER_MENU_GROUP 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 inthe 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 Contactsapplication.

Situation Result

A group contains one application withlinked contacts. The application containsone menu item.

The menu item for the application appears in the menu in theContacts application.

A group contains one application withlinked contacts. The application containsmultiple menu items.

The application's name appears in the menu. Selecting the namedisplays a dialog box that contains a button for each menu item.

A group contains multiple applicationswith linked contacts.

The group menu item (such as Social Networking) appears in themenu. Selecting the group menu item displays a dialog box with abutton for each application with linked contacts in the group.

Create menu items for linked contactsYou can create menu items that are available in the Contacts application on the BlackBerry® device when a userviews a contact that is linked with a contact in your application.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.menuitem.ApplicationMenuItem;import net.rim.blackberry.api.pdap.contactlinking.LinkedContactConstants;import net.rim.blackberry.api.pdap.contactlinking.LinkedContactUtilities;import net.rim.device.api.system.ApplicationDescriptor;

2. Create a class that extends the ApplicationMenuItem class.

public class LinkedMenuItem extends ApplicationMenuItem {...}

3. Create an application descriptor for your application.

Development Guide Linking third-party contacts with contacts in the Contacts application

92

Page 95: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

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

public static final long APPLICATION_ID = 0x1eredfe71d34760fdL;

5. 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 tothe menu. Pass in the array of menu items, the unique ID of your application, the application group, and theapplication 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 theContact Linking Demo sample application that is included in the BlackBerry® Java® SDK.

Create an information provider for a linked contactYou can create a class that extends the abstract LinkedContactInfoProvider class to define information abouta linked contact. This information appears in the Contacts application on the BlackBerry® device when a user viewsa 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 animage in order for any information to appear for your linked contact when a user views a contact in the Contactsapplication.

Development Guide Linking third-party contacts with contacts in the Contacts application

93

Page 96: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

public Image getAppImage(){ return _image; }

4. Implement getAppName() and return the name of your application. The method must return a name in orderfor 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 yourapplication supports, implement isSupported(). By default, a field is not supported. You need to implementisSupported() 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 theContacts application. Specify the contact's name, status, and current availability, depending on which fields youdefined 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. Register the information provider with your application.

Development Guide Linking third-party contacts with contacts in the Contacts application

94

Page 97: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 theCOMPOSE_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 thatyou defined in your information provider displays on the contact screen. The framework determines the layout ofthe information. In this example, because the application was defined as a social networking application, theinformation 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 theSampleLinkedContactInfoProvider class in the Contact Linking Demo sample application that is included inthe BlackBerry® Java® SDK.

Development Guide Linking third-party contacts with contacts in the Contacts application

95

Page 98: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Task list 9

View or change a task1. Import the required classes and interfaces.

import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.ToDo;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 and store it in an Enumeration.

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

3. Create a ToDo object using an element from the Enumeration.

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

4. Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments objectcreated 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 task1. 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 objectcreated using the ARG_NEW field.

Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments( TaskArguments.ARG_NEW));

Create a new populated task1. Import the required classes and interfaces.

import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.ToDo;

Development Guide Task list

96

Page 99: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 objectcreated 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 list1. 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 theaccess 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 task1. 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();

Development Guide Open a task list

97

Page 100: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Add task information1. Import the required classes and interfaces.

import java.util.Date;import javax.microedition.pim.PIMList;import javax.microedition.pim.ToDo;import javax.microedition.pim.ToDoList;

2. Before you set or retrieve a field, verify that the item supports the field by invokingToDoList.isSupportedField(int).

3. Invoke PIMList.getFieldDataType(int) to retrieve the field data type.

4. 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 information1. Import the required classes and interfaces.

import javax.microedition.pim.ToDo;import javax.microedition.pim.ToDoList;

2. To replace an existing value with a new value, invoke the appropriate set method, such as ToDo.setString().

3. To determine if a value is already set for the field, invoke ToDo.countValues().

Development Guide Add task information

98

Page 101: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Save a task1. Import the required classes and interfaces.

import javax.microedition.pim.ToDo;import javax.microedition.pim.ToDoList;

2. Before you commit your changes, invoke isModified() to determine whether any task fields have changedsince the task was last saved.

3. Invoke commit().

if(task.isModified()) { task.commit();}

Retrieve task information1. Import the required classes and interfaces.

import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.ToDo;import 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. Invoke ToDo.getFields() to retrieve an array of IDs for fields that have data for a particular ToDo item.

4. 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) {

Development Guide Save a task

99

Page 102: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Export a task1. Import the required classes and interfaces.

import java.io.ByteArrayOutputStream;import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.ToDo;import javax.microedition.pim.ToDoList;

2. Use an output stream writer to export tasks from the BlackBerry® device to a supported serial format.

3. To retrieve a string array of supported serial formats, invoke PIM.supportedSerialFormats(), and thenspecify the list type (PIM.TODO_List).

4. To write an item to a serial format, invoke PIM.getInstance().toSerialFormat. The enc parameterspecifies the character encoding to use when writing to the output stream. Supported character encodingsinclude "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 task1. Import the required classes and interfaces.

import java.io.ByteArrayInputStream;import javax.microedition.pim.PIM;import javax.microedition.pim.PIMItem;import javax.microedition.pim.ToDo;import javax.microedition.pim.ToDoList;

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

Development Guide Export a task

100

Page 103: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

String[] dataFormats = PIM.toDoSerialFormats();

// Write task to serial formatByteArrayOutputStream os = new ByteArrayOutputStream();PIM.getInstance().toSerialFormat(task, os, "UTF8", dataFormats[0]);

// Import task from serial formatByteArrayInputStream 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 task1. Import the required classes and interfaces.

import java.util.Enumeration;import javax.microedition.pim.PIM;import javax.microedition.pim.ToDo;import 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 list1. Import the required classes and interfaces.

import javax.microedition.pim.PIMException;import javax.microedition.pim.ToDoList;

2. Invoke ToDoList.close().

3. Create code that manages exceptions.

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

Development Guide Delete a task

101

Page 104: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Notify a BlackBerry device application when a list of taskschanges1. 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. Implement the PIMListListener interface.

class MyTaskListListener implements PIMListListener {...}

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

Development Guide Notify a BlackBerry device application when a list of tasks changes

102

Page 105: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Phone 10The net.rim.blackberry.api.phone package contains the APIs that you can use to access the phone applicationon the BlackBerry® device. You can use this package to make calls, switch between available phone lines, receivenotification events, and change phone options.

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

Make a call from a BlackBerry device application (single-line 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 phonenumber.

PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL, "519-555-0100");

3. Invoke Invoke.invokeApplication() to open the phone application from your application, providing theAPP_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-lineenvironment)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 hard-coded number or user text. In the following code sample, the application makes a call to the destination number519-555-0100 and uses the line ID that returns at index 0.

Phone.initiateCall(Phone.getLineIds()[0], "519-555-0100");

Development Guide Phone

103

Page 106: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Add DTMF tones to the send queue1. Import the required class.

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

2. • 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 Low Tone (Hz) High Tone (Hz)

1 697 12092 697 13363 697 14774 770 12095 770 13366 770 14777 852 12098 852 13369 852 14770 941 1209* 941 1336# 941 1477

Listen for and handle phone eventsYou can configure your BlackBerry® device application to listen for and automatically handle various phone eventsby implementing the PhoneListener interface. The PhoneListener interface provides a set of callback methodsthat you can use to receive notification of phone events.

1. Import the required classes and interfaces.

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

2. Create a class that implements the PhoneListener interface.

3. Register the class that implements PhoneListener by invoking addPhoneListener().

Development Guide Add DTMF tones to the send queue

104

Page 107: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Phone.addPhoneListener(this);

4. Handle incoming phone events by using the PhoneListener callback methods. For example, to receivenotification that a call is disconnected, implement the notification in callDisconnected(int); to receivenotification that a new call has arrived, implement the notification in callIncoming(int); and to receivenotification 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

5. To deregister the PhoneListener, invoke Phone.removePhoneListener().

Phone.removePhoneListener(this);

Listen for and handle multi-line eventsFor BlackBerry® devices that support multiple phone lines, you can configure your application to listen for andautomatically handle multi-line phone events by using the MultiLineListener class. The MultiLineListenerclass is a helper class that implements the PhoneListener interface and provides a set of callback methods thatyou 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. Create a class that extends MultiLineListener.

3. Register the class as a PhoneListener by invoking Phone.addPhoneListener().

Phone.addPhoneListener(this);

4. To handle line switching events, perform the following actions:

a. Override the MultiLineListener callback methods to notify the application when a line switching eventoccurs. 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 followingcode sample, the application selects the line that returns at index 0.

Phone.setPreferredLine( Phone.getLineIds()[0]);

Development Guide Listen for and handle multi-line events

105

Page 108: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Retrieve call information by using call logsCall 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 orPhoneLogs.FOLDER_MISSED_CALLS constants.

1. Import the required classes.

import net.rim.blackberry.api.phone.phonelogs.*;

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

PhoneLogs _logs = PhoneLogs.getInstance();

3. 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 areTYPE_MISSED_CALL_OPENED, TYPE_MISSED_CALL_UNOPENED, TYPE_PLACED_CALL, orTYPE_RECEIVED_CALL.

int phoneType = phoneLog.getType();

Retrieve a call participantYou can use the PhoneCallLogID and ConferencePhoneCallLog classes to retrieve a call participant from a thecall log.

1. Import the required classes and interfaces.

import net.rim.blackberry.api.phone.phonelogs.*;

2. Invoke PhoneCallLog.getParticipant() or ConferencePhoneCallLog.getParticipantAt() toretrieve the call particpant information.

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

Retrieve call information1. Import the required class.

Development Guide Retrieve call information by using call logs

106

Page 109: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

2. Invoke PhoneCall.getElapsedTime() to retrieve the length of time of the current call. InvokePhoneCall.getStatus() to retrieve the connection status for the call. InvokePhoneCall.getDisplayPhoneNumber() to retrieve the phone number of the call. In the following codesample, 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 device1. Import the required class.

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

2. Invoke Phone.getDevicePhoneNumber(), passing in true to return the phone number in its regional format.

String phNumber = Phone.getDevicePhoneNumber(true);

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

Retrieve a call by call ID1. 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);

Development Guide Retrieve the phone number of a BlackBerry device

107

Page 110: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Displaying content on a call screenOn BlackBerry® devices that are running BlackBerry® Device Software 5.0 or later, you can customize the incomingcall screen and active call screen to display content by using the Phone Screen API that is provided in thenet.rim.blackberry.api.phone.phonegui package. For example, you can display information that is providedby 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 acall screen, the device displays each application's content in sequence for approximately two seconds until the nextcall screen appears. For example, if you display content on the incoming call screen, the device displays the contentuntil the user answers the call and the active call screen appears.

The Phone Screen sample application that is included in the BlackBerry® Java® SDK demonstrates how to use this API.

Display content on a phone screenIn the following code sample, custom content is added to the incoming call screen by overridingAbstractPhoneListener.callIncoming(). You can display content on other call screens by overridingcallWaiting(), 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 thesample application. For more information, see the BlackBerry Java Plug-in for Eclipse Development Guide.

1. Import the required classes and interfaces.

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

Development Guide Displaying content on a call screen

108

Page 111: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

2. Create the application framework by extending the Application class. In the constructor, invokePhone.addPhoneListener() to register the listener that is created in step 3. In main(), invokeenterEventDispatcher() 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 invokingScreenModel.getPhoneScreen(). Pass in parameters to specify the call screen orientation and type thatyou 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 parameterPhoneScreen.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 isadded to the incoming call screen by using label fields. Override LabelField.paint() to change the color ofthe 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."){

Development Guide Displaying content on a call screen

109

Page 112: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 thecall screen is used. Invoke PhoneScreen.getCallerInfoFont() to obtain the font that is used by the callscreen. Invoke Field.setFont() and pass in the call screen font to specify the font for the label fields thatwere 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 theincoming call screen.

screenModel.sendAllDataToScreen();

Code sample: Displaying content on a phone screenimport net.rim.blackberry.api.phone.*;import net.rim.blackberry.api.phone.phonegui.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import 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);

Development Guide Displaying content on a call screen

110

Page 113: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 networkThe Phone application on a BlackBerry® device displays the active call screen when a user answers a call or makes acall. After the user answers a call, the user can receive and answer a second call. On devices that operate on a CDMAnetwork, the second call does not invoke the same events that the original call does. For these devices, to displaycustom content on the active call screen, you must override the AbstractPhoneListener.callAnswered()method and AbstractPhoneListener.callWaiting() method.

Method Description

callAnswered() To display content on the first active call screen, overrideAbstractPhoneListener.callAnswered() and obtain call screenobjects for the active call. The Phone application invokes this method whenthe user answers the first call. On devices that operate on a GSM® network,the Phone application invokes this method when the user answers the firstcall and second call.

callWaiting() To display content on the second active call screen, overrideAbstractPhoneListener.callWaiting() and obtain call screenobjects for the active call. The Phone application invokes this method whenthe user answers the second call.

Development Guide Displaying content on a call screen

111

Page 114: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Code sample: Displaying content on devices that operate on a CDMA network

The following code sample demonstrates how to override AbstractPhoneListener.callWaiting(). You cancheck whether the device operates on a CDMA network by using the RadioInfo class. You obtain the instances ofthe active call screen by invoking ScreenModel.getPhoneScreen() and passing in PhoneScreen.ACTIVE sothat 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}

Development Guide Displaying content on a call screen

112

Page 115: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

BlackBerry Browser 11

Retrieve a BlackBerry Browser sessionRetrieving the default session overrides any open sessions on the BlackBerry® device.

1. Import the net.rim.blackberry.api.browser.Browser class.

2. Retrieve the default BrowserSession object by invoking the static method Browser.getDefaultSession().

Retrieve a non-default BlackBerry Browser session1. Import the net.rim.blackberry.api.browser.Browser class.

2. Invoke Browser.getSession(uid), where uid is the browser's service record UID.

Request a web page1. Import the net.rim.blackberry.api.browser.BrowserSession class.

2. 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 deviceapplicationsIn BlackBerry® Java® Development Environment 5.0, the net.rim.device.api.browser.field2 packageprovides 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 providedfunctionality to add web content to a BlackBerry device application. For more information about using this browserfield, 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:

Development Guide BlackBerry Browser

113

Page 116: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

• 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 andbe accessed and invoked by JavaScript code by using the APIs in the net.rim.device.api.script package, whichis 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 thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheBrowserFieldDemoScreen 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. In the screen constructor, create an instance of the BrowserField class.

BrowserField myBrowserField = new BrowserField();

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

add(myBrowserField);

Development Guide Enhanced support for web content in BlackBerry device applications

114

Page 117: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

6. In the screen constructor, invoke BrowserField.displayContent() to specify and display the HTMLcontent.

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 net.rim.device.api.browser.field2.*;import net.rim.device.api.system.*;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 thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheBrowserFieldDemoScreen 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. In the screen constructor, create an instance of the BrowserField class.

BrowserField myBrowserField = new BrowserField();

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

add(myBrowserField);

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

Development Guide Enhanced support for web content in BlackBerry device applications

115

Page 118: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Display HTML content from a resource in your application

1. Import the required classes and interfaces.

import net.rim.device.api.browser.field2.*;import net.rim.device.api.system.*;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 thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheBrowserFieldDemoScreen 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. In the screen constructor, create an instance of the BrowserField class.

BrowserField myBrowserField = new BrowserField();

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

add(myBrowserField);

6. In the screen constructor, invoke BrowserField.requestContent() to specify the location of the resourcein 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 classdisplays the first resource found that matches the specifed file name.

Development Guide Enhanced support for web content in BlackBerry device applications

116

Page 119: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheBrowserFieldDemoScreen 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. In the screen constructor, create an instance of the BrowserFieldConfig class.

BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();

5. In the screen constructor, invoke BrowserFieldConfig.setProperty() to specify a property of theBrowserField. The first parameter in setProperty() specifies the property, and the second parameterspecifies the value of the property. For example, the following code sample specifies the NAVIGATION_MODEproperty 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 youdefined.

BrowserField browserField = new BrowserField(myBrowserFieldConfig);

Development Guide Enhanced support for web content in BlackBerry device applications

117

Page 120: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Send form data to a web address in a browser field

1. Import the required classes and interfaces.

import net.rim.device.api.browser.field2.*;import net.rim.device.api.io.http.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import java.lang.*;import java.util.*;

2. Create the application framework by extending the UiApplication class. In main(), create an instance of thenew class and invoke enterEventDispatcher() to enable the application to receive events. In the applicationconstructor, invoke pushScreen() to display the custom screen for the application. TheBrowserFieldDemoScreen 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. In the screen constructor, create an instance of the BrowserField class.

BrowserField browserField = new BrowserField();

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

add(browserField);

6. In the screen constructor, create a String object that contains the base web address of the web page that youare 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 webpage.

Development Guide Enhanced support for web content in BlackBerry device applications

118

Page 121: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

8. In the screen constructor, create a Hashtable object to store the header information for the form data.

Hashtable header = new Hashtable();

9. 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 pageand display the web page.

browserField.requestContent(baseURL, postData.getBytes(), new HttpHeaders(header));

Development Guide Enhanced support for web content in BlackBerry device applications

119

Page 122: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Menu items 12

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

Create and register a menu itemExtend the ApplicationMenuItem class to define a menu item to display in BlackBerry® Device Softwareapplications.

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 Steps

Define a menu item Extend the ApplicationMenuItem class.

public class SampleMenuItem extends ApplicationMenuItem { ... }

Specify the position of the menuitem in the menu

Construct the ApplicationMenuItem. A higher number in theconstructor 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 menuitem

Implement run().

Development Guide Menu items

120

Page 123: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Create and register a menu item

121

Page 124: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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.

Development Guide Find more information

122

Page 125: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Glossary 14API

application programming interface

BCCblind carbon copy

CCcarbon copy

CRMcustomer relationship management

DTMFDual Tone Multiple-frequency

JSRJava® Specification Request

MIMEMultipurpose Internet Mail Extensions

MEIDMobile Equipment Identifier

MMSMultimedia Messaging Service

PIMpersonal information management

PINpersonal identification number

SMSShort Message Service

SVGScalable Vector Graphics

UCSUniversal Content Stream

Development Guide Glossary

123

Page 126: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

UIDunique identifier

UTFUCS Transformation Format

Development Guide Glossary

124

Page 127: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Provide feedback

125

Page 128: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

Document revision history 16

Date Description

24 September 2010 Changed the following topics:

• 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

10 September 2010 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:

• Code sample: Working with a sensor16 August 2010 Added the following topic:

Development Guide Document revision history

126

Page 129: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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:

• Create a custom field for linked contacts3 August 2010 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

Development Guide Document revision history

127

Page 130: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Development Guide Document revision history

128

Page 131: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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

Eclipse is a trademark of Eclipse Foundation, Inc. Google and YouTube are trademarks of Google Inc. Java andJavaScript are trademarks of Oracle America, Inc. iCal is a trademark of Apple Inc. vCard is a trademark of the InternetMail Consortium. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are the property of their respectiveowners.

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

This documentation might contain references to third-party sources of information, hardware or software, productsor services including components and content such as content protected by copyright and/or third-party web sites(collectively the "Third Party Products and Services"). RIM does not control, and is not responsible for, any ThirdParty Products and Services including, without limitation the content, accuracy, copyright compliance, compatibility,performance, trustworthiness, legality, decency, links, or any other aspect of Third Party Products and Services. Theinclusion of a reference to Third Party Products and Services in this documentation does not imply endorsement byRIM of the Third Party Products and Services or the third party in any way.

EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL CONDITIONS,ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS ORWARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLEQUALITY, NON-INFRINGEMENT, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM ORA COURSE OF DEALING OR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCEOR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICESREFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE ORPROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES ANDCONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THEDOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, AREHEREBY LIMITED TO NINETY (90) DAYS FROM THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEMTHAT IS THE SUBJECT OF THE CLAIM.

Development Guide Legal notice

129

Page 132: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL RIM BELIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICESREFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT,CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL, PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGESFOR LOSS OF PROFITS OR REVENUES, FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSSOF BUSINESS INFORMATION, LOSS OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TOTRANSMIT OR RECEIVE ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITHRIM PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTIONTHEREOF OR OF ANY AIRTIME SERVICES, COST OF SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES,COST OF CAPITAL, OR OTHER SIMILAR PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN ORUNFORESEEN, AND EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

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

THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THECAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO BREACH OF CONTRACT,NEGLIGENCE, TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACHOR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINEDHEREIN; AND (B) TO RIM AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS(INCLUDING AIRTIME SERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICEPROVIDERS) AND THEIR RESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS.

IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY DIRECTOR, EMPLOYEE,AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF RIM OR ANY AFFILIATES OF RIM HAVE ANYLIABILITY ARISING FROM OR RELATED TO THE DOCUMENTATION.

Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to ensurethat your airtime service provider has agreed to support all of their features. Some airtime service providers mightnot offer Internet browsing functionality with a subscription to the BlackBerry® Internet Service. Check with yourservice provider for availability, roaming arrangements, service plans and features. Installation or use of Third PartyProducts and Services with RIM's products and services may require one or more patent, trademark, copyright, orother licenses in order to avoid infringement or violation of third party rights. You are solely responsible fordetermining whether to use Third Party Products and Services and if any third party licenses are required to do so.If required you are responsible for acquiring them. You should not install or use Third Party Products and Servicesuntil all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIM'sproducts and services are provided as a convenience to you and are provided "AS IS" with no express or impliedconditions, endorsements, guarantees, representations, or warranties of any kind by RIM and RIM assumes no liabilitywhatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject toyou agreeing to the terms of separate licenses and other agreements applicable thereto with third parties, exceptto the extent expressly covered by a license or other agreement with RIM.

Development Guide Legal notice

130

Page 133: Blackberry Java SDK Development Guide 1244681 0730085420 001 6.0 US

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 applicablethereto. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY EXPRESS WRITTEN AGREEMENTS ORWARRANTIES PROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THISDOCUMENTATION.

Research In Motion Limited295 Phillip StreetWaterloo, ON N2L 3W8Canada

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

Published in Canada

Development Guide Legal notice

131