Professional Documents
Culture Documents
Contents
1 Integrating with BlackBerry Device Software applications............................................................................... Invoke a BlackBerry Device Software application............................................................................................. 2 Unified search................................................................................................................................................... Making data findable........................................................................................................................................ Exposing your application data.................................................................................................................. Passing queries to other search engines................................................................................................... Define an EntityBasedSearchable class for your SearchableEntity objects...................................................... Customizing the appearance of your data in search results...................................................................... Specify an icon in the EntityBasedSearchable or SearchableEntity class.................................................. Encapsulate your data in the SearchableEntity class........................................................................................ Register your EntityBasedSearchable object with the Unified Search Service................................................. Notify the Unified Search Service about changes to your data........................................................................ Listening for responses from the Unified Search Service................................................................................. Removing your data from the content repository............................................................................................ Using other search engines............................................................................................................................... Ensure that a device runs a single instance of your application....................................................................... Inserting data when a device starts.................................................................................................................. Searching.......................................................................................................................................................... Configure and start a search...................................................................................................................... Process search results................................................................................................................................ 3 Device interaction support............................................................................................................................... Device Capability API........................................................................................................................................ Cradle detection............................................................................................................................................... Cradle handling................................................................................................................................................. Working with sensors on a device.................................................................................................................... Check for a sensor on the device............................................................................................................... Check the state of a sensor....................................................................................................................... Notify an application when the state of a sensor changes........................................................................ Code sample: Working with a sensor........................................................................................................ 4 Message list...................................................................................................................................................... Create a new blank SMS text message............................................................................................................. Create a new populated text message............................................................................................................. Create a new blank MMS message................................................................................................................... Create a new blank email message................................................................................................................... Create a new populated email message........................................................................................................... 6 6 7 7 7 9 10 12 13 13 15 16 16 17 18 20 22 22 22 23 25 25 25 27 28 28 29 30 31 34 34 34 34 35 35
Create a new blank PIN message...................................................................................................................... Create a new populated PIN message.............................................................................................................. Receive a message notification......................................................................................................................... Add a listener to the message store................................................................................................................. Add a listener to the message store for batch updates.................................................................................... Add a listener to a folder.................................................................................................................................. Retrieve the total count of unread email messages in all folders in the store................................................. Open a message................................................................................................................................................ Retrieving the body of an email message......................................................................................................... Retrieve the plain text and HTML content in the body of an email message using a recursive method ................................................................................................................................................................... Retrieve the plain text content of an email message................................................................................ Retrieve the HTML content of an email message...................................................................................... Notify a BlackBerry device application that an email message is about to be sent.......................................... Notify a BlackBerry device application that an MMS message is about to be sent.......................................... Notify a BlackBerry device application that an SMS message is about to be sent........................................... Send a message................................................................................................................................................ Reply to a message........................................................................................................................................... Forward a message........................................................................................................................................... Work with message folders.............................................................................................................................. 5 Custom messages............................................................................................................................................. Using custom messages and folders in the message list.................................................................................. Creating a module for background processes.................................................................................................. Creating a module for the UI............................................................................................................................ Create a module for background processes..................................................................................................... Start the module for background processes or the module for the UI............................................................. Create an icon for a custom message............................................................................................................... Create a custom folder in the message list....................................................................................................... Send a notification when a custom folder changes.......................................................................................... Create a custom indicator................................................................................................................................. Hide an indicator............................................................................................................................................... Remove a custom indicator.............................................................................................................................. 6 Attachments..................................................................................................................................................... Create an attachment handler.......................................................................................................................... Retrieve the contents of an attachment........................................................................................................... Retrieve information about an attachment...................................................................................................... Send a message with an attachment................................................................................................................
35 36 36 37 37 38 38 38 39 40 42 43 46 46 47 47 49 50 51 53 53 53 53 53 54 55 56 57 58 58 59 60 60 61 61 61
Download attachments automatically.............................................................................................................. 7 Calendar............................................................................................................................................................ Open the calendar............................................................................................................................................ View or change a calendar entry...................................................................................................................... Open a new populated calendar entry............................................................................................................. Update calendar entry information.................................................................................................................. Retrieve calendar entry information................................................................................................................ Export a calendar entry.................................................................................................................................... Import a calendar entry.................................................................................................................................... Retrieve multiple lists of calendar entries........................................................................................................ Notify a BlackBerry device application when a list of calendar entries changes.............................................. Notify a BlackBerry device application when the default list of calendar entries changes.............................. Update a calendar entry with no notification................................................................................................... Remove a calendar entry with no notification................................................................................................. 8 Contact list........................................................................................................................................................ Multiple contact lists support........................................................................................................................... Open the contacts application.......................................................................................................................... Open the contacts application by using contact data....................................................................................... Open the contacts application with a specific contact list............................................................................... Create a contact and assign it to a contact list................................................................................................. Retrieve contact information............................................................................................................................ Retrieve a contact list UID................................................................................................................................ Export a contact................................................................................................................................................ Import a contact............................................................................................................................................... Delete a contact................................................................................................................................................ Notify an application when a contact list changes........................................................................................... Creating and removing contact lists................................................................................................................. Create a contact list................................................................................................................................... Remove a contact list................................................................................................................................ Retrieve the contact that is associated with an active call............................................................................... Retrieve the contact that is associated with a completed call......................................................................... Retrieve contacts by phone number................................................................................................................ Linking third-party contacts with contacts in the Contacts application........................................................... Link a contact............................................................................................................................................. Remove a link............................................................................................................................................ Creating menu items for linked contacts................................................................................................... Create menu items for linked contacts.....................................................................................................
62 64 64 64 64 65 67 68 69 69 70 70 71 72 74 74 74 75 75 77 78 79 79 80 81 82 83 83 85 86 87 88 89 90 91 91 92
Create an information provider for a linked contact................................................................................. 9 Task list............................................................................................................................................................. View or change a task....................................................................................................................................... Create a new blank task.................................................................................................................................... Create a new populated task............................................................................................................................ Open a task list................................................................................................................................................. Create a task..................................................................................................................................................... Add task information........................................................................................................................................ Change task information................................................................................................................................... Save a task........................................................................................................................................................ Retrieve task information................................................................................................................................. Export a task..................................................................................................................................................... Import a task..................................................................................................................................................... Delete a task..................................................................................................................................................... Close the task list.............................................................................................................................................. Notify a BlackBerry device application when a list of tasks changes................................................................ 10 Phone................................................................................................................................................................ Making a call from a BlackBerry device application......................................................................................... Make a call from a BlackBerry device application (single-line environment)................................................... Make a call from a BlackBerry device application (multi-line environment).................................................... Add DTMF tones to the send queue................................................................................................................. BlackBerry DTMF tones..................................................................................................................................... Listen for and handle phone events................................................................................................................. Listen for and handle multi-line events............................................................................................................ Retrieve call information by using call logs....................................................................................................... Retrieve a call participant................................................................................................................................. Retrieve call information.................................................................................................................................. Retrieve the phone number of a BlackBerry device......................................................................................... Retrieve a call by call ID.................................................................................................................................... Displaying content on a call screen................................................................................................................... Display content on a phone screen........................................................................................................... Code sample: Displaying content on a phone screen................................................................................ Displaying content on devices that operate on a CDMA network.............................................................
93 96 96 96 96 97 97 98 98 99 99 100 100 101 101 102 103 103 103 103 104 104 104 105 106 106 106 107 107 108 108 110 111
11 BlackBerry Browser........................................................................................................................................... 113 Retrieve a BlackBerry Browser session............................................................................................................. 113 Retrieve a non-default BlackBerry Browser session......................................................................................... 113
Request a web page.......................................................................................................................................... Enhanced support for web content in BlackBerry device applications............................................................ Display HTML content in a browser field................................................................................................... Display HTML content from a web page in a browser field....................................................................... Display HTML content from a resource in your application...................................................................... Configure a browser field.......................................................................................................................... Send form data to a web address in a browser field.................................................................................
12 Menu items....................................................................................................................................................... 120 Adding menu items to BlackBerry Device Software applications..................................................................... 120 Create and register a menu item...................................................................................................................... 120 13 Find more information...................................................................................................................................... 122 14 Glossary............................................................................................................................................................ 123 15 Provide feedback.............................................................................................................................................. 125 16 Document revision history................................................................................................................................ 126 17 Legal notice....................................................................................................................................................... 129
Development Guide
This section describes how to invoke a BlackBerry Device Software application, such as the contacts application, the phone application, and the media application. For more information about integrating your application with BlackBerry Device Software applications, see the Application Integration category overview in the API reference for the BlackBerry Java Development Environment.
2.
Invoke the Invoke.invokeApplication() method and use the appropriate parameters. For example: To start the messages application and create a new blank SMS message, invoke the Invoke.invokeApplication() and use the following parameters: Invoke.APP_TYPE_MESSAGES and a MessageArguments object that uses the ARG_NEW_SMS field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_SMS) );
To start the calendar, invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments). To start the phone application, invoke Invoke.invokeApplication (APP_TYPE_PHONE,PhoneArguments). To start BlackBerry Maps and display the default map view, invoke Invoke.invokeApplication() and provide as parameters Invoke.APP_TYPE_MAPS and a new MapsArguments object.
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments() );
For more information about using the net.rim.blackberry.api.invoke.Invoke class, see the API reference for the BlackBerry Java Development Environment.
Development Guide
Unified search
Unified search
The Unified Search Service is a search engine that is included with BlackBerry Device Software 6.0 and later. BlackBerry device users interact with the Unified Search Service primarily from the Universal search feature by clicking the search icon on the Home screen. Developers can use Unified Search Service through the Unified Search API. You can use the API to include your application data in the Service's content repository, and search the content index from your application. For example, imagine that you have a large collection of books and you loan them to people frequently. It might be useful to create an application that allows you to catalog your books, and keep a list of people to whom you loan them. If this application used the Unified Search API, you could search for a book from the Home screen, or any application, to find the book and contact details for the person who holds it. As a developer, you control whether your data appears in searches that users perform from the Home screen of a BlackBerry device, other applications on the device, or your application only. In addition, you can search data from other applications when that data is registered in the Unified Search Service.
objects.
Description An EntityBasedSearchable object represents your searchable data to the Unified Search Service. When you register your EntityBasedSearchable, the Service requests that your application prepare data for submission by calling EntityBasedSearchable.load (). When your application data is ready for submission, you should invoke completed() on the NotificationListener parameter passed to load(). A SearchableEntity object is the smallest unit of data that an application can submit to the Unified Search Service. Your EntityBasedSearchable object sends your SearchableEntity objects to the Service when asked. You need to encapsulate your application
7
Development Guide
Task
Description data in a SearchableEntity object. The Service indexes the metadata that is exposed by these objects for consideration during search operations. Also, SearchableEntity objects are returned in search results from the Service. The Unified Search Service may need interrupt your load operation if the BlackBerry device is busy, or has a low battery power level. If an interruption is necessary, the Service invokes EntityBasedSearchable.pause(). When the Service detects that your operation can continue, it invokes EntityBasedSearchable.resume(). Respond to these events in a timely manner so that your application does not cause disruption to other applications on the device. After you notify the Unified Search Service that your data is ready, it calls EntityBasedSearchable.getSearchableEntities() to index your data. The Service may invoke load() and getSearchableEntities() again if it detects that its content index and your data are not synchronized. After you prepare your data for search, and define how it will be indexed, you must register your EntityBasedSearchable with the Unified Search Service. Pass your EntityBasedSearchable when you invoke SearchRegistry.register(). The Service then retrieves and indexes your data for inclusion in search results. To notify the content index about changes to your application data, use the insert(), delete(), and update() methods in the AppContentManager object. When you notify the Unified Search Service about changes to your application data, you should provide an AppContentListener object where the Service can notify your application about the result of your request.
Register your
EntityBasedSearchable object
Notify the Unified Search Service about changes to your data. Listening for responses from the Unified Search Service.
The following diagram illustrates the relationship between the components that are used in the previous tasks.
Development Guide
Development Guide
2.
3.
In the constructor, create an array of SearchField objects. Each SearchField stores the name of one searchable property of your data. In the following code sample, the application data objects that are managed by this class have three searchable properties. For example, if your application data modeled books, these fields might include the title, the publisher, and number of pages.
class MyEBS implements EntityBasedSearchable { _searchFields = new SearchField[3];
4.
10
Development Guide
_searchFields[0] = new SearchField("Title"); _searchFields[1] = new SearchField("Publisher"); _searchFields[2] = new SearchField("Number of pages");
5.
6.
Create an icon to appear in search results that include searchable entities managed by this EntityBasedSearchable. For more information about creating icons, see "Customizing the appearance of your data in search results." Implement getType(). Return the content type that best matches your application data. For a list of valid content types, see the net.rim.device.api.unifiedsearch.searchables.SearchableContentTypeConstants interface in the API reference.
public long getType() { return SearchableContentTypeConstants.CONTENT_TYPE_MEMO;
7.
Choose the search initiators that should receive search results from your application. For more information about exposing your data to searches, see net.rim.device.api.unifiedsearch.entity.ExposureLevel class in the API reference.
public int getPrivacyLevel() { return ExposureLevel.LEVEL_PUBLIC; }
8.
Implement load(). If the BlackBerry device is busy, or the battery power level is low, you may need to pause the operation of this method, and resume it when requested. a. For your EntityBasedSearchable, determine how many data objects currently exist in your application.
public void load (NotificationListener observer, int loadType) { Vector myObjects = MyObjectManager.getDataObjects(); if (myObjects != null) { int size = myObjects.size() if(size < 1) { _myEntities = new MySearchableEntity[0]; } else { _myEntities = new MySearchableEntity[size]; } } else { // handle the condition where you have no data objects }
b.
c.
Check whether the Unified Search Service has sent a pause command. If so, pause the operation that populates your arrray of searchable entities and notify the Service.
if (_wait){ try { synchronized(_monitor) { 11
Development Guide
d.
When your application has control of the thread again, continue to populate your array of searchable entities.
MyObject dataObject = (MyObject) objects.nextElement(); _myEntities[count++] = new MySearchableEntity(dataObject, this);
e.
Notify the Unified Search Service that your are done loading your data.
} observer.completed(this, NotificationListener.TYPE_SEARCHABLE);
9.
The Unified Search Service invokes getSearchableEntities() next to retrieve the array you populated. In pause(), change the value of the _wait variable to true. The Unified Search Service calls this method when it wants your application to stop loading data.
public void pause() { _wait = true; }
10. In resume(), change the value of the _wait variable to false. Also, notify the load() method that it can resume execution. The Unified Search Service invokes resume() when it wants your application to resume loading data.
public void resume() { _wait = false; synchronized(_monitor) { _monitor.notifyAll(); } }
11. In getSearchableEntities(), return the _myEntities array that you created in step 8.
public SearchableEntity[] getSearchableEntities() { return _myEntities; }
12
Development Guide
You can also specify an icon for different categories of related searchabe entities. For example, if you create an application that catalogs books you might want to have different icons for different categories of books, such as best sellers, oversized, and first editions. These categories are all types of books, so they would logically fall under one EntityBasedSearchable object that managed books. However, an application that displays them might want to give a visual cue to help a user quickly determine whether to find a book on a regular shelf, a large shelf, or in an environmentally controlled room. In this case, you could create three SearchableEntity classes to wrap three different kinds of book objects, each with its own implementation of getIcon() . All three classes would still be managed by a single EntityBasedSearchable.
2. 3. 4.
Import the graphic into your application from your resource folder.
Bitmap img = Bitmap.getBitmapResource("icon.png")
5.
13
Development Guide
2. 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.length SearchFieldCriteria[] criteria = new SearchFieldCriteria[size]; for (int i = size -1; i >= 0; --i) { criteria[i] = new SearchFieldCriteria(searchfields[i], new String[] {myObject.getProperty(i)}); }
4.
Create and populate a SearchFieldCriteriaList object to hold your search field criteria.
SearchFieldCriteriaList _sfcl = new SearchFieldCriteriaList(); for (int i = size -1; i >= 0; --i) { sfcl.addCriteria(criteria[i]); }
5.
6.
In getData(), return your application data object. To continue with the book example, this method would return an object that represents the book.
public Object getData() { return myObject; }
7.
In getTitle(), assign a title to this searchable entity. The title text appears in search results. To continue with the book example, myObject.getName() could return the name of a book.
public String getTitle() { return myObject.getName(); }
8.
In getSummary() provide a summary of the data in this searchable entity. The summary text appears in search results. Continuing with the book example, myObject.getDescription() could return a description of the book.
public String getSummary() { return myObject.getDescription(); }
14
Development Guide
9.
Implement getSearchable(). Retrieve the EntityBasedSearchable that your application creates to manage this object, and return it.
public Searchable getSearchable() { return myPublisher.getSearchable(); }
10. Define what options should appear on the context menu when a BlackBerry device user clicks on your entity in a list of search results. For more information, see "Specify what users can do with your data in search results". 11. If you want this SearchableEntity to display a different icon than your application icon, provide the icon in getIcon(). For more information, see "Customize the appearance of your data in search results".
2.
3. 4.
Note: The registration token is unique to your EntityBasedSearchable until the BlackBerry device restarts. You should store your registration token and reuse it when you update content using the AppContentManager class.
15
Development Guide
To update a SearchableEntity object that the Unified Search Service has already indexed, invoke updateContent().
public void updateUSS(MyEntity entity, RegistrationToken regToken) { MyEntity[] toUpdate = new MyEntity[1]; toUpdate[0] = entity; AppContentManager.getInstance().updateContent(toUpdate, _myListener, regToken); }
3.
4.
16
Development Guide
17
Development Guide
Approach
Description To remove all data from the content repository for an EntityBasedSearchable, invoke UnifiedSearchServices.removeAllData() and pass the registration token that was returned when that EntityBasedSearchable was registered.
import net.rim.device.api.ui.image.Image; import net.rim.device.api.ui.image.ImageFactory; import net.rim.device.api.unifiedsearch.searchables.ExternalSearchProvider; import net.rim.device.api.unifiedsearch.searchables.SearchableContentTypeConstants; public class MySearchProvider implements ExternalSearchProvider { // A unique registration ID for this provider. private long _regId; // The external search provider icon. private Image _icon; // Constructor public MySearchProvider() { // Read the icon from the resource bundle
18
Development Guide
Bitmap img = Bitmap.getBitmapResource("myicon.png"); if(img != null) { _icon = ImageFactory.createImage(img); } else { _icon = null; }
// The provider name to be displayed. public String getProviderName() { return "Sample External Search Provider"; } // The provider icon to be displayed. public Image getProviderIcon() { return _icon; } // The content type this provider offers. public long getContentType() { return SearchableContentTypeConstants.CONTENT_TYPE_MEDIA_MEMO; } // The search initiator will pass control to your application using this method. public void search(String keywords) { // Create network or IPC connections, send search keywords, and display the results. } // Allows the Unified Search Service and your application to keep track of // this searchable's registration public long getRegistrationID() { return _regId; } public setRegistrationID(long id) { _regId = id; }
19
Development Guide
2.
3.
Retrieve an array of objects that represent the applications that are running on the device.
ApplicationDescriptor[] allApps = ApplicationManager.getApplicationManager ().getVisibleApplications();
4.
Examine each element of the array to determine whether your application is running on the device.
for(int i = allApps.length -1; i >= 0; --i) { if(allApps[i].getModuleHandle() == modHandle) {
5.
If your application is running, send the search keywords to it. Invoke postGlobalEvent() to send your application a message that it should display a screen with the results for the new keywords. You need to detect a global event that is posted to your GUID in your application's constructor, .
int procID = ApplicationManager.getApplicationManager().getProcessId (allApps[i]); ApplicationManager.getApplicationManager().postGlobalEvent(procID, your application's GUID, 0, 0, keywords, null); } }
6.
If your application is not running on the device, retrieve an ApplicationDescriptor object that represents your application.
ApplicationDescriptor[] myAppDes = (modHandle); CodeModuleManager.getApplicationDescriptors
7.
Start your application. Pass the search keywords as an argument. In your application's constructor, you need to detect whether there is an argument that contains search keywords.
try { ApplicationManager.getApplicationManager().runApplication(new ApplicationDescriptor(myAppDes[0], new String[]{keywords})); } catch(ApplicationManagerException e)
20
Development Guide
{ } }
8.
In your application class, import the net.rim.device.api.system.GlobalEventListener package to listen for global events.
import net.rim.device.api.system.GlobalEventListener;
9.
10. Register your application to listen for global events, such as the one that you created in step 5, and display your first screen.
public class MySearchProviderApp extends UiApplication implements GlobalEventListener { public MySearchProviderApp(String searchKeywords) { addGlobalEventListener(this); pushScreen(new MySearchScreen(searchKeywords)); }
12. If your application is running on the device, close the existing screen and display another screen.
if(guid == G53DDE84S97JHVEK390) { if(object0 instanceof String) { popScreen(); pushScreeen(new MySearchScreen((String) object0)); requestForeground(); } }
13. Test for search keywords in the arguments for the main method. Start your application with the keywords that are given, or with an empty string if no keywords are given.
public static void main(String[] args) { String searchKeywords = ""; if(args != null && args.length > 0) { searchKeywords = args[0]; } MySearchProviderApp app = new MySearchProviderApp(searchKeywords); app.enterEventDispatcher(); }
21
Development Guide
Searching
You can use the UnifiedSearchServices class to configure and start a search operation from your application. In the simplest case, you can search all data sources when you submit a keyword to the Unified Search Service. However, you can limit your search to particular searchable data sources, and search fields within those sources. When your search is complete, the Unified Search Service returns a SearchResponse object that contains searchable entities that matched your search criteria. The Service returns the data organized by searchable data source and search field. The structure of the result allows you to look at the metadata that is related to the result. In this way, you can make more detailed decisions about the relevance of search results to your users.
2.
3.
Retrieve a reference to your EntityBasedSearchable object and assign it to an instance variable. When you retrieve a list of searchable applications on the device, change the SearchableContentTypeConstants value to one that is appropriate for your search. Make sure you take some kind of action if your EntityBasedSearchable is not found in the deviceSearchables vector.
MySearchable _searchable = null; Vector deviceSearchables = _uss.getDeviceSearchables (SearchableContentTypeConstants.CONTENT_TYPE_MEMO); for(int i = deviceSearchables.size() -1; i >=0; --i) { if(deviceSearchables.elementAt(i).getName().equals("name of your searchable")) { _searchable = (MySearchable) deviceSearchables.elementAt(i);
22
Development Guide
Searching
4.
Create a method to start the search. Accept the search keyword as a parameter, where your application specifies the search keywords that the BlackBerry device user provides. This method invokes a new thread, so declare the String parameter as final.
private void doSearch(final String keyword) {
5.
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.
8.
After you finish: Implement parseResponse. For more information see "Process search results."
2.
Create an instance variable to store searchable entities to display to the BlackBerry device user.
23
Development Guide
Searching
MySearchableEntity[] _myEntities;
3.
Implement parseResponse. This method runs after your search thread terminates, so declare the SearchResponse parameter as final.
private void parseResponse(final SearchResponse searchResult) {
4.
Configure this method to run when your application regains control of the event thread.
Application.getApplication().invokeLater(new Runnable() { public void run() {
5.
From the search results, retrieve a Hashtable object that contains search fields and searchable entities for your EntityBasedSearchable.
final Hashtable results = searchResult.getSearchResult(_searchable);
6.
Retrieve an Enumeration object that contains the values in the Hashtable, and declare an array to store unique values from the enumeration.
Enumeration values = results.elements(); Object[] searchableEntities;
7. 8.
Iterate through the values enumeration and add unique values to searchableEntities.
while(values.hasMoreElements()) { searchableEntities = (Object[]) values.nextElement(); for(int i = searchableEntities - 1; i >= 0; --i) { if(!Arrays.contains(_myEntities, searchableEntities[i]) { Arrays.add(_myEntities, searchableEntities[i]); } } }
});
The _myEntities array contains a set of unique MySearchableEntity objects that you can use to display the search results to the user.
24
Development Guide
You can query the capabilities of a BlackBerry device by using the Device Capability API that is provided in the net.rim.device.api.system.capability package. You can use the DeviceCapability class to query whether specific features, such as a virtual keyboard or a physical keyboard, are supported on the device, whether the feature is currently available to the BlackBerry device user (for example, if the slider on a device is open and the user can use the physical keyboard), and whether your application can currently access the feature. For example, DeviceCapability.isVirtualKeyboardAvailable() returns true if the device has a virtual keyboard currently displayed. Otherwise the method returns false. You can define a listener to notify your application of changes to the specified capabilities of the device by implementing the DeviceCapabilityListener interface. For an example of how to use the Device Capability API, see Cradle detection. For more information about the Device Capability API, see the API reference for the BlackBerry Java SDK.
Cradle detection
You can detect when a BlackBerry device is connected to a cradle (such as a car kit cradle) by using the DeviceCapability.TYPE_CRADLE capability type that is part of the Device Capability API. You can use DeviceCapability.isSupported() and DeviceCapability.isAvailable() to detect the cradle status. Devices that are running BlackBerry Device Software 6.0 return true for isSupported (DeviceCapability.TYPE_CRADLE). When a device that is running BlackBerry Device Software 6.0 is connected to a cradle, isAvailable(DeviceCapability.TYPE_CRADLE) returns true. When you detect a cradle connection, you can use the CradleProtocol class to detect the cradle type and properties. CradleProtocol is provided in the net.rim.device.api.accessory package. The class provides fields for a cradle's type (such as a car kit cradle, a holster, or a charging pod) and a cradle's properties (such as whether a cradle has a light or buttons that can be changed programmatically).
CradleProtocol.getCradleType() returns the cradle type that the cradle itself provides. A cradle might not provide its precise type. For example, a car kit cradle might return CradleProtocol.TYPE_SIMPLE, instead of CradleProtocol.TYPE_CAR_KIT.
Code sample: Detecting if a device is connected to a cradle The following code sample tests whether the device is connected to a cradle. If it is, the type of cradle is displayed.
import import import import net.rim.device.api.accessory.CradleProtocol; net.rim.device.api.system.capability.DeviceCapability; net.rim.device.api.ui.component.RichTextField; net.rim.device.api.ui.container.MainScreen;
25
Development Guide
Cradle detection
class CradleDemoScreen extends MainScreen { public CradleDemoScreen() { setTitle("Cradle Demo"); RichTextField statusField = new RichTextField(); add(statusField); boolean isConnected = DeviceCapability.isAvailable(DeviceCapability.TYPE_CRADLE); if (isConnected) { CradleProtocol myCradle = CradleProtocol.getInstance(); int cradleType = myCradle.getCradleType(); switch (cradleType) { case CradleProtocol.TYPE_CAR_KIT: statusField.setText("Device is connected to a car kit cradle."); break; case CradleProtocol.TYPE_AUDIO: statusField.setText("Device is connected to an audio cradle."); break; case CradleProtocol.TYPE_BEDSIDE: statusField.setText("Device is connected to a charging pod cradle."); break; case CradleProtocol.TYPE_CHARGER: statusField.setText("Device is connected to a charger cradle."); break; case CradleProtocol.TYPE_DESKTOP: statusField.setText("Device is connected to a desktop cradle."); break; case CradleProtocol.TYPE_HOLSTER: statusField.setText("Device is connected to a holster cradle."); break; case CradleProtocol.TYPE_MULTIMEDIA: statusField.setText("Device is connected to a multimedia cradle."); break; case CradleProtocol.TYPE_SIMPLE: statusField.setText("Device is connected to a simple cradle."); break; default: statusField.setText("Can't determine type of cradle."); } } else { statusField.setText("Device is not connected."); }
26
Development Guide
Cradle handling
Cradle handling
You can register your application as a cradle handler. A cradle handler is an application that can start when a BlackBerry device is connected to a cradle of a specified type. For example, if your application provides local travel information, you might want to register it as a handler for a car kit cradle, so that it can start automatically when the device is connected to a car kit cradle. To register your application as a cradle handler, use CradleHandlerRegistry.registerHandler(). The CradleHandlerRegistry class is provided in the net.rim.blackberry.api.cradle package. When you
register your application, you specify the type of cradle that you want to handle and your application descriptor. Cradle types are defined as fields in the CradleProtocol class that is provided in the net.rim.device.api.accessory package. Registration as a cradle handler is persistent. You need to register your application only once after it is installed on the device. If any handlers are registered for a cradle type, the user is presented with a dialog box when that type of cradle is connected.
The user can select which handler to use, if any, and the selected handler application is started. The user can also indicate that the selected handler application should start automatically the next time the cradle of the specified type is connected.
27
Development Guide
The user can change the cradle handler settings on the device by clicking Options > Third Party Applications on the Home screen. Code sample: Registering a cradle handler The following code sample registers the current application as a handler for car kit cradles.
CradleHandlerRegistry.registerHandler( CradleProtocol.TYPE_CAR_KIT, ApplicationDescriptor.currentApplicationDescriptor());
Invoke Sensor.isSupported() and specify the type of sensor that you want to check for. The sensor types are defined as constants in the Sensor class. The following code sample checks to see whether a device has a slider.
boolean hasSliderSensor; hasSliderSensor = Sensor.isSupported(Sensor.SLIDE);
The method returns true if the device contains the specified sensor, and returns false otherwise. Code sample: Checking for a sensor on the device The following code sample checks whether the device has a holster sensor, slider sensor, or flip sensor.
class SensorDemoScreen extends MainScreen { private RichTextField statusField; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField = new RichTextField();
28
Development Guide
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);
Invoke Sensor.getState() and specify the type of sensor that you want to check. The sensor types are defined as constants in the Sensor class. The following code sample checks the state of the slider on a BlackBerry device.
int sliderState = Sensor.getState(Sensor.SLIDE);
The method returns the sensor's state as an int constant. The constants that can be returned are defined in the Sensor class. You can use the following methods to determine whether the sensor is in a given state: Sensor.isSlideClosed(), Sensor.isSlideOpen(), Sensor.isSlideInTransition(). Code sample: Displaying the state of the device's slider
class SensorDemoScreen extends MainScreen implements SensorListener { private RichTextField statusField; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField = new RichTextField(); add(statusField); if (Sensor.isSupported(Sensor.SLIDE)) { int sliderState = Sensor.getState(Sensor.SLIDE); switch (sliderState) { case Sensor.STATE_SLIDE_CLOSED: // do something if slider is closed statusField.setText("Slider is closed."); break; case Sensor.STATE_SLIDE_IN_TRANSITION: // do something if slider in transition statusField.setText("Slider is between open and closed."); 29
Development Guide
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.");
2.
3.
In the class, implement SensorListener.onSensorUpdate() and perform actions based on the type of sensor (the method's first parameter) and the new state of the sensor (the second parameter). The following code sample checks the state of the slider on a BlackBerry device.
public void onSensorUpdate(int sensorID, int update) { if (sensorID == Sensor.SLIDE) { if (update == Sensor.STATE_SLIDE_OPEN) { // do something if slider is now open statusField.setText("Slider is now open."); } else if (update == Sensor.STATE_SLIDE_IN_TRANSITION) { // do something if slider is now in transition statusField.setText("Slider state is now in transition."); } else if (update == Sensor.STATE_SLIDE_CLOSED) { // do something if slider is now closed statusField.setText("Slider is now closed."); } } }
4.
Invoke SensorListener.addListener() to add the listener to your application. Specify the application, the listener to add, and the types of sensor changes to listen for. The following code sample adds a listener for slider changes to the current application. You can invoke Sensor.removeListener() to remove a listener.
30
Development Guide
5.
To listen for changes to multiple sensors, update the third argument of addListener() to add additional sensor state flags. The following code sample listens for changes to the flip sensor or slider sensor.
Sensor.addListener(Application.getApplication(), this, Sensor.FLIP | Sensor.SLIDE);
Code sample: Listening for changes to the state of the device's slider
class SensorDemoScreen extends MainScreen implements SensorListener { private RichTextField statusField; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField = new RichTextField(); add(statusField); Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE); } public void onSensorUpdate(int sensorID, int update) { if (sensorID == Sensor.SLIDE) { if (update == Sensor.STATE_SLIDE_OPEN) { // do something if slider is now open statusField.setText("Slider is now open."); } else if (update == Sensor.STATE_SLIDE_IN_TRANSITION) { // do something if slider is now in transition statusField2.setText("Slider state is now in transition."); } else if (update == Sensor.STATE_SLIDE_CLOSED) { // do something if slider is now closed statusField.setText("Slider is now closed."); } } }
31
Development Guide
public SensorDemo() { SensorDemoScreen screen = new SensorDemoScreen(); pushScreen(screen); } public static void main(String[] args) { SensorDemo app = new SensorDemo(); app.enterEventDispatcher(); } class SensorDemoScreen extends MainScreen implements SensorListener { private RichTextField statusField1; private RichTextField statusField2; public SensorDemoScreen() { setTitle("Sensor Demo"); statusField1 = new RichTextField(); statusField2 = new RichTextField(); add(statusField1); add(statusField2); // Check for the presence of a sensor boolean hasFlipSensor, hasHolsterSensor, hasSliderSensor; hasFlipSensor = Sensor.isSupported(Sensor.FLIP); hasHolsterSensor = Sensor.isSupported(Sensor.HOLSTER); hasSliderSensor = Sensor.isSupported(Sensor.SLIDE); statusField1.setText("Flip: " + hasFlipSensor + "\nHolster: " + hasHolsterSensor + "\nSlider: " + hasSliderSensor + "\n"); // Check for the state of a sensor if (Sensor.isSupported(Sensor.SLIDE)) { int sliderState = Sensor.getState(Sensor.SLIDE); switch (sliderState) { case Sensor.STATE_SLIDE_CLOSED: // do something if slider is closed statusField2.setText("Slider is closed."); break; case Sensor.STATE_SLIDE_IN_TRANSITION: // do something if slider in transition statusField2.setText("Slider is between open and closed."); break; case Sensor.STATE_SLIDE_OPEN: // do something if slider is open statusField2.setText("Slider is open."); break; default: statusField2.setText("Can't determine state of slider."); } } // Listen for changes to a sensor Sensor.addListener(Application.getApplication(), this, Sensor.SLIDE);
32
Development Guide
} // implementation of SensorListener.onSensorUpdate() // only checks for slider changes public void onSensorUpdate(int sensorID, int update) { if (sensorID == Sensor.SLIDE) { if (update == Sensor.STATE_SLIDE_OPEN) { // do something if slider is now open statusField2.setText("Slider is now open."); } else if (update == Sensor.STATE_SLIDE_IN_TRANSITION) { // do something if slider is now transitioning statusField2.setText("Slider state is changing."); } else if (update == Sensor.STATE_SLIDE_CLOSED) { // do something if slider is now closed statusField2.setText("Slider is now closed."); } } }
33
Development Guide
Message list
Message list
This section describes how to use the messaging capabilities of the BlackBerry device. For more information, see the Messaging category overview in the API reference for the BlackBerry Java Development Environment.
2.
Invoke Invoke.invokeApplication(). Use the following parameters: the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_SMS field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_SMS));
2.
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) );
34
Development Guide
2.
Invoke Invoke.invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_MMS field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_MMS));
2.
Invoke Invoke.invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW));
2.
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));
35
Development Guide
2.
Invoke Invoke.invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_PIN field.
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_PIN));
2.
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));
2. 3.
Check for a ControlledAccessException if your application accesses an object that you do not have permission to access.
36
Development Guide
2.
3.
Within the try-catch block, invoke Session.waitForDefaultSession().getStore() to retrieve the Store object.
try {
4.
Store object.
After the try-catch block, invoke store.addStoreListener() to add a StoreListener instance to the
store.addStoreListener(this);
2.
37
Development Guide
2.
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.
Retrieve the total count of unread email messages in all folders in the store
1. 2. Import the required class.
import net.rim.blackberry.api.mail.Store;
Invoke Store.getUnreadMessageCount().
int numUnread = store.getUnreadMessageCount();
Open a message
1. Import the required classes and interfaces.
import import import import import import java.util.Date; net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store;
2.
38
Development Guide
3. 4.
Invoke folder.getMessages() to retrieve the message objects and store the message objects in a Message array. Iterate through the array and retrieve information, such as the sender and subject, to display to the BlackBerry device user.
Message[] msgs = folder.getMessages();
5.
When a user selects a message from the list, invoke methods on the Message object to retrieve the appropriate fields and body contents to display to the user.
Message msg = msgs[0]; // Retrieve the first message Address[] recipients = msg.getRecipients(Message.RecipientType.TO); Date sent = msg.getSentDate(); Address from = msg.getFrom(); String subject = msg.getSubject(); Object o = msg.getContent(); // Verify that the message is not multipart if ( o instanceof String ) { String body = (String)o; } //...
6.
Invoke Message.getBodyText() on a message to retrieve the plain text contents as a String. If the message does not contain plain text, the method returns null.
39
Development Guide
Retrieve the plain text and HTML content in the body of an email message using a recursive method
Create a recursive method to retrieve all the parts of the body of an email message including plain text and HTML. 1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.mail.MimeBodyPart; net.rim.blackberry.api.mail.Multipart; net.rim.blackberry.api.mail.SupportedAttachmentPart; net.rim.blackberry.api.mail.TextBodyPart; net.rim.blackberry.api.mail.UnsupportedAttachmentPart;
2. 3.
Create local variables that indicate if the BlackBerry Attachment Service supports the message attachment type.
boolean _hasSupportedAttachment; boolean _hasUnsupportedAttachment;
4.
5.
If the method parameter is a Multipart object, the object has multiple BodyPart objects. On each BodyPart object, invoke the recursive method that searches through the body of an email message.
if(obj instanceof Multipart) { _Multipart mp = (Multipart)obj; //Extract all of the parts within the Multipart message. for(int count=0; count < mp.getCount(); ++count) { findEmailBody(mp.getBodyPart(count)); }
6.
If the BodyPart object is a TextBodyPart, retrieve the plain text body of the message.
else if (obj instanceof TextBodyPart) { //This message only has a text body. TextBodyPart tbp = (TextBodyPart) obj; readEmailBody(tbp); }
7. 8.
40
Development Guide
a. b.
If the MimeBodyPart object does not contain attachments, retrieve the body of the message using the MimeBodyPart object as a parameter.
if (mbp.getContentType().indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) { readEmailBody(mbp); }
c.
If the MimeBodyPart object does contain attachments, invoke a method that retrieves the body of the message.
else if (mbp.getContentType().equals(ContentType.TYPE_MULTIPART_MIXED_STRING) || mbp.getContentType().equals (ContentType.TYPE_MULTIPART_ALTERNATIVE_STRING)) { findEmailBody(mbp.getContent()); }
9.
If the BodyPart is an attachment that the BlackBerry Attachment Service supports, change the appropriate local variable to true.
else if (obj instanceof SupportedAttachmentPart) { _hasSupportedAttachment = true; }
10. If the BodyPart is an attachment that the BlackBerry Attachment Service does not support, change the appropriate local variable to true.
else if (obj instanceof UnsupportedAttachmentPart) { _hasUnsupportedAttachment = true; }
Development Guide
} 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; }
2. 3.
Cast the value that TextBodyPart.getContent() returns as a String to get the plain text part of the body of the message.
_plainTextMessage = (String)tbp.getContent();
42
Development Guide
4.
Invoke TextBodyPart.hasMore() and TextBodyPart.moreRequestSent() to identify if more of the TextBodyPart object is available on the server.
if (tbp.hasMore() && !tbp.moreRequestSent()) {
5.
If more data is available for the TextBodyPart object, invoke Transport.more() to retrieve the rest of the TextBodyPart object.
Transport.more((BodyPart)tbp, true);
2.
3.
Invoke MimeBodyPart.getContent() and MimeBodyPart.getContentType() to retrieve the content of the MimeBodyPart object.
Object obj = mbp.getContent(); String mimeType = mbp.getContentType();
4.
Create a String variable to hold the String representation of the MimeBodyPart object.
43
Development Guide
5.
If the BlackBerry device can convert the HTML body of a message to a String, the MimeBodyPart object will be a String. Cast the MimeBodyPart object as a String and assign it to the String representation of the body part of the message.
if (obj instanceof String) { body = (String)obj; }
6.
If the BlackBerry device cannot convert the HTML body of a message to a String, the MimeBodyPart object will be a byte array. Create a new instance of String using as a parameter the MimeBodyPart object cast as a byte array. Assign the String to the String representation of the body part of the message.
else if (obj instanceof byte[]) { body = new String((byte[])obj); }
7.
Check to see if the String representation of the content of the MimeBodyPart object contains ContentType.TYPE_TEXT_PLAIN_STRING to determine if the MimeBodyPart object is the plain text body part of the message.
if (mimeType.indexOf(ContentType.TYPE_TEXT_PLAIN_STRING) != -1) {
8.
Invoke MimeBodyPart.hasMore() and MimeBodyPart.moreRequestSent() to determine if all of the text body part is present in the MimeBodyPart object.
if (mbp.hasMore() && !mbp.moreRequestSent()) {
9.
If more data is available for the MimeBodyPart object, invoke Transport.more() to retrieve the rest of the data for the MimeBodyPart object.
Transport.more((BodyPart)mbp, true);
10. Check to see if the String representation of the content of the MimeBodyPart object contains ContentType.TYPE_TEXT_HTML_STRING to detemine if the MimeBodyPart object is the HTML body part of the message.
else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) {
11. Invoke MimeBodyPart.hasMore() and MimeBodyPart.moreRequestSent() to determine if all of the HTML body part is present in the MimeBodyPart object.
if (mbp.hasMore() && !mbp.moreRequestSent()) {
12. If more data is available for the MimeBodyPart object, invoke Transport.more() to retrieve the rest of the MimeBodyPart object.
44
Development Guide
Transport.more((BodyPart)mbp, true);
if (mimeType.indexOf(ContentType.TYPE_TEXT_PLAIN_STRING) != -1) { _plainTextMessage = body; //Determine if all of the text body part is present. if (mbp.hasMore() && !mbp.moreRequestSent()) { try { Transport.more((BodyPart)mbp, true); } catch (Exception ex) { Dialog.alert("Exception: " + ex.toString()); } }
else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) { _htmlMessage = body; //Determine if all of the HTML body part is present. if (mbp.hasMore() && !mbp.moreRequestSent()) { try { Transport.more((BodyPart)mbp, true); } catch (Exception ex) { Dialog.alert("Exception: " + ex.toString()); }
45
Development Guide
2. 3. 4.
5.
6.
2.
46
Development Guide
3. 4.
2. 3. 4.
Add a SendListener.
SMS.addSendListener(smsSL);
Send a message
1. Import the required classes and interfaces.
import import import import import import import import net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.AddressException; net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.MessagingException; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store; net.rim.blackberry.api.mail.Transport;
2. 3.
4.
Development Guide
Send a message
5.
6.
7. 8.
Invoke Message.addRecipients() and provide the type of recipient (TO, CC, or BCC) and the array of addresses to add as parameters to the method. If the message has multiple types of recipients, invoke Message.addRecipients() once for each recipient type.
msg.addRecipients(Message.RecipientType.TO, toList);
9.
Invoke Message.setFrom(Address).
Address from = new Address("ming.li@example.com", "Ming Li"); msg.setFrom(from);
11. Invoke Message.setContent(String). (Typically, the BlackBerry device application retrieves content from text that a BlackBerry device user types in a field.)
try {
12. Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();
trans.send(msg); } catch(MessagingException e)
48
Development Guide
Reply to a message
{ }
System.out.println(e.getMessage());
Reply to a message
1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.mail.Folder; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Store; net.rim.blackberry.api.mail.Transport;
2.
Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();
3. 4. 5. 6.
Invoke Store.list(INBOX) to retrieve all the folders in the INBOX folder. Store the folders in a Folder array.
Folder[] folders = store.list(INBOX);
Invoke Folder.getMessages() to retrieve the messages in the inbox folder. Store the messages in a Message array.
Message[] messages = inbox.getMessages();
7.
Invoke Message.reply(Boolean) and specify true to reply to all message recipients or false to reply to only the sender.
if( messages.length > 0 ) { Message msg = messages[0]; } Message reply = msg.reply(true);
8.
49
Development Guide
Forward a message
Forward a message
1. Import the required classes and interfaces.
import import import import import net.rim.blackberry.api.mail.Address; net.rim.blackberry.api.mail.Message; net.rim.blackberry.api.mail.MessagingException; net.rim.blackberry.api.mail.Session; net.rim.blackberry.api.mail.Transport;
2.
Invoke Message.forward() on an existing Message object. The subject line of a forwarded message is set automatically to FW:original_subject.
Message fwdmsg = msg.forward();
3. 4. 5. 6.
Invoke Message,setContent(String) to set the content of the message that appears before the original message.
try {
7.
Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();
8.
Invoke Transport.send(Message).
try {
50
Development Guide
2. 3.
Complete any of the following actions: Task Open a folder view Steps a. Retrieve a list of folders.
Store store = null; store = Session.waitForDefaultSession().getStore(); Folder[] folders = store.list();
b.
Invoke Store.list().
Folder[] folders = store.list();
Invoke Store.findFolder(String).
Folder[] folders = store.findFolder("Inbox");
Invoke Store.getFolder(String) and provide as a parameter the absolute path to the folder.
51
Development Guide
Task
Steps
Folder folder = store.getFolder("Mailbox - Yan Wang/Inbox/ Projects");
Create code to manage a FolderNotFoundException exception if the folder does not exist. Invoke Folder.getID() to retrieve the folder ID. Invoke Store.getFolder() with the ID as a parameter.
Folder[] folders = store.list(); long id = folders[0].getId(); Folder f2 = store.getFolder(id);
File a message
52
Development Guide
Custom messages
Custom messages
Using custom messages and folders in the message list
You can use the net.rim.blackberry.api.messagelist package to create custom messages and folders for a BlackBerry device application. To use custom folders and messages in an application, you must create an application with the following modules: A UI module to interact with a BlackBerry device user A service module to interact with an application server and perform other actions in the background
Both modules are part of the same application but have different application entry points. You must determine the functionality that is part of each module. For example, a menu item that lets the user delete a message or mark a message as read should be part of the service module. A menu item that lets the user open or reply to a message should be part of the UI module. See the Message List Demo sample application that is included in the BlackBerry Java SDK for a demonstration on how to use this API.
53
Development Guide
Start the module for background processes or the module for the UI
2. 3. 4.
Create a class with the fields and methods for the module. Compile the project into a .jad file. Include the .jad file with the .jad files for the UI module and the main part of the application.
Start the module for background processes or the module for the UI
1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*;
3.
In main(), check if the value of the args parameter indicates that the application should start the service module or the UI module.
if( args.length == 1 && args[ 0 ].equals( "service" ) ) { } } else if( args.length == 1 && args[ 0 ].equals( "gui" ) ) { }
4.
If the application should start the service module, in the first if statement, create an instance of a class that contains the service functionality and items. Obtain a reference to an ApplicationMessageFolderRegistry object.
MLSampleService service = new MLSampleService(); ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();
5.
If the application should start the UI module, in the else if statement, create an instance of a class that contains the UI functionality and items. For example, the UI module should start if the BlackBerry device user clicks the application icon on the Home screen or opens a custom message in the Messages application. Display the UI for the application and add the application to the event dispatcher.
MLSampleGui gui = new MLSampleGui(); gui.showGui(); gui.enterEventDispatcher();
Code sample: Starting the module for background processes or the module for the UI
import net.rim.blackberry.api.messagelist.*; public static void main( String[] args ) { try 54
Development Guide
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(); }
2.
Invoke EncodedImage.getEncodedImageResource() to create an icon based on an encoded image. Pass in the file name as an argument.
ApplicationIcon newIcon = new ApplicationIcon( EncodedImage.getEncodedImageResource( "ml_sample_new.png" ) ); ApplicationIcon openedIcon = new ApplicationIcon( EncodedImage.getEncodedImageResource ( "ml_sample_opened.png" ) );
3.
Invoke ApplicationMessageFolderRegistry.registerMessageIcon() to assign a status and an icon to a custom message. Specify the following as arguments: a value for the message type for a BlackBerry device application, a message status by using a field from the ApplicationMessage.Status interface, and an instance of the ApplicationIcon class.
int MESSAGE_TYPE = 0; int STATUS_NEW = ApplicationMessage.Status.UNOPENED; int STATUS_OPENED = ApplicationMessage.Status.OPENED; reg.registerMessageIcon( MESSAGE_TYPE, STATUS_NEW, newIcon ); reg.registerMessageIcon( MESSAGE_TYPE, STATUS_OPENED, openedIcon );
55
Development Guide
2. 3.
4.
5.
Invoke ApplicationMessageFolder.addListener() to add a listener so that your application can be notified when specific folder events occur. In the following code sample, the application listens for deleted messages. For a list of all actions that you can listen for, see the documentation for the ApplicationMessageFolderListener class in the API reference for the BlackBerry Java SDK.
deletedFolder.addListener( this, ApplicationMessageFolderListener.MESSAGE_DELETED );
6.
7.
56
Development Guide
// check if action was performed on multiple messages if( messages.length == 1 ) { switch( action ) { case ApplicationMessageFolderListener.MESSAGE_DELETED: messageStore.deleteInboxMessage( message ); ...
8.
Invoke ApplicationMessageFolderRegistry.setRootFolderName() to specify the name of the root folder for your application's custom folders. The name of the root folder appears in the View Folder dialog box of the Messages application when an application registers more than one application message folder.
reg.setRootFolderName( "ML Sample" );
3.
Invoke ApplicationMessageFolder.fireElementRemoved() to notify an application when a message is removed from a custom folder.
inboxFolder.fireElementRemoved( deletedMessage );
4.
5.
Invoke ApplicationMessageFolder.fireReset() to notify an application when more than one message in a custom folder changes.
inboxFolder.fireReset();
57
Development Guide
2.
3.
Create an indicator based on an encoded image by invoking EncodedImage.getEncodedImageResource () and passing in the file name as an argument. Save a reference to the encoded image in an EncodedImage variable. Create an instance of the ApplicationIcon class using the EncodedImage as an argument.
EncodedImage image = EncodedImage.getEncodedImageResource( "clowds.gif" ); ApplicationIcon icon = new ApplicationIcon( image );
4.
Register the icon as an application indicator by invoking ApplicationIndicatorRegistry.register(). In the following code sample, the second parameter specifies that the indicator can have a numeric value associated with it (for example, new message count). The third parameter specifies that the indicator should be visible.
ApplicationIndicator indicator = reg.register( icon, false, true);
5.
ApplicationIndicatorRegistry.getApplicationIndicator(). Save the return value in an ApplicationIndicator variable. ApplicationIndicator appIndicator = reg.getApplicationIndicator();
6.
Set the icon and value for the indicator by invoking ApplicationIndicator.set(). You should consider only showing a value if it is greater than 0.
appIndicator.set( newIcon, newValue );
Hide an indicator
1. Import the required classes and interfaces.
import net.rim.blackberry.api.messagelist.*;
58
Development Guide
2.
To temporarily hide an indicator, invoke ApplicationIndicator.setVisible() and provide false as the argument.
appIndicator.setVisible( false );
59
Development Guide
Attachments
Attachments
You can use the Mail API in the net.rim.blackberry.api.mail package to manage attachments in incoming email messages and include attachments in outgoing email messages on a BlackBerry device. An attachment is represented as a separate BodyPart object on a Multipart message.
2. 3.
Implement the supports(String) method, to specify the content type of the attachment supported by your handler.
public boolean supports(String contentType) { return (contentType.toLowerCase().indexOf("contenttype") != -1 ? true : false); }
4.
Implement the menuString() method, to specify the text of the menu item that displays when a user selects an attachment.
public String menuString() { return "Custom Attachment Viewer"; }
5.
Implement the run() method to specify what should happen when a user clicks the menu item. In the following code sample, a new screen uses the RichTextField class to display a String representation of the content of the attachment.
public void run(Message m, SupportedAttachmentPart p) { MainScreen view = new MainScreen(); view.setTitle("Attachment Viewer"); view.add(new RichTextField(new String((byte[])p.getContent()))); }
60
Development Guide
6.
Invoke AttachmentHandlerManager.addAttachmentHandler(), to register the attachment handler with the manager. Note that the attachment name must be prefixed with "x-rimdevice" for the attachment to be sent and stored on the BlackBerry device.
AttachmentHandlerManager m = AttachmentHandlerManager.getInstance(); CustomAttachmentHandler ah = new CustomAttachmentHandler(); m.addAttachmentHandler(ah);
2.
3.
Create a SupportedAttachmentPart object, designating the Multipart object as its parent, to create each component of the screen.
SupportedAttachmentPart attach = new SupportedAttachmentPart( multipart, "application/x-example", "filename", data);
4.
61
Development Guide
multipart.addBodyPart(attach);
5.
Invoke Message.setContent(Multipart) and provide as a parameter the Multipart object to set the content of the attachment.
msg.setContent(multipart);
6.
Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
Transport trans = Session.getTransport();
7.
Invoke Transport.send(Message).
try {
The AttachmentDownloadManager.download() method performs verification during the download process. If verification errors are found, the method throws an exception. For a list of possible verification errors, see the API reference for the BlackBerry Java Development Environment. Note: The BlackBerry Attachment Service receives all attachments first. Third-party attachment handlers cannot override this default behavior. For more information about the BlackBerry Attachment Service, see the BlackBerry Enterprise Server Administration Guide. 1. Import the required classes and interfaces.
import java.io.IOException; import net.rim.blackberry.api.mail.*;
62
Development Guide
2.
3.
Use the methods available in AttachmentDownloadManager to determine information about the attachment.
public public public public String String String String fileSize fileName fileType filePath = = = = getFileSize(BodyPart bodyPart); getFileName(BodyPart bodyPart); getFileContentType(BodyPart bodyPart); getDownloadedFileName(BodyPart bodyPart);
4. 5.
Override the DownloadProgressListener callback methods, to provide updates about the status of the download of the attachment.
private void downloadCancelled(String msg) { BodyPart bodyPart = (BodyPart) element; _screen.displayProgress("Failed to download " + _adm.getFileName(bodyPart)); } private void downloadCompleted(Object element) { BodyPart bodyPart = (BodyPart) element; _screen.displayProgress(_adm.getFileName(bodyPart) + " downloaded."); } public void updateProgress(Object element, int current, int total) { }
63
Development Guide
Calendar
Calendar
Open the calendar
1. Import the required classes and interfaces.
import net.rim.blackberry.api.invoke.CalendarArguments; import net.rim.blackberry.api.invoke.Invoke; import net.rim.device.api.system.ControlledAccessException;
2. 3.
Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments). Check for a ControlledAccessException if your application does not have permission to access the application that it invokes.
2.
3.
Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments) using the CalendarArguments object created using the ARG_VIEW_DEFAULT field and the retrieved Event.
Invoke.invokeApplication( Invoke.APP_TYPE_CALENDAR, new CalendarArguments ( CalendarArguments.ARG_VIEW_DEFAULT, e ) );
4.
Check for a ControlledAccessException if your application does not have permission to access the application that it invokes.
Development Guide
2.
3.
4.
Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments) using the CalendarArguments object created using the ARG_NEW field and the Event.
Invoke.invokeApplication( Invoke.APP_TYPE_CALENDAR, new CalendarArguments ( CalendarArguments.ARG_NEW, e ) );
2.
Invoke openPIMList() to open a list of calendar entries. Provide the following as parameters: the type of list to open (PIM.EVENT_LIST) and the mode in which to open the list: READ_WRITE READ_ONLY WRITE_ONLY
EventList eventList = null; try { eventList = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); } catch (PimException e) { // Handle exception. }
3.
65
Development Guide
a.
Create a RepeatRule object. The RepeatRule class defines fields for the properties and values that you can set, such as COUNT, FREQUENCY, and INTERVAL. Invoke RepeatRule.getFields() to retrieve an array of supported fields.
b.
66
Development Guide
Task
d.
a. b. c.
Invoke the appropriate set method, such as setString() to replace an existing value with a new one. Invoke Event.countValues() to determine if a value is already set for the field. Use the corresponding set method, such as setString() to change an existing value.
if (event.countValues(Event.LOCATION) > 0) { event.setString(Event.LOCATION, 0, Event.ATTR_NONE, "Board Room"); }
Save an appointment
a.
Before you save the appointment, to identify appointment fields that have changed since the appointment was last saved, invoke Event.isModified(). Invoke Event.commit().
if(event.isModified()) { event.commit(); }
b.
67
Development Guide
2.
3.
Invoke PIMItem.getFields() to retrieve an array of IDs of fields that have data for a particular task. Invoke PIMItem.getString() to retrieve the field values.
while (e.hasMoreElements()) { Event event = (Event)e.nextElement(); int[] fieldIds = event.getFields(); int id; for(int index = 0; index < fieldIds.length; ++index) { id = fieldIds[index]; if(e.getPIMList().getFieldDataType(id) == STRING) { for(int j=0; j < event.countValues(id); ++j) { String value = event.getString(id, j); System.out.println(event.getFieldLable(id) + "=" + value); } } } }
2.
Invoke PIM.supportedSerialFormats() specifying the list type (PIM.EVENT_LIST), to retrieve a string array of supported serial formats.
String[] dataFormats = PIM.supportedSerialFormats(PIM.EVENT_LIST);
3. 4.
Use an output stream writer to export calendar entries from the BlackBerry device to a supported serial format, such as iCal. Invoke toSerialFormat() to write an item in serial format. The enc parameter specifies the character encoding to use when writing to the output stream. Supported character encodings include UTF8, ISO-8859-1, and UTF-16BE. This parameter cannot be null.
68
Development Guide
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]); }
2. 3.
Invoke PIM.getInstance().fromSerialFormat() to return an array of PIMItem objects. Invoke EventList.importEvent() to add a new calendar entry.
// Convert an existing entry into a iCal and then // import the iCal as a new entry String[] dataFormats = PIM.supportedSerialFormats(); // Write entry to iCal ByteArrayOutputStream os = new ByteArrayOutputStream(); PIM.getInstance().toSerialFormat(event, os, "UTF8", dataFormats[0]); // Import entry from iCal ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); PIMItem[] pi = PIM.getInstance().fromSerialFormat(is, "UTF8"); EventList eventList = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); Event event2 = eventList.importEvent((Event)pi[0]);
69
Development Guide
2. 3.
Notify a BlackBerry device application when the default list of calendar entries changes
When an update occurs to the list of services on a BlackBerry device, the list of PIM databases on a device may change. This action may result in the creation of a new default list of calendar entries. 1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import net.rim.blackberry.api.pdap.BlackBerryPIM; import net.rim.blackberry.api.pdap.ListChangeListener;
2. 3.
4.
To have the application always use the default PIMList, store a reference to the desired PIMList and design the ListChangeListener.defaultListChanged() method to update the reference when the default list changes.
70
Development Guide
2.
3.
4.
5.
Invoke BlackBerryPIMItem.commit() and specify the flag BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES to save your changes.
if(event.isModified()) { try { int result; result = ((BlackBerryPIMItem) event).commit(BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES); } catch (PIMException e) { // Handle exception } }
71
Development Guide
If you specify BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES when committing changes to a calendar entry, notification is not sent unless the calendar entry is a new meeting or meeting participants have been added since the last update (meeting participants must be notified about the meeting in order to accept the meeting invitation). If notification was sent, BlackBerryPIMItem.commit() returns BlackBerryEvent.MEETING_RECORD_NOT_FOUND or BlackBerryEvent.INVITEE_LIST_CHANGED. Code sample
BlackBerryEventList eventList = null; try { eventList = (BlackBerryEventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); Enumeration events = eventList.items(); BlackBerryEvent event = (BlackBerryEvent) events.nextElement(); if (eventList.isSupportedField(Event.SUMMARY)) { event.addString(Event.NOTE, Event.ATTR_NONE, "Remember to bring food"); } if(event.isModified()) { int result; result = ((BlackBerryPIMItem) event).commit(BlackBerryEvent .DO_NOT_NOTIFY_ATTENDEES); }
2.
72
Development Guide
3.
4.
Invoke BlackBerryEventList.removeElement() and specify the flag BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES to remove the entry without notification.
try {
If an error occurs when you try to remove the event, the method throws a PIMException. Code sample
BlackBerryEventList eventList = null; try { eventList = (BlackBerryEventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); Enumeration events = eventList.items(); BlackBerryEvent event = (BlackBerryEvent) events.nextElement(); eventList.removeEvent(event, BlackBerryEvent.DO_NOT_NOTIFY_ATTENDEES); } catch (PIMException e) { // Handle exception }
73
Development Guide
Contact list
Contact list
You can use an instance of the ContactList class or BlackBerryContactList class in your application to add and view contact information in the contacts application on the BlackBerry device. You can create Contact or BlackBerryContact objects to store information for individual contacts such as the name, phone number, email address, and street address. Your application can perform tasks such as adding, deleting, and changing contact list entries.
2.
74
Development Guide
3.
Check for a ControlledAccessException if your application does not have permission to access the application that it invokes.
2.
Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList(int, int) to open the default contact list, passing in as parameters the type of list to open (PIM.CONTACT_LIST) and the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). To open a named contact list, you can instead invoke PIM.openPIMList(int, int, String).
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
3. 4. 5.
Invoke Invoke.invokeApplication(APP_TYPE_ADDRESSBOOK, AddressBookArguments) and use the AddressBookArguments object for the contact.
Invoke.invokeApplication(Invoke.APP_TYPE_ADDRESSBOOK, abArg);
6.
Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.
75
Development Guide
2.
Invoke PIM.listPIMLists(int pimListType) to return an array of String objects. The returned array provides the system-assigned names, one for each PIM list of the specified type. The default list of the specified type is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);
3. 4. 5.
Iterate over the array that is returned from PIM.listPIMLists() to search for the system-assigned name for the contact list that you want to display. Invoke BlackBerryPIMList.getPIMListUID() to return the UID for contact list.
long uid = cl.getPIMListUID();
Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList(int, int, long) to open the contact list, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the UID.
BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, uid);
6.
7.
Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.
76
Development Guide
2.
To add the new contact to the default contact list, invoke PIM.openPIMList(int, int) to open the default contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST) and the PIM.READ_WRITE access mode. Proceed to step 4.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
3.
To add the new contact to a contact list that is not the default contact list, perform the following actions: a. Invoke PIM.listPIMLists(int), passing in as the parameter the type of list (PIM.CONTACT_LIST), to return an array of String objects. The returned array provides the system-assigned names for each contact list. The default contact list is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);
b. c.
Iterate over the array that PIM.listPIMLists() returns to search for the system-assigned name for the contact list that you want to open. Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the PIM.READ_WRITE access mode, and the contact list name.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);
4. 5.
Invoke one or more of the following methods to add information for the new contact. For more information about PIMItem methods, see the API reference for the BlackBerry Java Development Environment. addString() addStringArray() addDate() addInt() addBoolean() addBinary()
77
Development Guide
6.
Invoke the following methods to verify that the information meets the size requirements and type requirements for the specified contact field. Invoke ContactList.isSupportedField(int) to verify that the item supports the field type. Invoke ContactList.isSupportedAttribute(int, int) to verify that the field supports the specified attribute. Invoke PIMList.maxValues(int field) to verify the number of values that the field supports. Invoke Contact.commit() to commit the changes.
if(contact.isModified()) { contact.commit(); }
7.
8.
Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.
2.
Invoke PIM.getInstance() to retrieve a PIM instance, and invoke PIM.openPIMList() to open a contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the name if you are not opening the default contact list.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
3. 4.
Invoke one of the PIMItem getter methods to retrieve contact information. To retrieve an array of fields that contain the data for a specified contact, invoke PIMItem.getFields(). To retrieve a String that represents the value for a specified contact field, invoke PIMItem.getString (int field, int index).
78
Development Guide
To retrieve a date that represents the value for a specified contact field, invoke PIMItem.getDate(int field, int index).
while (_enum.hasMoreElements()) { BlackBerryContact c = (BlackBerryContact)_enum.nextElement(); int[] fieldIds = c.getFields(); int id; for(int index = 0; index < fieldIds.length; ++index) { id = fieldIds[index]; if(c.getPIMList().getFieldDataType(id) == BlackBerryContact.STRING) { for(int j=0; j < c.countValues(id); ++j) { String value = c.getString(id, j); System.out.println(c.getPIMList().getFieldLabel(id) + "=" + value); } } } }
2. 3.
Access the contact list that you want to work with. Invoke BlackBerryPIMList.getPIMListUID() to retrieve the UID of the contact list.
long uid = list.getPIMListUID();
Export a contact
You can export contact information from a contact list on a BlackBerry device to an output stream. The export process converts a PIM item to a stream of bytes that another application can import. You can export PIM data to a supported serial format by invoking PIM.toSerialFormat(PIMItem, OutputStream, String, String),
79
Development Guide
Import a contact
and passing in as arguments the PIMItem, the OutputStream to which the serialized PIMItem is written, the character encoding format to use when writing to the output stream, and the supported serial format to convert to, such as vCard. 1. Import the required classes and interfaces.
import import import import import import java.io.UnsupportedEncodingException; java.util.Enumeration; javax.microedition.pim.Contact; javax.microedition.pim.ContactList; javax.microedition.pim.PIM; javax.microedition.pim.PIMException;
2.
Invoke PIM.supportedSerialFormats() and specify the list type (PIM.CONTACT_LIST) to retrieve a string array of the supported serial formats.
ContactList contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); String[] dataFormats = PIM.getInstance().supportedSerialFormats(PIM.CONTACT_LIST);
3.
Invoke PIM.getInstance().toSerialFormat(item, stream, enc, dataFormat)to write an item to a supported serial format. Use the enc parameter to specify the character encoding format to use when writing to the output stream. Supported character encoding formats include UTF8, ISO-8859-1, and UTF-16BE. If the enc parameter is null, the method uses UTF-8.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Enumeration e = contactList.items(); while (e.hasMoreElements()) { try { Contact c = (Contact)e.nextElement(); PIM.getInstance().toSerialFormat(c, byteStream, "UTF8", dataFormats[0]); } catch (UnsupportedEncodingException ex) { System.out.println(ex.toString()); } }
Import a contact
You can import contact information from a compatible input stream to a contact list on a BlackBerry device. You can import contact information by invoking fromSerialFormat(InputStream, String), and passing in as arguments the InputStream from which the PIMItem is written and the character encoding format to use. Supported character encoding formats include UTF8, ISO-8859-1, and UTF-16BE. 1. Import the required classes and interfaces.
80
Development Guide
Delete a contact
2.
3.
Open a contact list and invoke ContactList.importContact() to create a new contact by using a PIM item.
ContactList contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); Contact contact2 = contactList.importContact((Contact) pi[0]); contact2.commit();
Delete a contact
You can delete a contact from the default contact list or another contact list on a BlackBerry device. 1. Import the required classes and interfaces.
import import import import import import import net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryPIMList; net.rim.device.api.system.ControlledAccessException; javax.microedition.pim.Contact; javax.microedition.pim.ContactList; javax.microedition.pim.PIM; javax.microedition.pim.PIMException;
2.
To delete a contact from the default contact list, invoke PIM.openPIMList(int, int) to open the default contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), and the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). Proceed to step 4.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
3.
To delete a contact from a contact list that is not the default contact list, perform the following actions: a. Invoke listPIMLists(int pimListType) to return an array of String objects. The returned array provides the system-assigned name for each contact list. The default contact list is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);
b.
Iterate over the array that PIM.listPIMLists() returns to search for the system-assigned name for the contact list that you want to delete.
81
Development Guide
c.
Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the contact list name.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);
4. 5.
Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.
2.
To receive change notifications for the default contact list, invoke PIM.openPIMList(int, int) to open the default contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), and the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY). Proceed to step 4.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
3.
To receive change notifications for a contact list that is not the default contact list, perform the following actions: a. Invoke listPIMLists(int), passing in as the parameter the type of list to open (PIM.CONTACT_LIST), to return an array of String objects. The returned array provides the system-assigned name for each contact list. The default contact list is returned at index 0 of the array.
String[] lists = PIM.listPIMLists(PIM.CONTACT_LIST);
b.
Iterate over the array that PIM.listPIMLists() returns to search for the system-assigned name for the contact list that you want to receive change notifications for.
82
Development Guide
c.
Invoke PIM.openPIMList(int, int, String) to open the contact list instance, passing in as parameters the type of list to open (PIM.CONTACT_LIST), the access mode with which to open the list (PIM.READ_WRITE, PIM.READ_ONLY, or PIM.WRITE_ONLY), and the contact list name.
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, name);
4. 5.
Override the PIMListListener.itemAdded(), PIMListListener.itemUpdated(), and PIMListListener.itemRemoved() methods to configure the notification behavior.
public void itemAdded(PIMItem item) { System.out.println("ITEM ADDED: " + (BlackBerryContact) item.getString(BlackBerryContact.UID, 0)); } public void itemUpdated(PIMItem oldItem, PIMItem newItem) { System.out.println("ITEM UPDATED: " + (BlackBerryContact) oldItem.getString(BlackBerryContact.UID, 0) + " to " + (BlackBerryContact) newItem.getString(Contact.UID, 0)); } public void itemRemoved(PIMItem item) { System.out.println("ITEM REMOVED: " + (BlackBerryContact) item.getString(BlackBerryContact.UID, 0)); }
6.
Check for PIMException, and check for ControlledAccessException if your application does not have permission to access the application that it invokes.
83
Development Guide
1.
Applications can register to listen for changes to your contact list by invoking BlackBerryPIMList.addListener(). Import the required classes and interfaces.
import import import import import import import import javax.microedition.pim.Contact; javax.microedition.pim.PIM; javax.microedition.pim.PIMException; javax.microedition.pim.PIMItem; net.rim.blackberry.api.pdap.BlackBerryContact; net.rim.blackberry.api.pdap.BlackBerryContactList; net.rim.blackberry.api.pdap.BlackBerryPIM; net.rim.blackberry.api.pdap.BlackBerryPIMList;
2. 3.
4.
The contact list is named using the name that you provide ("test" in the preceding example), unless there is another contact list with that name on the device, in which case a number is appended to the name to make it unique. To reference the contact list later, you should use the list's UID, which is the value that is returned by createPIMList(). Optionally, populate the contact list.
BlackBerryContactList contactList = (BlackBerryContactList) myPIM.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, listUID); Contact contact = contactList.createContact(); String[] name = new String[contactList.stringArraySize(Contact.NAME)]; name[Contact.NAME_GIVEN] = "Noha"; name[Contact.NAME_FAMILY] = "Toma"; contact.addStringArray(Contact.NAME, PIMItem.ATTR_NONE, name); contact.commit();
5.
Code sample
BlackBerryPIM myPIM = (BlackBerryPIM) PIM.getInstance(); try {
// create a contact list long listUID = myPIM.createPIMList(PIM.CONTACT_LIST, "test"); // add a contact to the list BlackBerryContactList contactList = (BlackBerryContactList) myPIM.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, listUID);
84
Development Guide
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();
A BlackBerryPIMRemovalException is thrown if an error occurs when you try to remove a contact list. 1. Import the required classes and interfaces.
import javax.microedition.pim.PIM; import net.rim.blackberry.api.pdap.BlackBerryPIM; import net.rim.blackberry.api.pdap.BlackBerryPIMRemovalException;
2. 3. 4.
If you know the name or UID of the contact list that you want to remove, go to step 6. Retrieve the array of contact lists.
String[] lists = myPIM.listPIMLists(PIM.CONTACT_LIST);
5. 6.
The returned array provides the names that are assigned to each contact list. Iterate through the array to search for the contact list that you want to remove. Remove the contact list by invoking BlackBerryPIM.removePIMList(). You can provide either the name or the UID of the contact list. By default, the method removes a contact list only if the list is empty. If you want to remove a contact list that is not empty, you must provide the parameter BlackBerryPIM.REMOVE_NON_EMPTY_LIST.
try {
myPIM.removePIMList(PIM.CONTACT_LIST, "test",
85
Development Guide
BlackBerryPIM.REMOVE_NON_EMPTY_LIST);
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()); }
2.
3.
Invoke PhoneCall.getContact() in a callback method in the phone listener (for example, in callIncoming () for a new call). The getContact() method searches all contact lists on the BlackBerry device and returns a BlackBerryContact that is associated with the current phone number, or null if there is no matching contact.
public void callIncoming(int callId) { PhoneCall call = Phone.getCall(callId); BlackBerryContact contact = call.getContact(); }
4.
Code sample
public void callIncoming(int callID) // in a phone listener { StringBuffer strBuffer = new StringBuffer(); 86
Development Guide
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
2. 3.
Retrieve the caller ID information for a call from the call log.
PhoneCallLogID callLog = new PhoneCallLogID(phoneNum);
Retrieve the associated contact by invoking PhoneCallLogID.getContact(). The getContact() method searches all contact lists on the BlackBerry device for a contact that matches the caller ID information. The method returns null if there is no matching contact.
BlackBerryContact contact = callLog.getContact();
87
Development Guide
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")); }
2.
Do one of the following: a. To search all contacts lists, invoke Phone.getContactsByPhoneNumber(), which returns a Vector object that contains the contacts that match the specified phone number. The Vector is empty if there are no matching contacts.
Vector contacts = Phone.getContactsByPhoneNumber(phoneNum);
b.
To search a specified contact list, invoke BlackBerryContactList.itemsByPhoneNumber(), which returns an Enumeration object of all contacts that match the specified phone number. Each of the items in the Enumeration is a PIMItem object, which you can cast to a BlackBerryContactList object.
BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, "test"); Enumeration myEnum = list.itemsByPhoneNumber(phoneNum);
Code sample
88
Development Guide
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]));
89
Development Guide
Link a contact
You can link a contact in your application with a contact in the Contacts application on the BlackBerry device. You can decide how to interact with the BlackBerry device user when you link a contact. The steps that follow describe one possible approach. Before you begin: Create the contacts in your application by creating and instantiating a class that implements the LinkableContact interface. Define a class that extends LinkedContactInfoProvider and register the class with your application. For more information, see Create an information provider for a linked contact. 1. Import the required classes and interfaces.
import net.rim.blackberry.api.pdap.*; import net.rim.blackberry.api.pdap.contactlinking.*; import javax.microedition.pim.*;
2.
Check to see whether there is a contact in the Contacts application (a BlackBerryContact object) that is a linking candidate for your contact. The LinkedContactUtilities.getContactLinkCandidate() method returns a BlackBerryContact if it finds a contact in the Contacts application that has the same email address or phone number as the LinkableContact that is passed to it. If there is no matching contact, the method returns null.
BlackBerryContact bbContact = LinkedContactUtilities.getContactLinkCandidate(linkableContact);
3. 4.
If a match is not found, have the user select a contact in the Contacts application to link to the selected contact.
BlackBerryContactList contacts = null; try { contacts = (BlackBerryContactList) PIM.getInstance(). openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); } catch(PIMException e) { ContactLinkingDemo.errorDialog("Couldn't open contacts list."); return; } Object choice = contacts.choose(); if(choice instanceof BlackBerryContact) { bbContact = (BlackBerryContact)choice; }
5.
Check to see whether the selected contact in the Contacts application is already linked to a contact in your application.
90
Development Guide
LinkedContactUtilities.isContactLinked(bbContact, linkableContact.getApplicationID())
6.
If the selected contact in the Contacts application is not already linked, link it to the contact in your application.
bbContact = LinkedContactUtilities.linkContact(bbContact, linkableContact);
Code sample: Linking a contact To see an example of this approach to linking a contact, see linkContact() in the Contact Linking Demo sample application that is included in the BlackBerry Java SDK.
Remove a link
You can remove a link between a contact in your application and a contact in the Contacts application on the BlackBerry device. 1. 2. Import the required classes and interfaces.
import net.rim.blackberry.api.pdap.contactlinking.*;
Retrieve the contact in the Contacts application that is linked to your contact.
BlackBerryContact contact = LinkedContactUtilities.getLinkedContact(linkableContact);
3.
91
Development Guide
Application group
COMPOSE_SN_MENU_GROUP COMPOSE_IM_MENU_GROUP COMPOSE_OTHER_MENU_GROUP
Description social networking applications instant messaging applications applications that are not social networking applications or instant messaging applications
If a contact in the Contacts application is linked with contacts in multiple third-party applications, the menu items in the Contacts application are grouped with other applications of the same group. Social networking menu items are grouped under the Social Networking menu item. Instant messaging menu items are grouped under the Instant Messaging menu item. Menu items from other types of applications are grouped under the Contact Using menu item.
The menu items from the third-party applications with linked contacts are integrated with the menu for the Contacts application. Situation A group contains one application with linked contacts. The application contains one menu item. A group contains one application with linked contacts. The application contains multiple menu items. A group contains multiple applications with linked contacts. Result The menu item for the application appears in the menu in the Contacts application. The application's name appears in the menu. Selecting the name displays a dialog box that contains a button for each menu item. The group menu item (such as Social Networking) appears in the menu. Selecting the group menu item displays a dialog box with a button for each application with linked contacts in the group.
2. 3.
92
Development Guide
4. 5.
6.
Invoke LinkedContactUtilities.registerMenuItems() to add the menu items for the linked contact to the menu. Pass in the array of menu items, the unique ID of your application, the application group, and the application descriptor.
LinkedContactUtilities.registerMenuItems(items, APPLICATION_ID, LinkedContactConstants.COMPOSE_SN_MENU_GROUP, appdesc);
Code sample: Creating menu items for linked contacts To see an example of creating menu items for linked contacts, see the SampleMenuItem class and main() in the Contact Linking Demo sample application that is included in the BlackBerry Java SDK.
2.
3.
Implement getAppImage() and return the icon that represents your application. The method must return an image in order for any information to appear for your linked contact when a user views a contact in the Contacts application.
93
Development Guide
4.
Implement getAppName() and return the name of your application. The method must return a name in order for information about the linked contact to appear when a user edits a contact in the Contacts application.
public String getAppName() { return _appName; }
5.
To indicate which LinkedContactInfoProvider fields (user name, availability, or status) that your application supports, implement isSupported(). By default, a field is not supported. You need to implement isSupported() only if your application supports any of the fields.
public boolean isSupported(int capability) { switch(capability) { case LinkedContactInfoProvider.STATUS: case LinkedContactInfoProvider.AVAILABILITY: case LinkedContactInfoProvider.USER_NAME: return true; default: return false; } }
6.
Implement requestFields() to specify the information to display for the contact in the Contacts application. The method is invoked by the framework when it needs to display information for the linked contact in the Contacts application. Specify the contact's name, status, and current availability, depending on which fields you defined as supported in isSupported().
public void requestFields(String contactID, final LinkedContactCallback callback, int fields) { LinkableContact contact = ContactListScreen.getUserForID(contactID); if((fields & LinkedContactInfoProvider.AVAILABILITY) != 0) { callback.setAvailability(LinkedContactInfoProvider.AVAILABILITY_ONLINE); } if((fields & LinkedContactInfoProvider.STATUS) != 0) { callback.setStatusString("<Sample contact status>"); } if((fields & LinkedContactInfoProvider.USER_NAME) != 0) { callback.setUserName(contact.toString()); }
7.
94
Development Guide
This example registers the application as a social networking application, using the COMPOSE_SN_MENU_GROUP field in LinkedContactConstants. When a user displays a contact in the Contacts application that is linked to one of your contacts, the information that you defined in your information provider displays on the contact screen. The framework determines the layout of the information. In this example, because the application was defined as a social networking application, the information displays in the Social Networks section of the contact. Code sample: Creating an information provider for a linked contact To see an example of creating an information provider for a linked contact, see the SampleLinkedContactInfoProvider class in the Contact Linking Demo sample application that is included in the BlackBerry Java SDK.
95
Development Guide
Task list
Task list
View or change a task
1. Import the required classes and interfaces.
import import import import import import java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList; net.rim.blackberry.api.invoke.Invoke; net.rim.blackberry.api.invoke.TaskArguments;
2.
3. 4.
Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments object created using the ARG_VIEW field and the ToDo object.
Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments(TaskArguments.ARG_VIEW, todo));
2.
Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments object created using the ARG_NEW field.
Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments( TaskArguments.ARG_NEW));
96
Development Guide
2.
3.
Invoke createToDo() to create a new ToDo object and add information to the new ToDo object.
ToDo todo = tdl.createToDo(); todo.addString(ToDo.SUMMARY, 0, "Walk the Dog");
4.
Invoke Invoke.invokeApplication() using the APP_TYPE_TASKS field, and a new TaskArguments object created using the ARG_NEW field and the new ToDo object.
Invoke.invokeApplication(Invoke.APP_TYPE_TASKS, new TaskArguments( TaskArguments.ARG_NEW, todo));
2.
Invoke PIM.openPIMList() and provide as parameters the type of list to open (PIM.TODO_LIST) and the access mode with which to open the list (READ_WRITE, READ_ONLY, or WRITE_ONLY).
ToDoList todoList = null; try { todoList = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE); } catch (PimException e) { // handle exception here }
Create a task
1. Import the required classes and interfaces.
import javax.microedition.pim.ToDo; import javax.microedition.pim.ToDoList;
2.
97
Development Guide
2. 3. 4.
Before you set or retrieve a field, verify that the item supports the field by invoking ToDoList.isSupportedField(int). Invoke PIMList.getFieldDataType(int) to retrieve the field data type. Invoke one of the following methods to set the field data: addString() addDate() addInt() addBoolean() addBinary()
if (todoList.isSupportedField(ToDo.SUMMARY)) { task.addString(ToDo.SUMMARY, ToDo.ATTR_NONE, "Create project plan"); } if (todoList.isSupportedField(ToDo.DUE)) { Date date = new Date(); task.addDate(ToDo.DUE, ToDo.ATTR_NONE, (date + 17280000)); } if (todoList.isSupportedField(ToDo.NOTE)) { task.addString(ToDo.NOTE, ToDo.ATTR_NONE, "Required for meeting"); } if (todoList.isSupportedField(ToDo.PRIORITY)) { task.addInt(Todo.PRIORITY, ToDo.ATTR_NONE, 2); }
2. 3.
98
To replace an existing value with a new value, invoke the appropriate set method, such as ToDo.setString(). To determine if a value is already set for the field, invoke ToDo.countValues().
Development Guide
Save a task
4.
Create code to manage a FieldFullException that a method such as addString() throws when a value already exists.
Save a task
1. Import the required classes and interfaces.
import javax.microedition.pim.ToDo; import javax.microedition.pim.ToDoList;
2. 3.
Before you commit your changes, invoke isModified() to determine whether any task fields have changed since the task was last saved. Invoke commit().
if(task.isModified()) { task.commit(); }
2.
3. 4.
Invoke ToDo.getFields() to retrieve an array of IDs for fields that have data for a particular ToDo item. Invoke PIMItem.getString() to retrieve the field values.
while (enum.hasMoreElements()) { ToDo task = (ToDo)enum.nextElement(); int[] fieldIds = task.getFields(); int id; for(int index = 0; index < fieldIds.length; ++index) { id = fieldIds[index]; if(task.getPIMList().getFieldDataType(id) == STRING) { 99
Development Guide
Export a task
for(int j=0; j < task.countValues(id); ++j) { String value = task.getString(id, j); System.out.println(task.getFieldLable(id) + "=" + value); }
Export a task
1. Import the required classes and interfaces.
import import import import import java.io.ByteArrayOutputStream; java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;
2. 3. 4.
Use an output stream writer to export tasks from the BlackBerry device to a supported serial format. To retrieve a string array of supported serial formats, invoke PIM.supportedSerialFormats(), and then specify the list type (PIM.TODO_List). To write an item to a serial format, invoke PIM.getInstance().toSerialFormat. The enc parameter specifies the character encoding to use when writing to the output stream. Supported character encodings include "UTF8," "ISO-8859-1," and "UTF-16BE." This parameter cannot be null.
ToDoList todoList = (ToDoList)PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_ONLY); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); String[] dataFormats = PIM.getInstance().supportedSerialFormats(PIM.TODO_LIST); Enumeration e = todoList.items(); while (e.hasMoreElements()) { ToDo task = (ToDo)e.nextElement(); PIM.getInstance().toSerialFormat(task, byteStream, "UTF8", dataFormats[0]); }
Import a task
1. Import the required classes and interfaces.
import import import import import java.io.ByteArrayInputStream; javax.microedition.pim.PIM; javax.microedition.pim.PIMItem; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;
2.
Invoke PIM.getInstance().fromSerialFormat() to return an array of PIMItem objects. The enc parameter specifies the character encoding to use when writing to the output stream. Supported character encodings include "UTF8," "ISO-8859-1," and "UTF-16BE." This parameter cannot be null.
100
Development Guide
Delete a task
3.
Delete a task
1. Import the required classes and interfaces.
import import import import java.util.Enumeration; javax.microedition.pim.PIM; javax.microedition.pim.ToDo; javax.microedition.pim.ToDoList;
2.
3.
2. 3.
101
Development Guide
2. 3.
102
Development Guide
Phone
Phone
10
The net.rim.blackberry.api.phone package contains the APIs that you can use to access the phone application on the BlackBerry device. You can use this package to make calls, switch between available phone lines, receive notification events, and change phone options.
2.
Create an instance of the PhoneArguments class, passing in the ARG_CALL field, and the destination phone number.
PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL, "519-555-0100");
3.
Invoke Invoke.invokeApplication() to open the phone application from your application, providing the APP_TYPE_PHONE field, and the PhoneArguments instance.
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, call);
4.
2.
Invoke initiateCall() to use a specific phone line to make a call. For the destination number, pass in a hardcoded number or user text. In the following code sample, the application makes a call to the destination number 519-555-0100 and uses the line ID that returns at index 0.
Phone.initiateCall(Phone.getLineIds()[0], "519-555-0100");
103
Development Guide
Create a class that implements the PhoneListener interface. Register the class that implements PhoneListener by invoking addPhoneListener().
104
Development Guide
Phone.addPhoneListener(this);
4.
5.
Handle incoming phone events by using the PhoneListener callback methods. For example, to receive notification that a call is disconnected, implement the notification in callDisconnected(int); to receive notification that a new call has arrived, implement the notification in callIncoming(int); and to receive notification that a call is waiting, implement the notification in callWaiting(int). For a complete list of PhoneListener callback methods, see the API reference for the BlackBerry Java Development Environment To deregister the PhoneListener, invoke Phone.removePhoneListener().
Phone.removePhoneListener(this);
2. 3. 4.
Create a class that extends MultiLineListener. Register the class as a PhoneListener by invoking Phone.addPhoneListener().
Phone.addPhoneListener(this);
To handle line switching events, perform the following actions: a. Override the MultiLineListener callback methods to notify the application when a line switching event occurs. This is particularly important when using this feature on devices that operate on CDMA networks, as a delay might occur when the application switches between phone lines.
public void setPreferredLineFailure(int lineId) { _screen.popupMessage("switching failed."); } public void setPreferredLineSuccess(int lineId) { _screen.popupMessage("Switching succeeded to " + Phone.getLineNumber(lineId) + " completed." ); }
b.
Invoke Phone.setPreferredLine(), passing in the line ID of the phone line to switch to. In the following code sample, the application selects the line that returns at index 0.
Phone.setPreferredLine( Phone.getLineIds()[0]);
105
Development Guide
Invoke numberOfCalls() to retrieve the total number of calls in a specified call log folder (FOLDER_MISSED_CALLS or FOLDER_NORMAL_CALLS).
int numberOfCalls = _logs.numberOfCalls(PhoneLogs.FOLDER_NORMAL_CALLS);
4.
Invoke PhoneLogs.callAt() to retrieve call information from a call log, passing in the index for the call log, and the call log folder.
PhoneCallLog phoneLog = (PhoneCallLog)_logs.callAt(0,PhoneLogs.FOLDER_NORMAL_CALLS);
5.
Invoke PhoneCallLog.getType() to retrieve the call type. The possible return values are TYPE_MISSED_CALL_OPENED, TYPE_MISSED_CALL_UNOPENED, TYPE_PLACED_CALL, or TYPE_RECEIVED_CALL.
int phoneType = phoneLog.getType();
106
Development Guide
import net.rim.blackberry.api.phone.PhoneCall;
2.
Invoke PhoneCall.getElapsedTime() to retrieve the length of time of the current call. Invoke PhoneCall.getStatus() to retrieve the connection status for the call. Invoke PhoneCall.getDisplayPhoneNumber() to retrieve the phone number of the call. In the following code sample, a status message displays on the screen when the phone call has lasted more than 120 seconds.
int threshold = 120; int elapsedTime = call.getElapsedTime(); int status = call.getStatus(); if ((status == PhoneCall.STATUS_CONNECTED || status == PhoneCall.STATUS_CONNECTING) && call.isOutGoing() && elapsedTime > threshold) { String phoneNumber = call.getDisplayPhoneNumber(); Status.show("Your call to " + call.getDisplayPhoneNumber() + " has lasted more than " + (String)threshold + "."); }
Invoke Phone.getDevicePhoneNumber(), passing in true to return the phone number in its regional format.
String phNumber = Phone.getDevicePhoneNumber(true);
Check for ControlledAccessException to catch instances where your application does not have permission to access the phone number information.
2.
107
Development Guide
108
Development Guide
2.
Create the application framework by extending the Application class. In the constructor, invoke Phone.addPhoneListener() to register the listener that is created in step 3. In main(), invoke enterEventDispatcher() to enable the application to receive events.
public final class MyPhoneScreen extends Application { public MyPhoneScreen() { Phone.addPhoneListener(new MyPhoneScreenContent()); } public static void main(String[] args) { new MyPhoneScreen().enterEventDispatcher(); } }
3.
Create a class that extends the AbstractPhoneListener class. Create a constructor for this new class.
final class MyPhoneScreenContent extends AbstractPhoneListener { public MyPhoneScreenContent() { } }
4.
In the class that extendsAbstractPhoneListener, override AbstractPhoneListener.callIncoming (). Create an instance of the ScreenModel class. Obtain an instance of the incoming call screen by invoking ScreenModel.getPhoneScreen(). Pass in parameters to specify the call screen orientation and type that
you want to obtain. In the following code sample, the portrait orientation of the incoming call screen is obtained. Because devices with touch screens support portrait and landscape orientations, you pass in the parameter PhoneScreen.LANDSCAPE to obtain the landscape orientation of the incoming call screen.
public void callIncoming(int callId) { ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING);
5.
In callIncoming(), create custom content to add to the call screen. In the following code sample, text is added to the incoming call screen by using label fields. Override LabelField.paint() to change the color of the label field.
LabelField labelField1 = new LabelField("Hello") { public void paint(Graphics g) { g.setColor(Color.GREEN); super.paint(g); } }; LabelField labelField2 = new LabelField(" to the World.") {
109
Development Guide
};
6.
In callIncoming(), specify the font for the custom content. In the following code sample, the font from the call screen is used. Invoke PhoneScreen.getCallerInfoFont() to obtain the font that is used by the call screen. Invoke Field.setFont() and pass in the call screen font to specify the font for the label fields that were created in step 5. Invoke PhoneScreen.add() to add the label fields to the call screen.
labelField1.setFont(phoneScreenPortrait.getCallerInfoFont()); labelField2.setFont(phoneScreenPortrait.getCallerInfoFont()); phoneScreenPortrait.add(labelField1); phoneScreenPortrait.add(labelField2);
7.
In callIncoming(), invoke ScreenModel.sendAllDataToScreen() to add the custom content to the incoming call screen.
screenModel.sendAllDataToScreen();
public final class MyPhoneScreen extends Application { public MyPhoneScreen() { Phone.addPhoneListener(new MyPhoneScreenContent()); } public static void main(String[] args) { new MyPhoneScreen().enterEventDispatcher(); } } final class MyPhoneScreenContent extends AbstractPhoneListener { public MyPhoneScreenContent() { } public void callIncoming(int callId) { ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.INCOMING);
110
Development Guide
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();
callWaiting()
Description To display content on the first active call screen, override AbstractPhoneListener.callAnswered() and obtain call screen objects for the active call. The Phone application invokes this method when the user answers the first call. On devices that operate on a GSM network, the Phone application invokes this method when the user answers the first call and second call. To display content on the second active call screen, override AbstractPhoneListener.callWaiting() and obtain call screen objects for the active call. The Phone application invokes this method when the user answers the second call.
111
Development Guide
Code sample: Displaying content on devices that operate on a CDMA network The following code sample demonstrates how to override AbstractPhoneListener.callWaiting(). You can check whether the device operates on a CDMA network by using the RadioInfo class. You obtain the instances of the active call screen by invoking ScreenModel.getPhoneScreen() and passing in PhoneScreen.ACTIVE so that you are only specifying content for the second call.
public void callWaiting(int callId) { // For CDMA devices, specify the content for the active call screen if((RadioInfo.getSupportedWAFs() & RadioInfo.WAF_CDMA) != 0) { ScreenModel screenModel = new ScreenModel(callId); PhoneScreen phoneScreenPortrait = screenModel.getPhoneScreen(PhoneScreen.PORTRAIT, PhoneScreen.ACTIVE); PhoneScreen phoneScreenLandscape = screenModel.getPhoneScreen(PhoneScreen.LANDSCAPE, PhoneScreen.ACTIVE);
} }
// For GSM and CDMA devices, specify the content for the incoming call screen
112
Development Guide
BlackBerry Browser
BlackBerry Browser
Retrieve a BlackBerry Browser session
Retrieving the default session overrides any open sessions on the BlackBerry device. 1. 2.
11
Import the net.rim.blackberry.api.browser.Browser class. Retrieve the default BrowserSession object by invoking the static method Browser.getDefaultSession ().
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"); } };
113
Development Guide
load and configure the display settings for web content in Field objects in any application access the DOM for loaded web content control the HTTP handling for connections, SSL, cookies, and caching set callback listeners to monitor the loading progress of web pages
You can create applications that include Java objects and methods that can access and invoke JavaScript code and be accessed and invoked by JavaScript code by using the APIs in the net.rim.device.api.script package, which is new in BlackBerry JDE 5.0.
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }
3.
4. 5.
In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(myBrowserField);
114
Development Guide
6.
In the screen constructor, invoke BrowserField.displayContent() to specify and display the HTML content.
myBrowserField.displayContent("<html><body><h1>Hell o World!</h1></body></html>", "http://localhost");
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }
3.
Create the framework for the custom screen by extending the MainScreen class.
class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }
4. 5. 6.
In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(myBrowserField);
In the screen constructor, invoke BrowserField.requestContent() to specify the location of the HTML content and display it.
115
Development Guide
myBrowserField.requestContent("http://www.blackberry.com");
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }
3.
4. 5. 6.
In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(myBrowserField);
In the screen constructor, invoke BrowserField.requestContent() to specify the location of the resource in your application and display the HTML content.
myBrowserField.requestContent("local:///test.html");
Note: The BrowserField class does not access resources using a folder structure. The BrowserField class displays the first resource found that matches the specifed file name.
116
Development Guide
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }
3.
Create the framework for the custom screen by extending the MainScreen class.
class BrowserFieldDemoScreen extends MainScreen { public BrowserFieldDemoScreen() { } }
4. 5.
In the screen constructor, invoke BrowserFieldConfig.setProperty() to specify a property of the BrowserField. The first parameter in setProperty() specifies the property, and the second parameter specifies the value of the property. For example, the following code sample specifies the NAVIGATION_MODE property of a BrowserField object:
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
6.
In the screen constructor, create an instance of the BrowserField class that uses the configuration that you defined.
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
117
Development Guide
2.
Create the application framework by extending the UiApplication class. In main(), create an instance of the new class and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor, invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class, described in step 3, represents the custom screen.
public class BrowserFieldDemo extends UiApplication { public static void main(String[] args) { BrowserFieldDemo app = new BrowserFieldDemo(); app.enterEventDispatcher(); } public BrowserFieldDemo() { pushScreen(new BrowserFieldDemoScreen()); }
3.
4. 5. 6.
In the screen constructor, invoke add() to add the BrowserField object to the screen.
add(browserField);
In the screen constructor, create a String object that contains the base web address of the web page that you are sending the form data to.
String baseURL = "http://www.blackberry.com";
7.
In the screen constructor, create a String that specifies the form data that your application sends to the web page.
118
Development Guide
8. 9.
In the screen constructor, create a Hashtable object to store the header information for the form data.
Hashtable header = new Hashtable();
In the screen constructor, invoke Hashtable.put() to specify the header information for the form data.
header.put("Content-Length", "" + postData.length()); header.put("Content-Type", "application/x-www-form-urlencoded");
10. In the screen constructor, invoke BrowserField.requestContent() to send the form data to the web page and display the web page.
browserField.requestContent(baseURL, postData.getBytes(), new HttpHeaders(header));
119
Development Guide
Menu items
Menu items
Adding menu items to BlackBerry Device Software applications
12
The Application Menu Item API, in the net.rim.blackberry.api.menuitem package, lets you define menu items to display in BlackBerry Device Software applications. The ApplicationMenuItemRepository class lets you add or remove menu items from BlackBerry Device Software applications.
2.
To create and register a menu item, perform the following tasks: Task Define a menu item Steps Extend the ApplicationMenuItem class.
public class SampleMenuItem extends ApplicationMenuItem { ... }
Construct the ApplicationMenuItem. A higher number in the constructor means that the menu item appears lower in the menu.
SampleMenuItem() { super(0x350100); }
Implement toString().
public String toString() { return "My menu item"; }
Implement run().
120
Development Guide
Task
Steps
public Object run(Object context) { // the menu's action here return null; }
Invoke ApplicationMenuItemRepository.addMenuItem().
ApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance(); amir.addMenuItem( ApplicationMenuItemRepository.MENUITEM_PHONE, mySampleMenuItem);
};
// Register menu item to display when user views a contact ApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance(); amir.addMenuItem(ApplicationMenuItemRepository.MENUITEM_ADDRESSCARD_VIEW, ami);
For more information, see the Application Integration category overview in the API reference for the BlackBerry Java Development Environment.
121
Development Guide
13
www.blackberry.com/go/apiref: View the latest version of the API reference for the BlackBerry Java SDK. www.blackberry.com/go/devguides: Find development guides, release notes, and sample application overviews for the BlackBerry Java SDK. www.blackberry.com/go/uiguidelines: Find the UI guidelines for BlackBerry smartphones. www.blackberry.com/developers: Visit the BlackBerry Developer Zone for resources about developing BlackBerry device applications. www.blackberry.com/go/developerkb: View knowledge base articles in the BlackBerry Development Knowledge Base. www.blackberry.com/developers/downloads: Find the latest development tools and downloads for developing BlackBerry device applications.
122
Development Guide
Glossary
Glossary
API application programming interface BCC blind carbon copy CC carbon copy CRM customer relationship management DTMF Dual Tone Multiple-frequency JSR Java Specification Request MIME Multipurpose Internet Mail Extensions MEID Mobile Equipment Identifier MMS Multimedia Messaging Service PIM personal information management PIN personal identification number SMS Short Message Service SVG Scalable Vector Graphics UCS Universal Content Stream
14
123
Development Guide
Glossary
124
Development Guide
Provide feedback
Provide feedback
To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.
15
125
Development Guide
16
10 September 2010
Create a custom folder in the message list Create an icon for a custom message Create a custom indicator Create a module for background processes Creating a module for background processes Creating a module for the UI Send a notification when a custom folder changes Start the module for background processes or the module for the UI Using custom messages and folders in the message list Added the following topics: Check for a sensor on the device Check the state of a sensor Cradle detection Cradle handling Create a custom folder in the message list Create an icon for a custom message Create a custom indicator Create a module for background processes Creating a module for background processes Creating a module for the UI Custom messages Device Capability API Hide an indicator Notify an application when the state of a sensor changes Remove a custom indicator Send a notification when a custom folder changes Start the module for background processes or the module for the UI Using custom messages and folders in the message list Working with sensors on a device
Added the following code sample: 16 August 2010 Code sample: Working with a sensor Added the following topic:
126
Development Guide
Date
Description Create an information provider for a linked contact Changed the following topics: Linking third-party contacts with contacts in the Contacts application Link a contact
Removed the following topic: 3 August 2010 Create a custom field for linked contacts Added the following topics: Configure and start a search Create a contact list Creating and removing contact lists Customizing the appearance of your data in search results Define an EntityBasedSearchable class for your SearchableEntity objects Displaying content on devices that operate on a CDMA network Encapsulate your data in the SearchableEntity class Ensure that a device runs a single instance of your application Exposing your application data Inserting data when a device starts Listening for responses from the Unified Search Service Making data findable Notify the Unified Search Service about changes to your data Passing queries to other search engines Process search results Register your EntityBasedSearchable object with the Unified Search Service Remove a calendar entry with no notification Remove a contact list Removing your data from the content repository Retrieve contacts by phone number Retrieve the contact that is associated with a completed call Retrieve the contact that is associated with an active call Searching Specify an icon in the EntityBasedSearchable or SearchableEntity class Unified search Update a calendar entry with no notification
127
Development Guide
Date
Description Using other search engines Added the following code samples: Code sample: Displaying content on a phone screen
Changed the following topics: Displaying content on a call screen Display content on a phone screen
128
Development Guide
Legal notice
Legal notice
17
2011 Research In Motion Limited. All rights reserved. BlackBerry, RIM, Research In Motion, and related trademarks, names, and logos are the property of Research In Motion Limited and are registered and/or used in the U.S. and countries around the world. Eclipse is a trademark of Eclipse Foundation, Inc. Google and YouTube are trademarks of Google Inc. Java and JavaScript are trademarks of Oracle America, Inc. iCal is a trademark of Apple Inc. vCard is a trademark of the Internet Mail Consortium. Wi-Fi is a trademark of the Wi-Fi Alliance. All other trademarks are the property of their respective owners. This documentation including all documentation incorporated by reference herein such as documentation provided or made available at www.blackberry.com/go/docs is provided or made accessible "AS IS" and "AS AVAILABLE" and without condition, endorsement, guarantee, representation, or warranty of any kind by Research In Motion Limited and its affiliated companies ("RIM") and RIM assumes no responsibility for any typographical, technical, or other inaccuracies, errors, or omissions in this documentation. In order to protect RIM proprietary and confidential information and/or trade secrets, this documentation may describe some aspects of RIM technology in generalized terms. RIM reserves the right to periodically change information that is contained in this documentation; however, RIM makes no commitment to provide any such changes, updates, enhancements, or other additions to this documentation to you in a timely manner or at all. This documentation might contain references to third-party sources of information, hardware or software, products or services including components and content such as content protected by copyright and/or third-party web sites (collectively the "Third Party Products and Services"). RIM does not control, and is not responsible for, any Third Party Products and Services including, without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Services in this documentation does not imply endorsement by RIM of the Third Party Products and Services or the third party in any way. EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS OR WARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NON-INFRINGEMENT, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROM THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE CLAIM.
129
Development Guide
Legal notice
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL RIM BE LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NONPERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL, PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGES FOR LOSS OF PROFITS OR REVENUES, FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH RIM PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OF SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, RIM SHALL HAVE NO OTHER OBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY. THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THE CAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO BREACH OF CONTRACT, NEGLIGENCE, TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B) TO RIM AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIME SERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIR RESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS. IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY DIRECTOR, EMPLOYEE, AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF RIM OR ANY AFFILIATES OF RIM HAVE ANY LIABILITY ARISING FROM OR RELATED TO THE DOCUMENTATION. Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to ensure that your airtime service provider has agreed to support all of their features. Some airtime service providers might not offer Internet browsing functionality with a subscription to the BlackBerry Internet Service. Check with your service provider for availability, roaming arrangements, service plans and features. Installation or use of Third Party Products and Services with RIM's products and services may require one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third party rights. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licenses are required to do so. If required you are responsible for acquiring them. You should not install or use Third Party Products and Services until all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIM's products and services are provided as a convenience to you and are provided "AS IS" with no express or implied conditions, endorsements, guarantees, representations, or warranties of any kind by RIM and RIM assumes no liability whatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties, except to the extent expressly covered by a license or other agreement with RIM.
130
Development Guide
Legal notice
Certain features outlined in this documentation require a minimum version of BlackBerry Enterprise Server, BlackBerry Desktop Software, and/or BlackBerry Device Software. The terms of use of any RIM product or service are set out in a separate license or other agreement with RIM applicable thereto. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY EXPRESS WRITTEN AGREEMENTS OR WARRANTIES PROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION. Research In Motion Limited 295 Phillip Street Waterloo, ON N2L 3W8 Canada Research In Motion UK Limited Centrum House 36 Station Road Egham, Surrey TW20 9LF United Kingdom Published in Canada
131