BlackBerry Java Development Environment Version 4.2.
BlackBerry Java Development Environment Version 4.2.0 Development Guide Last modified: 11 February 2008 Part number: 9461716 At the time of publication, this documentation is based on the BlackBerry Java Development Environment Version 4.2.0. Send us your comments on product documentation: https://www.blackberry.com/DocsFeedback. ©2008 Research In Motion Limited. All Rights Reserved.
no representation, warranty or guarantee whatsoever in relation to the Third Party Information and RIM assumes no liability whatsoever in relation to the Third Party Information even if RIM has been advised of the possibility of such damages or can anticipate such damages.
Contents 1 Creating UIs .........................................................................................................................................................13 Elements of a BlackBerry device UI ..............................................................................................................13 Screens.......................................................................................................................................................13 UI components.........
Code sample: Using a raw image to recreate an encoded image.................................................... 47 Drawing and rendering images ....................................................................................................................48 Position an image ....................................................................................................................................48 Draw an image in color..........................................................................
Activate synchronization when the BlackBerry device starts...........................................................89 Code sample: Letting the BlackBerry Desktop Software back up and restore application data 89 5 Using smart cards...............................................................................................................................................97 Smart cards .........................................................................................................................
Use USB or serial port connections.....................................................................................................128 Use Bluetooth serial port connections................................................................................................128 8 Creating notifications...................................................................................................................................... 135 Types of notification events ...........................................
Working with attachments .......................................................................................................................... 160 Create an attachment handler ............................................................................................................ 160 Retrieve attachments............................................................................................................................ 160 Send a message with an attachment ...................................
Use the BlackBerry Maps application ................................................................................................ 201 Locating BlackBerry devices using GPS information .............................................................................. 201 Methods for retrieving a GPS location............................................................................................... 201 Selecting a GPS location provider .......................................................................
Debugging applications.............................................................................................................................. 246 Use breakpoints.................................................................................................................................... 246 Debug an application in the BlackBerry IDE.....................................................................................247 Manage a debugging session .................................................
Distribute applications .........................................................................................................................267 Distributing applications with the BlackBerry Desktop Software........................................................ 269 Create an application loader file........................................................................................................ 269 Load an application on a specific BlackBerry device ..............................................
1 Creating UIs Elements of a BlackBerry device UI Create a screen Adding UI components to a screen Creating custom UI components Adding menu items to BlackBerry applications Arrange UI components Set field focus and navigation Listen for field focus changes Respond to UI events Listen for field property changes Manage foreground events Manage drawing areas Elements of a BlackBerry device UI Screens The main structure for a BlackBerry® device UI is the Screen object.
BlackBerry Java Development Environment Development Guide Types of screens Screen Type Class Description Default Screen Use the Screen class to define a manager to lay out UI components on the screen and to define a specific type of screen using the styles that the constants on the Field superclass define. Standard vertical FullScreen By default, a FullScreen class contains a single vertical field manager.
1: Creating UIs Create a screen Extend the Screen class or one of its subclasses, FullScreen or MainScreen. > Adding UI components to a screen 1. Create an instance of a UI component. CheckboxField myCheckbox = new CheckboxField("First checkbox", true); 2. Add the UI component to your extension of a screen class. mainScreen.add(myCheckbox); Create UI components To create an instance of a component, you can use more than one constructor. See the API Reference for more information about Field classes.
BlackBerry Java Development Environment Development Guide Task Steps Create an option. 1. Create an instance of a RadioButtonGroup(). RadioButtonGroup rbGroup = new RadioButtonGroup(); 2. Create an instance of a RadioButtonField for each option you want to make available to the BlackBerry® device user. RadioButtonField rbField = new RadioButtonField("First field"); RadioButtonField rbField2 = new RadioButtonField("Second field"); 3. Invoke RadioButtonGroup.
1: Creating UIs Task Steps Create a field that lets a BlackBerry device user select a range of items in the list. 1. Create the items that you want to display in a ListField. String fieldOne = new String("Mark Guo"); String fieldTwo = new String("Amy Krul"); 2. Create an instance of a ListField. ListField myList = new ListField(); 3. Create an instance of a ListCallback. ListCallback myCallback = new ListCallback(); 4. Set the call back of the ListField to be the ListCallback. myList.
BlackBerry Java Development Environment Development Guide Create a custom field Task Steps Create a custom field. You can only add custom context menu items and custom layouts to a custom field. > Extend the Field class, or one of its subclasses, implementing the DrawStyle interface to specify the characteristics of the custom field and turn on drawing styles.
1: Creating UIs Task Steps Specify the arrangement of the objects in the field. 1. Implement layout(). Arrange field data so that you perform the most complex calculations in layout() instead of in paint(). 2. Within your implementation, perform the following actions: • To calculate the available width and height, invoke Math.min() to return the smaller of the specified width and height and the preferred width and height of the field.
BlackBerry Java Development Environment Development Guide Task Steps Define the preferred height of a custom component. > 20 Implement getPreferredHeight(), using the relative dimensions of the field label to determine the preferred height.
1: Creating UIs Task Steps Define the appearance of the custom field. 1. Perform complex calculations in layout()instead of in paint(). 2. Implement paint(). protected void paint(Graphics graphics) { int textX, textY, textWidth; int w = getWidth(); switch(_shape) { case TRIANGLE: int h = (w>>1); int m = (w>>1)-1; graphics.drawLine(0, h-1, m, 0); graphics.drawLine(m, 0, w-1, h-1); graphics.drawLine(0, h-1, w-1, h-1); textWidth = Math.
BlackBerry Java Development Environment Development Guide Task Steps Add component capabilities. > Implement the Field set() and get() methods. public String getLabel() { return _label; } public int getShape() { return _shape; } public void setLabel(String label) { _label = label; _labelWidth = _font.getAdvance(_label); updateLayout(); } public void setShape(int shape) { _shape = shape; updateLayout(); } Code sample: Creating custom buttons Example: CustomButtonField.java /** * CustomButtonField.
1: Creating UIs /* Constructs a button with specified label and shape, and the default style. */ public CustomButtonField(String label, int shape) { this(label, shape, 0); } /* Constructs a button with specified label and style, and the default shape.
BlackBerry Java Development Environment Development Guide return _shape; } /* Sets the label. */ public void setLabel(String label) { _label = label; _labelWidth = _font.getAdvance(_label); updateLayout(); } /* Sets the shape. */ public void setShape(int shape) { _shape = shape; updateLayout(); } /* Retrieves the preferred width of the button.
1: Creating UIs // Update the cached font in case it has been changed. _font = getFont(); _labelHeight = _font.getHeight(); _labelWidth = _font.getAdvance(_label); // Calculate width. width = Math.min( width, getPreferredWidth() ); // Calculate height. height = Math.min( height, getPreferredHeight() ); // Set dimensions. setExtent( width, height ); } /* * Redraws this button. The field’s manager invokes this method during the * repainting process to instruct this field to repaint itself.
BlackBerry Java Development Environment Development Guide textWidth ); } } Create custom context menus Task Steps Create the custom context menu items. > Provide a context menu. > In your field class, create the custom context menu items.
1: Creating UIs Code sample: Creating a custom context menu Example: ContextMenuSample.java /** * ContextMenuSample.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.contextmenus; import import import import import import net.rim.device.api.i18n.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.system.*; com.rim.samples.docs.resource.
BlackBerry Java Development Environment Development Guide protected void makeContextMenu(ContextMenu contextMenu) { contextMenu.addItem(myContextMenuItemA); contextMenu.addItem(myContextMenuItemB); } MyContextField(String text) { super(text); } } public ContextMenuSample() { MainScreen mainScreen = new MainScreen(); MyContextField myContextField = new MyContextField(“Field label: “); mainScreen.
1: Creating UIs Create custom layout managers Task Steps Create a custom layout manager. > Extend the Manager class or one of its subclasses. class DiagonalManager extends Manager { public DiagonalManager(long style){ super(style); } ... } Return a preferred field width. > Override getPreferredWidth() so that it returns the preferred field width for the manager.
BlackBerry Java Development Environment Development Guide Task Steps Specify the arrangement of the child fields. Override sublayout() to retrieve the total number of fields in the manager. To control how each child field is added to the screen, call setPositionChild() and layoutChild() for each field that the manager contains.
1: Creating UIs package com.rim.samples.docs.custommenu; import import import import net.rim.device.api.system.*; net.rim.device.api.ui.container.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; class DiagonalManager extends Manager { public DiagonalManager(long style) { super(style); } public int getPreferredWidth() { int width = 0; int numberOfFields = getFieldCount(); for (int i=0; i
BlackBerry Java Development Environment Development Guide return index; } } } 32
1: Creating UIs Create custom lists Task Steps Let users BlackBerry® device select multiple items in a list. > Declare lists as MULTI_SELECT. Create a callback object. > Implement the ListFieldCallback interface. private class ListCallback implements ListFieldCallback { // The listElements vector contain the entries in the list. private Vector listElements = new Vector(); ... } Let the field repaint a row.
BlackBerry Java Development Environment Development Guide Code sample: Creating a custom list Example: SampleListFieldCallback.java /** * SampleListFieldCallback.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.listfields; import import import import import java.util.*; net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.
1: Creating UIs myList.insert(1); myCallback.insert(fieldTwo, 1); myList.insert(2); myCallback.insert(fieldThree, 2); mainScreen.
BlackBerry Java Development Environment Development Guide Adding menu items to BlackBerry applications The Application Menu Item API, in the net.rim.blackberry.api.menuitem package, lets you add menu items to BlackBerry® applications. The ApplicationMenuItemRepository class lets you add or remove menu items from BlackBerry applications. Create a menu item Task Steps Define a menu item. > Specify the position of the menu item in the menu.
1: Creating UIs Code sample: Creating a new menu item in a BlackBerry application The menu item appears when a BlackBerry® device user views a contact in the address book. When a BlackBerry device user clicks the menu item, the ContactsDemo application appears. Example: DemoAppMenuItem.java /** * DemoApplicationMenuItem.java * Copyright (C) 2003-2007 Research In Motion Limited. * * The following code example creates a menu item that appears when * a user views a contact in the address book.
BlackBerry Java Development Environment Development Guide DemoAppMenuItem() { long locationToAddMenuItem = ApplicationMenuItemRepository.MENUITEM_ADDRESSCARD_VIEW; addMenuItem(ARG_LAUNCH_CONTACT_DEMO, locationToAddMenuItem, new ContactsDemoMenuItem()); System.exit(0); } private static void addMenuItem(String argOfAppl, long location, ApplicationMenuItem applMenuItem) { ApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance(); ApplicationDescriptor app = ApplicationDescriptor.
1: Creating UIs • VerticalFieldManager • HorizontalFieldManager • FlowFieldManager • DialogFieldManager To create a custom layout manager, extend Manager.
BlackBerry Java Development Environment Development Guide Define a layout manager Task Steps Create a layout manager. On an instance of a Screen, complete the following actions: 1. Instantiate the appropriate Manager subclass. VerticalFieldManager vfm = new VerticalFieldManager(Manager.VERTICAL_SCROLL); 2. Add UI components to the layout manager. vfm.add(bitmapField); vfm.add(bitmapField2); 3. Add the layout manager to the screen. mainScreen.
1: Creating UIs Task Steps Interpret the status parameter of the navigation methods. > In your implementation of one of the navigationClick, navigationUnclick, or navigationMovement methods of the Screen or Field classes, perform a bitwise AND operation on the status parameter to yield more information about the event.
BlackBerry Java Development Environment Development Guide Define a layout manager Task Steps Create a layout manager. On an instance of a Screen, complete the following actions: 1. Instantiate the appropriate Manager subclass. VerticalFieldManager vfm = new VerticalFieldManager(Manager.VERTICAL_SCROLL); 2. Add UI components to the layout manager. vfm.add(bitmapField); vfm.add(bitmapField2); 3. Add the layout manager to the screen. mainScreen.
1: Creating UIs Manage foreground events The system calls Application.activate() when it brings an application to the foreground. Manage drawing areas The Graphics object represents the entire drawing surface that is available to the application. To limit this area, divide it into XYRect objects. Each XYPoint represents a point on the screen, which is composed of an X coordinate and a Y co-ordinate. Task Steps Create rectangular clipping areas. 1.
BlackBerry Java Development Environment Development Guide 44
2 Using graphics and multimedia Using images Drawing and rendering images Using audio Using rich media Using images Use raw images Task Steps Allow applications to use raw image data. > To retrieve raw image data from a specified region of a bitmap and store the data in an integer array, invoke Bitmap.getARGB(). void getARGB(int[] argbData, int offset, int scanLength, int x, int y, int width, int height); Retrieve image data. 1. Initialize an integer array. Bitmap original = Bitmap.
BlackBerry Java Development Environment Development Guide Use encoded images Task Steps Access an image. 1. Save an image to the project folder or subfolder. 2. Add the image to the project in the BlackBerry® Integrated Development Environment. 3. Invoke Class.getResourceAsStream() to retrieve the image as an input stream of bytes. private InputStream input; ... try { input = Class.forName("com.rim.samples.docs.imagedemo.ImageDemo"). getResourceAsStream("/images/example.
2: Using graphics and multimedia Code sample: Using a raw image to recreate an encoded image Example: ImageDemo.java /** * ImageDemo.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.imagedemo; import import import import import net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.system.*; java.io.*; /* The ImageDemo.
BlackBerry Java Development Environment Development Guide try { EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length); add(new BitmapField(image.getBitmap())); } catch (IllegalArgumentException iae) { System.out.println(“Image format not recognized.”); } } } } Drawing and rendering images Position an image Task Steps Use an individual field. 1. Invoke the Graphics() constructor.
2: Using graphics and multimedia Task Steps Determine the raster operations that the application supports. 1. Draw a set of shaded, filled paths. > Invoke Graphics.isRopSupported(int). 2. Provide one of the following constants as a parameter: • ROP_CONST_GLOBALALPHA: blends the constant foreground color using a constant global alpha value with destination pixels • ROP_SRC_GLOBALALPHA: blends a source bitmap using a constant global alpha value with destination pixels Invoke Graphics.
BlackBerry Java Development Environment Development Guide Code sample: Drawing a new bitmap using an existing bitmap Example: DrawDemo.java /* * DrawDemo.java * Copyright (C) 2002-2005 Research In Motion Limited. */ package com.rim.samples.docs.drawing; import import import import net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; /* The DrawDemo.
2: Using graphics and multimedia System.out.println(“Error occurred during drawing: “ + e); } if(restored.equals(original)) { System.out.println(“Success! Bitmap renders correctly with RGB data.”); } else if(!restored.equals(original)) { System.out.println(“Bitmap rendered incorrectly with RGB data.”); } BitmapField field1 = new BitmapField(original, BitmapField.
BlackBerry Java Development Environment Development Guide Task Steps Create a player for media from an input stream. 1. Invoke Manager.createPlayer(InputStream stream, String type). The type parameter represents the input media content type. 2. Check for a MediaException if null is the content type. RecordStore recSt; int recId; try { InputStream inpStr = new ByteArrayInputStream((store.getRecord(recId)); Player p = Manager.createPlayer(inpStr, "audio/mpeg"); p.
2: Using graphics and multimedia // Play "C" section D4, duration, D4, duration, E4, duration, D4, duration, C4, duration }; try{ Player p = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR); p.realize(); ToneControl c = (ToneControl)p.getControl("ToneControl"); c.setSequence(mySequence); p.
BlackBerry Java Development Environment Development Guide Play media Task Steps Prepare the media player. 1. Invoke Player.realize(). 2. Invoke Player.prefetch(). Start the media player. > Invoke Player.start(). The Player returns to the Prefetched state when you invoke Player.stop() or when it reaches the end of the media file. try { Player p = Manager.createPlayer("http://www.test.rim.net/abc.wav"); p.
2: Using graphics and multimedia Task Steps Send a media player event to > a registered player listener. Invoke playerUpdate(Player player, String event, Object eventData). public void playerUpdate(Player player,String event, Object eventData) {// Release resources player.close(); if ( event == PlayerListener.END_OF_MEDIA ) // Add code for actions if the end of media is reached. } Using rich media Playing rich media content To play rich media content, use the following classes: • To retrieve .
BlackBerry Java Development Environment Development Guide Task Steps Retrieve a UI object that displays rich media content. 1. Play rich media content. 1. Invoke MediaPlayer.getUI(). 2. Cast the object that getUI() returns as a Field, and add it to a Screen for display. add((Field)player.getUI()); Check the media player state. 2. Invoke MediaPlayer.start(). if(player.getState() == MediaPlayer.REALIZED) { try { player.start(); } catch(MediaException me) { System.out.
2: Using graphics and multimedia MediaPlayer player = new MediaPlayer(); MediaManager manager = new MediaManager(); try { Object media = manager.createMedia(“http://webserver/SVGFILE.pme”); player.setMedia(media); } catch (IOException ioe) { } catch (MediaException me) { System.out.println(“Error during media loading: “); System.out.println(me.getCode()); System.out.println(me.getMessage()); } add((Field)player.getUI()); try { player.start(); } catch(MediaException me) { System.out.
BlackBerry Java Development Environment Development Guide Task Steps Register the listener. > Invoke addMediaListener() on the MediaPlayer and MediaManager objects. private MediaListenerImpl _listener = new MediaListenerImpl(); private MediaPlayer player = new MediaPlayer(); private MediaManager manager = new MediaManager(); player.addMediaListener(_listener); manager.addMediaListener(_listener); Load the content in the 1. To download the content for future playback, invoke MediaManager.
2: Using graphics and multimedia ... break; } break; ... switch(s.getStatus()) { case LoadingStatus.LOADING_STARTED: System.out.println("Loading in progress"); break; case LoadingStatus.LOADING_READING: System.out.println("Parsing in progress"); break; case LoadingStatus.LOADING_FINISHED: System.out.println("Loading completed"); break; case LoadingStatus.LOADING_FAILED: String errorName = null; int code = s.getCode(); switch (code) { case MediaException.
BlackBerry Java Development Environment Development Guide Example: MediaSample2.java /** * MediaSample2.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.mediasample; import import import import import java.io.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.system.*; import net.rim.plazmic.mediaengine.*; import net.rim.plazmic.mediaengine.io.
2: Using graphics and multimedia case LoadingStatus.LOADING_STARTED: System.out.println(“Loading in progress”); break; case LoadingStatus.LOADING_READING: System.out.println(“Parsing in progress”); break; case LoadingStatus.LOADING_FINISHED: System.out.println(“Loading completed”); break; case LoadingStatus.LOADING_FAILED: String errorName = null; int code = s.getCode(); switch (code) { case MediaException.INVALID_HEADER: errorName = “Invalid header” + “\n” + break; case MediaException.
BlackBerry Java Development Environment Development Guide player.addMediaListener(_listener); manager.addMediaListener(_listener); // Change this to the location of a test .pme file. manager.createMediaLater(“http://test.rim.com/SVGBS0001.pme”); add((Field)player.getUI()); } } } Create a custom connector for rich media connections To add support for a custom protocol or to override default behavior, create a custom Connector. Task Steps Implement a custom connector. > Implement the net.rim.plazmic.
2: Using graphics and multimedia } public InputStream getInputStream(String uri, ConnectionInfo info) throws IOException, MediaException { if (uri.startsWith(“myprotocol://”)) { // Perform special tasks. info.setConnection(new MyProtocolConnection()); info.setContentType(“application/x-vnd.rim.pme”); // OpenMyInputStream() is a custom method that opens //stream for “myprotocol://” input = openMyInputStream(uri); } else { input = delegate.
BlackBerry Java Development Environment Development Guide 64
3 Storing data Use BlackBerry persistent storage Manage persistent data Manage custom objects Use the MIDP record store Use BlackBerry persistent storage Storage method Description BlackBerry® persistence model The BlackBerry persistence model provides a flexible and efficient way to store data. When writing an application specifically for BlackBerry devices, use the BlackBerry persistence model. • • MIDP record stores The BlackBerry persistence model lets you save any Object in the persistent store.
BlackBerry Java Development Environment Development Guide Feature Description Data integrity To maintain the integrity of data in persistent storage, partial updates are not made if an error occurs during a commit. Data in the PersistentObject retains the values from the last commit in order to preserve data integrity. If the JVM performs an emergency garbage collection operation due to low memory, outstanding transactions are committed immediately to avoid compromising data integrity.
3: Storing data Task Steps Retrieve persistent data. 1. Invoke getContents() on a PersistentObject. 2. To convert the object that PersistentObject.getContents() returns to a specific object type, perform an explicit cast on the object that PersistentObject.getContents() returns. synchronized(store) { String[] currentinfo = (String[])store.getContents(); if(currentinfo == null) { Dialog.alert(_resources.getString(APP_ERROR)); } else { currentusernamefield.setText(currentinfo[0]); currentpasswordfield.
BlackBerry Java Development Environment Development Guide private AutoTextEditField currentusernamefield; private AutoTextEditField currentpasswordfield; static { _resources = ResourceBundle.getBundle( UserInfoResource.BUNDLE_ID, UserInfoResource.BUNDLE_NAME); store = PersistentStore.getPersistentObject(0xa1a569278238dad2L); } private MenuItem saveItem = new MenuItem( _resources.getString(MENUITEM_SAVE), 110, 10) { public void run() { String username = usernamefield.
3: Storing data currentpasswordfield = new AutoTextEditField( _resources.getString(FIELD_CURRENTPASSWORD), ““); SeparatorField separator = new SeparatorField(); mainScreen.add(usernamefield); mainScreen.add(passwordfield); mainScreen.add(separator); mainScreen.add(currentusernamefield); mainScreen.add(currentpasswordfield); pushScreen(mainScreen); } private final class UserMainScreen extends MainScreen { protected void makeMenu( Menu menu, int instance ) { menu.add(saveItem); menu.add(getItem); super.
BlackBerry Java Development Environment Development Guide Task Steps Store data persistently. > In the class for the objects that you want to store, implement the Persistable interface.
3: Storing data Task Steps Retrieve the most recently saved object. > Invoke _data.lastElement(). public void run() { synchronized(store) { _data = (Vector)store.getContents(); if (!_data.isEmpty()) { RestaurantInfo info = (RestaurantInfo)_data.lastElement(); namefield.setText(info.getElement(RestaurantInfo.NAME)); addressfield.setText(info.getElement(RestaurantInfo.ADDRESS)); phonefield.setText(info.getElement(RestaurantInfo.PHONE)); specialtyfield.setText(info.getElement( RestaurantInfo.
BlackBerry Java Development Environment Development Guide public void run() { RestaurantInfo info = new RestaurantInfo(); info.setElement(RestaurantInfo.NAME, namefield.getText()); info.setElement(RestaurantInfo.ADDRESS, addressfield.getText()); info.setElement(RestaurantInfo.PHONE, phonefield.getText()); info.setElement(RestaurantInfo.WEBSITE, phonefield.getText()); info.setElement(RestaurantInfo.SPECIALTY, specialtyfield.getText()); _data.addElement(info); synchronized(store) { store.
3: Storing data public void run() { synchronized(store) { String websiteUrl = websitefield.getText(); if (websiteUrl.length() == 0) { Dialog.alert(_resources.getString(ALERT_NO_WEBSITE)); } else { BrowserSession visit = Browser.getDefaultSession(); visit.displayPage(websiteUrl); } } } }; static { _resources = ResourceBundle.getBundle( RestaurantResource.BUNDLE_ID, RestaurantResource.BUNDLE_NAME); store = PersistentStore.getPersistentObject(0xdec6a67096f833cL); // Key is hash of test.samples.restaurants.
BlackBerry Java Development Environment Development Guide _elements[id] = value; } } private final class RestaurantsMainScreen extends MainScreen { protected void makeMenu( Menu menu, int instance ) { menu.add(saveItem); menu.add(getItem); menu.add(phoneItem); menu.add(browserItem); super.makeMenu(menu, instance); } public void close() { Dialog.alert(_resources.getString(APP_EXIT)); super.close(); } } public Restaurants() { MainScreen mainScreen = new RestaurantsMainScreen(); mainScreen.
3: Storing data Use the MIDP record store Task Steps Create a record store. > Invoke openRecordStore() and specify true to indicate that the method should create the record store if the record store does not exist. Add a record. > Invoke addRecord(). Retrieve a record. > Invoke getRecord(int, byte[], int) and provide the following parameters: • a record ID • a byte array • an offset RecordStore store = RecordStore.openRecordStore("Contacts", true); int id = store.addRecord(_data.
BlackBerry Java Development Environment Development Guide 76
4 Managing data Data synchronization Backing up and restoring data Data synchronization Research In Motion (RIM) does not provide tools or applications for synchronizing data to remote data sources, so you must build the synchronization logic into your application. See the BlackBerry Java Development Environment Fundamentals Guide for more information about creating applications for sychronizing data on a BlackBerry® device.
BlackBerry Java Development Environment Development Guide Backing up and restoring data Add support for backing up data over the wireless network Task Steps Set up the BlackBerry® Enterprise Server to back up the application data using automatic wireless backup. > Activate the synchronization > process when the BlackBerry device starts. Implement the OTASyncCapable and CollectionEventSource interfaces. In the main method, create code that activates the synchronization process.
4: Managing data Task Steps Uniquely identify each record > type in a SyncCollection. Invoke the SyncCollectionSchema.setDefaultRecordType()method. The following example shows only one record type, so it uses the default record type: private static final int DEFAULT_RECORD_TYPE = 1; _schema = new SyncCollectionSchema(); _schema.setDefaultRecordType(DEFAULT_RECORD_TYPE); Uniquely identify each record > in a SyncCollection. Invoke the SyncCollectionSchema.setKeyFieldIDs() method.
BlackBerry Java Development Environment Development Guide Access a SyncCollection Task Steps Retrieve an instance of the SyncCollection from the RunTimeStore. > Retrieve the SyncCollection from the PersistentStore. 1. To make sure that the application works with only one version of the SyncCollection, implement a static method that returns an instance of the SyncCollection. static OTABackupRestoreContactCollection getInstance() { RuntimeStore rs = RuntimeStore.
4: Managing data Notify the system when a SyncCollection changes Task Steps Use a collection listener to The system invokes CollectionEventSource.addCollectionListener() to create a notify the system when a CollectionListener for each SyncCollection that the application makes available for wireless SyncCollection changes. backup. 1. Create a private vector object to store the collection of SyncCollection listeners for the application. private Vector _listeners; _listeners = new CloneableVector(); 2.
BlackBerry Java Development Environment Development Guide Using SyncObjects Task Steps Retrieve SyncObjects from the SyncCollection. > Implement the getSyncObjects() method. public SyncObject[] getSyncObjects() {//Retrieve the contact data. SyncObject[] contactArray = new SyncObject[_contacts.size()]; for (int i = _contacts.size() - 1; i >= 0; --i) { contactArray[i] = (SyncObject)_contacts.elementAt(i); } return contactArray; } Access a specific SyncObject.
4: Managing data import import import import import import import java.io.*; java.util.*; net.rim.device.api.collection.*; net.rim.device.api.i18n.*; net.rim.device.api.synchronization.*; net.rim.device.api.util.*; net.rim.device.api.system.*; /** * A collection enabled for OTA backup/restore. Basically a serially syncable collection * with few added interfaces.
BlackBerry Java Development Environment Development Guide _schema.setDefaultRecordType(DEFAULT_RECORD_TYPE); _schema.setKeyFieldIds(DEFAULT_RECORD_TYPE, KEY_FIELD_IDS); } static OTABackupRestoreContactCollection getInstance() { RuntimeStore rs = RuntimeStore.getRuntimeStore(); synchronized( rs ) { OTABackupRestoreContactCollection collection = (OTABackupRestoreContactCollection)rs.get( AR_KEY ); if( collection == null ) { collection = new OTABackupRestoreContactCollection(); rs.
4: Managing data int length = data.readShort(); byte[] bytes = new byte[length]; switch (data.readByte()) { case FIELDTAG_FIRST_NAME: data.readFully(bytes); //trim null-terminator contact.setFirst(new String(bytes).trim()); break; case FIELDTAG_LAST_NAME: data.readFully(bytes); contact.setLast(new String(bytes).trim()); break; case FIELDTAG_EMAIL_ADDRESS: data.readFully(bytes); contact.setEmail(new String(bytes).trim()); break; default: data.
BlackBerry Java Development Environment Development Guide } public boolean removeAllSyncObjects() { return false; //na } public SyncObject[] getSyncObjects() { SyncObject[] contactArray = new SyncObject[_contacts.size()]; for (int i = _contacts.size() - 1; i >= 0; --i) { contactArray[i] = (SyncObject)_contacts.elementAt(i); } return contactArray; } public SyncObject getSyncObject(int uid) { for (int i = _contacts.size() - 1; i >= 0; --i) { SyncObject so = (SyncObject)_contacts.elementAt(i); if ( so.
4: Managing data public String getSyncName(Locale locale) { return null; } public SyncConverter getSyncConverter() { return this; } public void beginTransaction() { _persist = PersistentStore.getPersistentObject(PERSISTENT_KEY); _contacts = (Vector)_persist.getContents(); } public void endTransaction() { _persist.setContents(_contacts); _persist.
BlackBerry Java Development Environment Development Guide Add support for backing up data with the BlackBerry Desktop Software Task Steps Let your application maintain a Implement the SyncCollection and SyncConverter interfaces by the same class or by separate collection of synchronized objects, classes, depending on the design of the application.
4: Managing data Activate synchronization when the BlackBerry device starts Task Steps Activate synchronization when the BlackBerry® device starts. The first time the BlackBerry device starts, the Alternate CLDC Application Entry Point project passes an argument to the application so that the application registers only once. > In the main method of the application, create code that activates the synchronization process.
BlackBerry Java Development Environment Development Guide package com.rim.samples.docs.restaurantssync; import import import import import import import import import import java.io.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.system.*; net.rim.device.api.util.*; java.util.*; net.rim.device.api.i18n.*; net.rim.device.api.synchronization.*; com.rim.samples.docs.resource.
4: Managing data _data = (Vector)store.getContents(); if (!_data.isEmpty()) { RestaurantInfo info = (RestaurantInfo)_data.lastElement(); namefield.setText(info.getElement(RestaurantInfo.NAME)); addressfield.setText(info.getElement(RestaurantInfo.ADDRESS)); phonefield.setText(info.getElement(RestaurantInfo.PHONE)); specialtyfield.setText(info.getElement( RestaurantInfo.SPECIALTY)); } } } }; static { _resources = ResourceBundle.getBundle(RestaurantsSyncResource.BUNDLE_ID, RestaurantsSyncResource.
BlackBerry Java Development Environment Development Guide public static final int SPECIALTY = 3; private int _uid; public int getUID() { return _uid; } public RestaurantInfo() { _elements = new String[4]; for ( int i = 0; i < _elements.length; ++i) { _elements[i] = ““; } } public RestaurantInfo(int uid) { _elements = new String[4]; for (int i = 0; i < _elements.
4: Managing data break; default: data.readFully(bytes); break; } } return info; } catch (EOFException e) { System.err.println(e.toString()); } return null; } public boolean convert(SyncObject object, DataBuffer buffer, int version) { if (version == getSyncVersion()) { if (object instanceof RestaurantInfo ) { String name = ((RestaurantInfo)object).getElement( RestaurantInfo.NAME); String phone = ((RestaurantInfo)object).getElement( RestaurantInfo.PHONE); String address = ((RestaurantInfo)object).
BlackBerry Java Development Environment Development Guide return this; } public String getSyncName() { return “Restaurant Synchronization Demo”; } public String getSyncName(Locale locale) { return getSyncName(); } public int getSyncObjectCount() { store = PersistentStore.getPersistentObject(KEY); _data = (Vector)store.getContents(); return _data.size(); } public SyncObject[] getSyncObjects() { SyncObject[] array = new SyncObject[_data.size()]; for (int i = _data.
4: Managing data public void setSyncObjectDirty(SyncObject object) { } public boolean updateSyncObject(SyncObject oldObject, SyncObject newObject) { return false; } public RestaurantsSync() { MainScreen mainScreen = new RestaurantsMainScreen(); mainScreen.setTitle(new LabelField( _resources.getString(APPLICATION_TITLE))); namefield = new AutoTextEditField(_resources.getString(FIELD_NAME), ““); addressfield = new AutoTextEditField( _resources.
BlackBerry Java Development Environment Development Guide 96
5 Using smart cards Smart cards Creating a smart card driver Smart cards Adding support for unsupported smart cards Smart cards are credit card-sized devices that are designed to store and transfer sensitive data. Smart card scenario Description Working with supported smart cards. The BlackBerry® device supports the following smart cards: Working with unsupported smart cards.
BlackBerry Java Development Environment Development Guide Task Steps Let a smart card driver to open a session with > a smart card. Implement SmartCard.openSessionImpl(SmartCardReaderSession). > Let a smart card driver to verify the compatibility of a smart card with a specific ATR. Implement SmartCard.checkAnswerToResetImpl(AnswerToReset) . Let a smart card driver to display settings or > properties. Implement SmartCard.displaySettingsImpl(Object).
5: Using smart cards private static final String LABEL = “RIM Sample”; private static final String DISPLAY_SETTINGS = “Show driver properties/settings now”; private static final String RSA = “RSA”; /** * Called on startup of the device. Register this driver with the smart card factory. * When you do this, you are automatically registered with the user authenticator * framework. */ public static void libMain( String args[] ) { SmartCardFactory.
BlackBerry Java Development Environment Development Guide /** * Determine if this smart card can display its settings. */ protected boolean isDisplaySettingsAvailableImpl( Object context ) { return true; } /** * Display this smart card’s settings. * This method will be invoked from the smart card options screen when * the user selects the driver and chooses to view the settings of that driver. * * This method could be called from the event thread.
5: Using smart cards Activate libMain() on startup Task Steps Create a libMain() method. > In your extension of the CryptoSmartCard class, implement the libMain() method. Run the libMain() method when the application starts. 1. Open the BlackBerry® Integrated Development Environment. 2. Create a new project for the smart card driver. 3. In the Workspace window, right-click the new project. 4. Select Properties. 5. On the Application tab, in the Project type field, type Library. 6.
BlackBerry Java Development Environment Development Guide */ package com.rim.samples.device.smartcard; import import import import import import net.rim.device.api.crypto.*; net.rim.device.api.crypto.certificate.*; net.rim.device.api.crypto.certificate.x509.*; net.rim.device.api.crypto.keystore.*; net.rim.device.api.smartcard.*; net.rim.device.api.util.*; /** * This class represents a communication session with a physical smart card.
5: Using smart cards * The method returns Integer.MAX_VALUE if an infinite number of attempts are allowed. */ protected int getMaxLoginAttemptsImpl() throws SmartCardException { return 5; } /** * Retrieve the remaining number of login attempts allowed (before the smart card will * lock, or Integer.MAX_VALUE if the smart card will not lock.) */ protected int getRemainingLoginAttemptsImpl() throws SmartCardException { return 4; } /** * Log into the smart card with the given password.
BlackBerry Java Development Environment Development Guide // Using friendly display name return new SmartCardID( idLong , ID_STRING, getSmartCard() ); } /** * Retrieve random data from the smart card’s internal Random Number Generator.
5: Using smart cards } stepProgressDialog( 1 ); privateKey = new RSAPrivateKey( cryptoSystem, new MyCryptoTokenData( smartCardID, ID_PKI ) ); keyStoreDataArray[ 0 ] = new CryptoSmartCardKeyStoreData( null, ID_CERT, privateKey, null, KeyStore.
BlackBerry Java Development Environment Development Guide if ( ( input.length < inputOffset + modulusLength ) || ( output.
5: Using smart cards Task Steps Determine if the token supports the > chosen operation using the current crypto system. Create a method that returns a Boolean value that indicates if the token object supports the current crypto system. Determine if the given key and crypto system support the type of encryption method. > Create a method that returns a Boolean value that indicates if the token object supports the chosen encryption method. Activate raw decryption.
BlackBerry Java Development Environment Development Guide Code sample: Creating a CryptoToken for private key RSA operations Example: MyRSACryptoToken.java /** * MyRSACryptoToken.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.device.smartcard; import import import import import import import import import net.rim.device.api.smartcard.*; net.rim.device.api.crypto.*; net.rim.device.api.crypto.keystore.*; net.rim.device.api.util.*; net.rim.device.
5: Using smart cards /** * Determine if this token supports the chosen operation using the provided system. * * @param cryptoSystem Crypto System to check against. * @param operation Operation to check: either KEY_GENERATION, * PUBLIC_KEY_OPERATION, PRIVATE_KEY_OPERATION,* or some other value * specific to the crypto system that indicates the operation to check.
BlackBerry Java Development Environment Development Guide /** * Perform a raw RSA signing. * * @param cryptoSystem Cypto system associated with the token. * @param privateKeyData RSA private key. * @param input Input data. * @param inputOffset First byte of the input data to read. * @param output The buffer for the output data. * @param outputOffset Position in the output buffer to receive the first written byte.
5: Using smart cards return; } } throw new RuntimeException(); } catch ( SmartCardSessionClosedException e ) { throw new CryptoTokenCancelException( e.toString() ); } catch ( SmartCardCancelException e ) { throw new CryptoTokenCancelException( e.toString() ); } catch( SmartCardRemovedException e ) { throw new CryptoTokenCancelException( e.toString() ); } catch ( SmartCardException e ) { throw new CryptoTokenException( e.toString() ); } finally { if ( smartCardSession != null ) { smartCardSession.
BlackBerry Java Development Environment Development Guide Store the private key file location Task Steps Store the location of the private key on the > smart card. In your application, implement the CryptoTokenPrivateKeyData interface. Associate the implementing class object with the smart card that contains the private key. Create an instance variable for storing the smart card ID. 1. private SmartCardID _id; 2.
5: Using smart cards */ private SmartCardID _id; /** * Location of the private key file on the smart card. */ private byte _file; /** * Constructs a new MyCryptoTokenData object * * @param id ID of the smart card containing the private key file * @param file Location of the private key file. */ public MyCryptoTokenData( SmartCardID id, byte file ) { _id = id; _file = file; } /** * Retrieve the ID of the key file containing the private key file. * * @return ID of the smart card.
BlackBerry Java Development Environment Development Guide 114
6 Managing memory Invoking a garbage collection operation Reduce the number of objects Managing low memory Invoking a garbage collection operation See the Garbage Collection in the BlackBerry Java Development Environment white paper and the BlackBerry Java Development Environment Fundamentals Guide for more information about garbage collection operations. Reduce the number of objects To use the BlackBerry® Integrated Development Environment to identify unnecessary objects, complete the following steps: 1.
BlackBerry Java Development Environment Development Guide Condition Description A low number of persistent object handles The number of persistent object handles falls below 1000. exist on a BlackBerry device. A low number of object handles exist on a The number of object handles falls below 1000. BlackBerry device. Use the LMM Task Steps Register your application with the LMM. 1. In the application, implement the LowMemoryListener method. 2.
7 Creating connections Fetching data using HTTP or TCP sockets Datagram connections Using port connections Fetching data using HTTP or TCP sockets Java™ applications for BlackBerry® devices can use standard HTTP, HTTPS, and TCP socket protocols to establish connections over the wireless network. When establishing the connection over the cellular network, an application can use one of two wireless gateways to proxy the connection to the Internet or the corporate intranet.
BlackBerry Java Development Environment Development Guide Using the wireless service providers Internet gateway Java™ applications for BlackBerry® devices can connect to the Internet using the Internet gateway that the wireless service provider provides. Most wireless service providers provide their own Internet gateway that offers direct TCP/IP connectivity to the Internet. Some operators also provide a WAP gateway that lets HTTP connections occur over the WAP protocol.
7: Creating connections Example: HTTPFetch.java /** * HTTPFetch.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.httpfetch; import import import import import import import import net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.i18n.*; net.rim.device.api.system.*; javax.microedition.io.*; java.io.*; com.rim.samples.docs.resource.
BlackBerry Java Development Environment Development Guide * the shared data in a synchronized block, but produces less overhead. */ private volatile boolean _start = false; private volatile boolean _stop = false; /** * Retrieve the URL. The synchronized keyword makes sure that only one * thread at a time can call this method on a ConnectionThread object. */ public synchronized String getUrl() { return _theUrl; } /** * Fetch a page.
7: Creating connections InputStream input = s.openInputStream(); // Extract data in 256 byte chunks. byte[] data = new byte[256]; int len = 0; StringBuffer raw = new StringBuffer(); while ( -1 != (len = input.read(data)) ) { raw.append(new String(data, 0, len)); } String text = raw.toString(); updateContent(text); input.close(); s.close(); } catch (IOException e) { System.err.println(e.toString()); // Display the text on the screen. updateContent(e.toString()); } // Reset the start state.
BlackBerry Java Development Environment Development Guide int i = 0; for (i = HTTP_PROTOCOL.length - 1; i >= 0; --i) { if ( -1 != lcase.indexOf(HTTP_PROTOCOL[i]) ) { validHeader = true; break; } } if ( !validHeader ) { // Prepend the protocol specifier if it is missing. url = HTTP_PROTOCOL[0] + url; } // Create a new thread for connection operations. _connectionThread.fetch(url); } // Display the content.
7: Creating connections Task Steps Retrieve login information from a BlackBerry device user. 1. Create code that manages an unauthorized HTTP connection attempt. int status = httpConn.getResponseCode(); switch (status) case (HttpConnection.HTTP_UNAUTHORIZED): 2. Create a run()method and within it implement a dialog object to ask the BlackBerry device user for login information. UiApplication.getUiApplication().invokeAndWait(new Runnable()) { public void run() { dialogResponse = Dialog.ask; (Dialog.
BlackBerry Java Development Environment Development Guide { int status = httpConn.getResponseCode(); switch (status) { case (HttpConnection.HTTP_OK): //Connection is 200 OK. //Download and process data. keepGoing = false; break; case (HttpConnection.HTTP_UNAUTHORIZED): //Connection is 401 UnAuthorized. //A login and password is required. //Retrieve the login information from somewhere.
7: Creating connections keepGoing = false; } break; default: //The connection failed for some other reason. //Handle failed connection. keepGoing = false; break; } } //Close the connection. s.close(); } catch (IOException e) { //Handle the exception. } Use HTTPS connections Task Steps Before opening an HTTPS connection, verify that the BlackBerry® device is within a wireless coverage area. > Use the CoverageInfo class and CoverageStatusListener interface of the net.rim.device.api.
BlackBerry Java Development Environment Development Guide • Applications that use socket connections typically require significantly more bandwidth than applications that use HTTP connections. Task Steps Before opening a socket connection, verify that the BlackBerry device is in a wireless coverage area. > Use the CoverageInfo class and CoverageStatusListener interface of the net.rim.device.api.system package to make sure that the BlackBerry device is in a wireless coverage area.
7: Creating connections Task Steps Before opening a datagram connection, verify that the BlackBerry® device is in > a wireless coverage area. Use the CoverageInfo class and CoverageStatusListener interface of the net.rim.device.api.system package to make sure that the BlackBerry device is in a wireless coverage area.
BlackBerry Java Development Environment Development Guide Using port connections Using a serial or USB connection, BlackBerry device ® applications can communicate with computer applications when they are connected to a computer using a serial or USB port. This type of connection also lets applications communicate with a peripheral device that plugs into the serial or USB port. Use USB or serial port connections Task Steps Open a USB or serial port connection. > Invoke Connector.
7: Creating connections Task Steps Send data on the Bluetooth connection. 1. Invoke openDataOutputStream() or openOutputStream(). DataOutputStream _dout = _bluetoothConnection.openDataOutputStream(); 2. Use the write methods on the output stream to write data. private static final int JUST_OPEN = 4; _dout.writeInt(JUST_OPEN); Receive data on the Bluetooth connection. 1. Create a non-main event thread to read data from the input stream. 2. Invoke openInputStream() or openDataInputStream().
BlackBerry Java Development Environment Development Guide */ package com.rim.samples.docs.bluetoothserialportdemo; import import import import import import import import import import java.io.*; javax.microedition.io.*; net.rim.device.api.bluetooth.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.i18n.*; net.rim.device.api.system.*; net.rim.device.api.util.*; com.rim.samples.docs.resource.
7: Creating connections public void close() { closePort(); super.close(); } } public static void main(String[] args) { new BluetoothSerialPortDemo().enterEventDispatcher(); } //constructor -------------------------------------------------------------public BluetoothSerialPortDemo() { MainScreen mainScreen = new BluetoothDemoScreen(); mainScreen.setTitle(new LabelField(_resources.getString(TITLE), LabelField.USE_ALL_WIDTH)); _infoField = new EditField(Field.READONLY); mainScreen.
BlackBerry Java Development Environment Development Guide } } _bluetoothConnection = null; _din = null; _dout = null; } // Open the serial port. private void openPort() { if (_bluetoothConnection != null) { closePort(); } new InputThread().start(); } private class InputThread extends Thread { public void run() { try { BluetoothSerialPortInfo[] info = BluetoothSerialPort.getSerialPortInfo(); if( info == null || info.length == 0 ) { invokeAndWait( new Runnable() { public void run() { Dialog.
7: Creating connections try { int type, offset, count; String value; _dout.writeInt(JUST_OPEN); _dout.flush(); for (;;) { type = _din.readInt(); if (type == INSERT) { offset = _din.readInt(); value = _din.readUTF(); insert(value, offset); } else if (type == REMOVE) { offset = _din.readInt(); count = _din.readInt(); remove(offset, count); } else if (type == JUST_OPEN) { // Send contents to desktop. value = _infoField.getText(); if (value == null || value.equals(““)) { _dout.writeInt(NO_CONTENTS); _dout.
BlackBerry Java Development Environment Development Guide }); } private void remove(final int offset, final int count) { invokeLater(new Runnable() { public void run() { _infoField.setCursorPosition(offset+count); _infoField.
8 Creating notifications Types of notification events Add a new event source Respond to deferred events Cancel events Customize system notifications for immediate events Types of notification events The notification API (net.rim.device.api.notification) lets you add custom events for your application and define the type of notifications that BlackBerry® device users receive when custom events occur.
BlackBerry Java Development Environment Development Guide Add a new event source Task Steps Create a unique long ID. 1. Define a long ID for each notification event. public static final long ID_1 = 0xdc5bf2f81374095L; 2. Open the BlackBerry® Integrated Development Environment. 3. In the BlackBerry IDE text pane, type a string. 4. Select the string. 5. Right-click the highlighted string. 6. Click Convert “string” to Long. Define a source object. 1.
8: Creating notifications Task Steps Perform initializations at the alternative entry point. Make sure that the string checked in the If statement matches the value you type in the Arguments passed to field in the BlackBerry IDE project. > In your main() method, perform any required initializations. public static void main (String[] args) { if ( args.length > 0 && args[0].equals(“autostartup”)) { //Application runs as a system module at startup.
BlackBerry Java Development Environment Development Guide } public NotificationsDemo() { MainScreen mainScreen = new NotificationsMainScreen(); mainScreen.setTitle(“Notification Demo App”); NotificationsManager.registerNotificationsEngineListener(ID_1, new NotificationsEngineListenerImpl(this)); pushScreen(mainScreen); } private MenuItem triggerItem = new MenuItem(null, 0, 100, 10) { public void run() { NotificationsManager.
8: Creating notifications } public void deferredEventWasSuperseded(long sourceID, long eventID, Object eventReference, Object context) { final long _eventID = eventID; er = eventReference; _app.invokeLater(new Runnable() { public void run() { NotificationsManager.cancelDeferredEvent(ID_1, _eventID, er, NotificationsConstants.
BlackBerry Java Development Environment Development Guide Respond to deferred events Task Steps Provide a custom UI notification. > Implement the NotificationsEngineListener interface. private static class ListenerImpl implements NotificationsEngineListener {...} Define behavior if an event is > superseded by another event at the same or higher priority level. Implement deferredEventWasSuperseded().
8: Creating notifications Cancel events Task Steps Cancel an immediate event. > Invoke cancelImmediateEvent(long, long, Object, Object), and then specify the source and event ID. Cancel a deferred event. > Invoke cancelDeferredEvent(long, long, Object, int, Object), and then specify the source and event ID. NotificationsManager.cancelImmediateEvent(ID_1, 0, this, null); NotificationsManager.cancelDeferredEvent(ID_1, 0, this, NotificationsConstants.
BlackBerry Java Development Environment Development Guide Task Steps Define a notification. > Implement startNotification(). public void startNotification(long consequenceID, long sourceID, long eventID, Object configuration, Object context) { LED.setConfiguration(500, 250, LED.BRIGHTNESS_50); LED.setState(LED.STATE_BLINKING); Alert.startAudio(TUNE, VOLUME); Alert.startBuzzer(TUNE, VOLUME); } Stop a notification. > Implement stopNotification().
8: Creating notifications Task Steps Define the notification configuration. 1. Create a class that implements SyncObject and Persistable. private static final class Configuration implements SyncObject, Persistable { 2. In the class, make sure that the SyncObject.getUID() method returns 0 if data synchronization is not required. public byte[] _data; public Configuration(byte[] data) { _data = data; } public int getUID() { return 0; } } Register a custom notification in the NotificationsManager.
BlackBerry Java Development Environment Development Guide public void startNotification(long consequenceID, long sourceID, long eventID, Object configuration, Object context) { LED.setConfiguration(500, 250, LED.BRIGHTNESS_50); LED.setState(LED.STATE_BLINKING); Alert.startAudio(TUNE, VOLUME); Alert.startBuzzer(TUNE, VOLUME); } public void stopNotification(long consequenceID, long sourceID, long eventID, Object configuration, Object context) { LED.setState(LED.STATE_OFF); Alert.stopAudio(); Alert.
8: Creating notifications } } } 145
BlackBerry Java Development Environment Development Guide 146
9 Managing applications Application manager Retrieve information about applications Register applications when the BlackBerry device starts Communicate with other applications Determine the services that are available to BlackBerry applications Listen for changes to IT policies Managing code modules Runtime store Share runtime objects Application manager The JVM on BlackBerry® devices includes an application manager that functions as the central dispatcher of operating system events for other Java™ applica
BlackBerry Java Development Environment Development Guide Register applications when the BlackBerry device starts To register the event source when the BlackBerry® device starts, create a separate project that acts as an alternative entry point to the main application. When the BlackBerry device starts, this project automatically runs as a system module and passes an argument to the application, allowing the application to perform any one-time initialization.
9: Managing applications Listen for changes to IT policies Task Steps Enable an application to use IT policies. > Implement the GlobalEventListener interface. Identify changes in IT policies. > Implement GlobalEventListener.eventOccurred(). Code example: Listening for changes to IT policies Example: ITPolicyDemo.java /** * ITPolicyDemo.java * Copyright (C) 2002-2005 Research In Motion Limited. */ package com.rim.samples.docs.itpolicy; import net.rim.device.api.system.*; import net.rim.device.api.
BlackBerry Java Development Environment Development Guide Retrieve module information Task Steps Retrieve a handle for a module. > Invoke getModuleHandle() and provide the name of the code module as a parameter. Retrieve specific information about a module. > Invoke the methods of the CodeModuleManager class and provide the module handle as a parameter to these methods. int handle = CodeModuleManager.getModuleHandle("test_module"); String name = CodeModuleManager.
9: Managing applications Task Steps Invoke deleteModuleEx(int, Boolean) and provide the following parameters: • the handle of the module to delete • a Boolean value to specify whether to delete the module and any data it contains, or to delete the module only if it does not have data associated with it Delete a module from the BlackBerry device > database. int handle = CodeModuleManager.getModuleHandle("test_module"); if( handle != 0 ) { Boolean success = CodeModuleManager.
BlackBerry Java Development Environment Development Guide Task Steps Replace a runtime object. 1. Invoke replace(). RuntimeStore store = RuntimeStore.getRuntimeStore(); String newmsg = "Some new text"; 2. Create a try-catch block to manage the ControlledAccessException that replace() throws if the runtime object with the specified ID does not exist. try { Object obj = store.replace( 0x60ac754bc0867248L, newmsg); } catch(ControlledAccessException e) { // Handle exception - insufficient permissions.
10 Using the messages application Create new messages Work with a message Work with folders Working with attachments Create new messages Task Steps Create a new blank text message. > Invoke invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_SMS parameter. Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments( MessageArguments.ARG_NEW_SMS)); Create a new populated text message. 1.
BlackBerry Java Development Environment Development Guide Task Steps Create a new populated email message. 1. Create and populate a new email message object. net.rim.blackberry.api.mail.Message m = new net.rim.blackberry.api.mail.Message(); Address a = new Address("mLi@rim.com", "Ming Li"); Address[] addresses = {a}; m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO , addresses); m.setContent("A message for you..."); m.setSubject("Email for you"); 2.
10: Using the messages application Work with a message Task Steps Receive a message notification. 1. Implement the FolderListener and StoreListener interfaces. public class MailTest implements FolderListener, StoreListener { ... } 2. Create code to manage a ControlledAccessException. Add a listener to the message store. 1. Retrieve the Store object. 2. Add a StoreListener instance to it. 3. Create a try-catch block to manage a NoSuchServiceException. try { Store store = Session.
BlackBerry Java Development Environment Development Guide Store store = Session.waitForDefaultSession.getStore(); Folder folder = Store.getFolder("SampleFolder"); 2. Retrieve the message objects from the folder. Iterate through the array and retrieve information, such as the sender and subject, to display to the BlackBerry® device user. Message[] msgs = folder.getMessages(); 3.
10: Using the messages application Task Steps Add the recipients. 1. 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 addRecipients() once for each recipient type. msg.addRecipients(Message.RecipientType.TO, toList); Specify the name and email address of > the sender. Invoke setFrom(Address). Add a subject line. > Invoke setSubject(String).
BlackBerry Java Development Environment Development Guide Forward a message Task Steps Create a message object. > Add the recipients. 1. Invoke forward() on a Message object. The subject line of a forwarded message is set automatically to FW:. Message fwdmsg = msg.forward(); Create an array of addresses. Address toList[] = new Address[1]; 2. Invoke addRecipients(int, Address[]). toList[0]= new Address("aisha.wahl@blackberry.com", "Katie Laird"); fwdmsg.addRecipients(Message.
10: Using the messages application Task Steps Retrieve an array of folders through a search. > Invoke findFolder(String). Folder[] folders = store.findFolder("Inbox"); Retrieve a folder by its name. 1. Invoke getFolder(String) and provide as a parameter the absolute path to the folder. Folder folder = store.getFolder("Mailbox - Aisha Wahl/Inbox/Projects"); 2. Create code to manage a FolderNotFoundException exception if the folder does not exist. Retrieve a folder by its ID. 1.
BlackBerry Java Development Environment Development Guide Working with attachments To open incoming message attachments and create outgoing attachments on the BlackBerry® device, use the mail API. A separate BodyPart on a Multipart message represents a message attachment. Create an attachment handler The BlackBerry® Attachment Service receives all attachments first. Third-party attachment handlers cannot override the default BlackBerry device behavior.
10: Using the messages application Task Steps Retrieve information about the attachment. > Invoke the methods of the SupportedAttachmentPart class. The SupportedAttachmentPart class represents an attachment with a corresponding viewer on the BlackBerry® device. An UnsupportedAttachmentPart represents an attachment that does not have a viewer on the BlackBerry device. public void run(Message m, SupportedAttachmentPart p) { ... String name = p.getName(); int size = p.
BlackBerry Java Development Environment Development Guide 162
11 Using PIM applications Using the calendar Using the address book Using tasks Using the calendar Start the calendar from your application Task Steps Open the calendar. > Invoke Invoke.invokeApplication(APP_TYPE_CALENDAR, CalendarArguments). View or change an event. 1. Retrieve an Event from the list of events. Event e = null; EventList el = (EventList)PIM.getInstance().openPIMList( PIM.EVENT_LIST, PIM.READ_WRITE ); Enumeration events = el.items(); e = (Event)events.nextElement(); 2.
BlackBerry Java Development Environment Development Guide Task Steps Open a new populated event. 1. Create a new Event using an EventList object. Event e = null; EventList el = (EventList)PIM.getInstance().openPIMList( PIM.EVENT_LIST, PIM.READ_WRITE ); e = el.createEvent(); 2. Add information to the Event object. e.addString( Event.SUMMARY, 0, "Go For A Walk" ); e.addString( Event.LOCATION, 0, "The Park" ); long start = System.currentTimeMillis() + 8640000; e.addDate( Event.START, 0, start ); e.
11: Using PIM applications Task Steps Add appointment information. > To verify that an item supports a field, invoke isSupportedField(int). if (event.isSupportedField(Event.SUMMARY)) { event.addString(Event.SUMMARY, Event.ATTR_NONE, "Meet with customer"); } if (event.isSupportedField(Event.LOCATION)) { event.addString(Event.LOCATION, Event.ATTR_NONE, "Conference Center"); } Date start = new Date(System.currentTimeMillis() + 8640000); if (event.isSupportedField(Event.START)) { event.addDate(Event.
BlackBerry Java Development Environment Development Guide Task Steps Save an appointment. To save an appointment, use the importEvent() method; you do not have to invoke commit(). 1. Before you save the appointment, to identify appointment fields that have changed since the appointment was last saved, invoke isModified(). 2. Invoke commit(). if(event.isModified()) { event.commit(); } Retrieve appointment information. 1. To retrieve an enumeration of appointments, invoke PIMList.items().
11: Using PIM applications Task Steps Import an appointment. 1. Write appointment to iCal. String[] dataFormats = PIM.eventSerialFormats(); ByteArrayOutputStream os = new ByteArrayOutputStream(); PIM.getInstance().toSerialFormat(event, os, "UTF8", dataFormats[0]); 2. Import appointment from iCal. ByteArrayInputStream is = new ByteArrayInputStream(outputStream.toByteArray()); 3. To return an array of PIMItem objects, invoke fromSerialFormat(java.io.InputStream is, java.lang.
BlackBerry Java Development Environment Development Guide private EventScreen _eventScreen; public static void main(String[] args) { new EventDemo().
11: Using PIM applications event = eventList.createEvent(); event.addString(Event.SUMMARY, PIMItem.ATTR_NONE, _subject.getText()); event.addString(Event.LOCATION, PIMItem.ATTR_NONE, _location.getText()); event.addDate(Event.END, PIMItem.ATTR_NONE, _endTime.getDate()); event.addDate(Event.START, PIMItem.ATTR_NONE, _startTime.getDate()); if(_repeat.getSelectedIndex() != 0) { event.setRepeat(setRule()); } // Save the appointment to the Calendar. event.commit(); //reset fields on screen _subject.
BlackBerry Java Development Environment Development Guide Using the address book Open the address book from your application Task Steps Open the address book. > From an application, invoke Invoke.invokeApplication(APP_TYPE_ADDRESSBOOK,AddressBookArgum ents). Open a contact using PIM data. 1. Create an instance of an AddressBookArguments object, specifying as a parameter a Contact object. AddressBookArguments abArg = AddressBookArguments(String arg, Contact contact); 2. Invoke Invoke.
11: Using PIM applications Task Steps Create a contact. To add a contact to the database, you must commit it. See “Save a contact” on page 173 for more information about committing contact data. > Invoke createContact() on a contacts list. Contact contact = contactList.
BlackBerry Java Development Environment Development Guide Task Steps Add contact information. 1. Invoke one of the following methods: • • • • • • addString() addStringArray() addDate() addInt() addBoolean() addBinary() 2. Before you set or retrieve a field, to verify that the item supports the field, invoke ContactList.isSupportedField(int). 3. To let fields store multiple values, use field attributes.
11: Using PIM applications Task Steps Change contact information. 1. To change the name and address fields, invoke the appropriate set method to replace an existing value with a new value. 2. Perform one of the following actions: • To change the fields that support a single value, retrieve the array and then change one or more indexes in the array before adding the array back to the Contact object. if (contact.countValues(Contact.NAME) > 0) { String[] newname = contact.getStringArray(Contact.
BlackBerry Java Development Environment Development Guide Task Steps Retrieve contact information. 1. Invoke PIMList.items(). 2. Perform one of the following actions: • To retrieve an array of IDs for fields that have data for a particular contact, invoke PIMItem.getFields() . • To retrieve the field values, invoke PIMItem.getString(). 3. When you invoke PIMList.items() to retrieve an enumeration of items in a contacts list, your application must sort items as necessary.
11: Using PIM applications Task Steps Import a contact. 1. To return an array of PIM items, invoke fromSerialFormat(). ByteArrayInputStream is = new ByteArrayInputStream(outputStream.toByteArray()); PIMItem[] pi = PIM.getInstance().fromSerialFormat(istream, "UTF8"); 2. To create a new contact using the PIM item, invoke ContactList.importContact(); ContactList contactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE); Contact contact2 = contactList.
BlackBerry Java Development Environment Development Guide { private ContactScreen _contactScreen; public static void main(String[] args) { new ContactsDemo().enterEventDispatcher(); } public ContactsDemo() { _contactScreen = new ContactScreen(); pushScreen(_contactScreen); } // Inner class. Creates a Screen to add a contact.
11: Using PIM applications try { ContactList contactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.WRITE_ONLY); Contact contact = contactList.createContact(); String[] name = new String[contactList.stringArraySize(Contact.NAME)]; // Add values to PIM item. if (!firstName.equals(““)) { name[Contact.NAME_GIVEN] = firstName; } if (!lastName.equals(““)) { name[Contact.NAME_FAMILY] = lastName; } contact.addStringArray(Contact.NAME, Contact.ATTR_NONE, name); contact.addString(Contact.
BlackBerry Java Development Environment Development Guide Using tasks Start the task application from your application Check for a ControlledAccessException if your application invokes a BlackBerry® application that you do not have permission to use or access. Task Steps Open the task application. The TaskArguments (net.rim.blackberry.api.invoke.TaskArguments) cannot be updated without changes to the task application. View or change a task. > Invoke Invoke.
11: Using PIM applications Use tasks Task Steps Open a task list. > 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) { //an error occurred return; } Create a task. > Add task information. 1. Invoke createToDo() on a task list.
BlackBerry Java Development Environment Development Guide Task Steps Change task information. 1. To replace an existing value with a new value, invoke the appropriate set method, such as setString(). 2. To determine if a value is already set for the field, invoke countValues(). 3. To change an existing value, use the corresponding set() method. 4. Create code to manage a FieldFullException, which a method such as addString() throws when a value already exists. if (task.countValues(ToDo.
11: Using PIM applications Task Steps Export a task. 1. To import or export PIM data, use an output stream writer to export tasks from the BlackBerry® device to a supported serial format. ToDoList todoList = (ToDoList)PIM.getInstance().openPIMList( PIM.TODO_LIST, PIM.READ_ONLY); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 2. To retrieve a string array of supported serial formats, invoke PIM.supportedSerialFormats(), and then specify the list type (PIM.TODO_List).
BlackBerry Java Development Environment Development Guide Code sample: Example: TaskDemo.java /** * TaskDemo.java * Copyright (C) 2002-2005 Research In Motion Limited. */ package com.rim.samples.docs.taskdemo; import java.io.*; import java.util.*; import javax.microedition.pim.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.i18n.*; import net.rim.device.api.system.*; import net.rim.device.api.util.
11: Using PIM applications _saveMenuItem = new SaveMenuItem(); setTitle(new LabelField(“Tasks Demo”, LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH)); _summary = new EditField(“Task Summary: “, ““); add(_summary); // In TODO.Priority, 0 to 9 is highest to lowest priority.
BlackBerry Java Development Environment Development Guide 184
12 Using the phone application Start the phone application from your application Use phone call functionality Listen for phone events Access and use call logs Start the phone application from your application To open the phone application from your application, invoke Invoke.invokeApplication(APP_TYPE_PHONE,PhoneArguments). The following excerpt from the Restaurants.java code sample on page 69 creates a menu item that invokes the phone application to call a restaurant.
BlackBerry Java Development Environment Development Guide Task Steps Retrieve phone call information. > Use the methods of the PhoneCall class. int threshold = 120; // Alert user if outgoing calls last longer than threshold. int elapsedTime = call.getElapsedTime(); // Use getStatusString() to retrieve status as an string. int status = call.getStatus(); if ((status == PhoneCall.STATUS_CONNECTED || status == PhoneCall.STATUS_CONNECTING) && call.
12: Using the phone application Listen for phone events Task Steps Listen for phone events. > Implement the PhoneListener interface. Register the phone listener. > Invoke Phone.addPhoneListener(). Remove a phone listener. > Invoke removePhoneListener(). To act on a particular event, implement one of the following methods.: Event Method A call is added to a conference call. callAdded(int) A BlackBerry® device user answers a call (user driven).
BlackBerry Java Development Environment Development Guide Task Steps Retrieve a call participant by phone number. The PhoneCallLogID class identifies participants in a phone call log by phone number. > Invoke PhoneCallLog.getParticipant(int) or ConferencePhoneCallLog.getParticipantAt(). PhoneCallLogID participant = phoneCallLog.getParticipant(); PhoneCallLogID participant = ConferencePhoneCallLog.getParticipant(); Retrieve the phone number type.
12: Using the phone application public class PhoneLogsDemo extends Application { private PhoneLogs _logs; private int _timeSpokenTo; static public void main(String[] args) { PhoneLogsDemo app = new PhoneLogsDemo(); app.enterEventDispatcher(); } private PhoneLogsDemo() { _logs = PhoneLogs.getInstance(); PhoneCallLogID participant = new PhoneCallLogID(“5551234”); _timeSpokenTo = findTimeSpokenTo(participant, PhoneLogs.
BlackBerry Java Development Environment Development Guide 190
13 Using the BlackBerry Browser Display content in the BlackBerry Browser Display content in a BlackBerry Browser field Display content in the BlackBerry Browser To display web content in the BlackBerry® Browser, use the net.rim.blackberry.api.browser package. Task Steps Retrieve a BlackBerry Browser session. Retrieving the default session overrides any open sessions on the BlackBerry device. > Retrieve the default BrowserSession object by invoking the static method Browser.getDefaultSession().
BlackBerry Java Development Environment Development Guide Display content in a BlackBerry Browser field To display web content in a BlackBerry® Browser field, use the net.rim.blackberry.api.browser package. Task Steps Access a rendering session. 1. Invoke RenderingSession.getNewInstance(). 2. Store the returned rendering session handle in a RenderingSession object. RenderingSession _renderingSession = RenderingSession.getNewInstance();. Define callback functionality for a rendering session.
13: Using the BlackBerry Browser Task Steps Set rendering options. > Override BrowserContent.getRenderingOptions(). Your application uses the default rendering options if you do not override BrowserContent.getRenderingOptions(). Manage events. > Implement RenderingApplication.eventOccurred(), specifying the actions that occur when a specific rendering event occurs.
BlackBerry Java Development Environment Development Guide Code sample: Using the BlackBerry Browser Example: BrowserFieldSampleApplication.java /** * DefaultRenderingApplication.java * Copyright (C) 2004-2005 Research In Motion Limited. */ package com.rim.samples.docs.browser; import import import import import import import import java.io.IOException; javax.microedition.io.HttpConnection; net.rim.device.api.browser.field.*; net.rim.device.api.io.http.HttpHeaders; net.rim.device.api.system.
13: Using the BlackBerry Browser BrowserContent browserContent = null; try { browserContent = _renderingSession.getBrowserContent(connection, this, e); if (browserContent != null) { Field field = browserContent.getDisplayableContent(); if (field != null) { synchronized (Application.getEventLock()) { _mainScreen.deleteAll(); _mainScreen.add(field); } } browserContent.finishLoading(); } } catch (RenderingException re) { } finally { SecondaryResourceFetchThread.doneAddingImages(); } } /** * @see net.rim.
BlackBerry Java Development Environment Development Guide RedirectEvent e = (RedirectEvent) event; String referrer = e.getSourceURL(); switch (e.getType()) { case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT : // show redirect message Application.getApplication().invokeAndWait(new Runnable() { public void run() { Status.show(“You are being redirected to a different page...”); } }); break; case RedirectEvent.TYPE_JAVASCRIPT : break; case RedirectEvent.
13: Using the BlackBerry Browser } /** * @see net.rim.device.api.browser.RenderingApplication#getAvailableWidth(net.rim.device.api.brows er.BrowserContent) */ public int getAvailableWidth(BrowserContent browserField) { // field has full screen return Graphics.getScreenWidth(); } /** * @see net.rim.device.api.browser.RenderingApplication#getHistoryPosition(net.rim.device.api.brow ser.
BlackBerry Java Development Environment Development Guide HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null); return connection; } else { // If the referrer is not null, set up the connection on a separate thread. SecondaryResourceFetchThread.enqueue(resource, referrer); } return null; } /** * @see net.rim.device.api.browser.RenderingApplication#invokeRunnable(java.lang.
14 Using location information Types of location information Using BlackBerry Maps Locating BlackBerry devices using GPS information Types of location information Information Type Description Location Based Services Location Based Services is a location-enabled platform that lets an application use location data on a BlackBerry® device or BlackBerry Enterprise Server. GPS The Location API (javax.microedition.location) lets applications retrieve the GPS location of the BlackBerry device.
BlackBerry Java Development Environment Development Guide Create a location document to display map data Location document tags Tag name Tag number Type Description lat 1 int Latitude in degrees * 100000 lon 2 int Longitude in degrees * 100000 zoom 3 int Zoom label 4 String Name description 5 String Description Location document structure When creating a location document, use the following structure: "; 2.
BlackBerry Java Development Environment Development Guide Method Constant Description Assisted GPS_AID_MODE_ASSIST The assisted method uses the wireless network to provide ephemeris GPS satellite data to the BlackBerry® device chip. Advantages • Provides the GPS location faster than the autonomous method and more accurately than the cellsite method. Requirements • Autonomous Requires network connectivity and wireless service provider support.
14: Using location information Recommended GPS location method Horizontal accuracy Vertical accuracy Cost Power consumption autonomous required required allowed low, medium, or no requirement first fix: assisted subsequent fixes: autonomous required required allowed high autonomous not required not required not allowed medium, high, or no requirement assisted not required not required allowed medium or no requirement first fix: assisted not required not required allowed high n
BlackBerry Java Development Environment Development Guide Retrieve BlackBerry device GPS location information Task Steps Specify a response time for retrieving the The time it takes to retrieve the location of the BlackBerry device for the first time depends on location of the BlackBerry® device. several factors, such as the selected GPS mode and the GPS signal strength. In autonomous method, typical times are less than 2 minutes. In assisted mode, typical times are less than 30 seconds.
14: Using location information Task Steps Register a location listener. You can associate only one location listener with a particular GPS location provider. Applications typically listen for updates on a separate thread. 1. Implement the LocationListener interface. 2. Register your implementation by invoking LocationProvider.setLocationListener(). import javax.microedition.LocationProvider.*; public class SampleLocationApp { public static void main (string[] Args) { // ... provider.
BlackBerry Java Development Environment Development Guide Send required PDE data to BlackBerry devices that run on the CDMA network Before your application tries to use the Location API, send your PDE data to the wireless transceiver of the BlackBerry device by invoking the setPDEInfo(String ip, int port) method of the GPSSettings class (see the net.rim.device.api.gps package), using as parameters the PDE IP and port number that the CDMA wireless service provider provides to you.
14: Using location information private static float[] _altitudes; private static float[] _horizontalDistances; private static PersistentObject _store; // Initialize or reload the persistent store. static { _store = PersistentStore.getPersistentObject(ID); if(_store.getContents()==null) { _previousPoints= new Vector(); _store.setContents(_previousPoints); } _previousPoints=(Vector)_store.
BlackBerry Java Development Environment Development Guide } // Constructors. ------------------------------------------------------------public GPSDemo() { // Used by waypoints; represents the time since the last waypoint. _startTime = System.currentTimeMillis(); _altitudes=new float[GRADE_INTERVAL]; _horizontalDistances=new float[GRADE_INTERVAL]; _messageString= new StringBuffer(); MainScreen screen = new GPSDemoScreen(); screen.setTitle(new LabelField(_resources.getString(GPSDEMO_TITLE), LabelField.
14: Using location information } }; // Cache the close menu item for reuse. private MenuItem _close = new MenuItem(_resources, GPSDEMO_MENUITEM_CLOSE, 110, 10) { public void run() { System.exit(0); } }; /* Invokes the Location API with the default criteria. */ private boolean startLocationUpdate() { boolean retval = false; try { _locationProvider = LocationProvider.
BlackBerry Java Development Environment Development Guide } /* Marks a point in the persistent store. Calculations are based on * all data collected since the previous waypoint, or from the start * of the application if no previous waypoints exist. */ private void markPoint() { long current = System.currentTimeMillis(); WayPoint p= new WayPoint(_startTime, current, _wayHorizontalDistance, _verticalDistance); addWayPoint(p); // Reset the waypoint variables.
14: Using location information * Rounds off a given double to the provided number of decimal places * @param d the double to round off * @param decimal the number of decimal places to retain * @return a double with the number of decimal places specified */ private static double round(double d, int decimal) { double powerOfTen = 1; while (decimal-- > 0) { powerOfTen *= 10.
BlackBerry Java Development Environment Development Guide // Running total of the vertical distance gain. float altGain = _altitudes[GRADE_INTERVAL-1] - _altitudes[GRADE_INTERVAL-2]; if (altGain > 0) _verticalDistance = _verticalDistance + altGain; captureCount += _interval; // If we’re mod zero then it’s time to record this data.
14: Using location information sb.append(“\n”); sb.append(“Altitude: “); sb.append(altitude); sb.append(“ m”); sb.append(“\n”); sb.append(“Heading relative to true north: “); sb.append(heading); sb.append(“\n”); sb.append(“Speed : “); sb.append(speed); sb.append(“ m/s”); sb.append(“\n”); sb.append(“Grade : “); if(Float.isNaN(grade))sb.append(“ Not available”); else sb.append(grade+” %”); GPSDemo.this.updateLocationScreen(sb.
BlackBerry Java Development Environment Development Guide 214
15 Creating push applications Types of push applications Types of push requests Write a client push application Write a server-side push application Create a RIM push request Create a PAP push request Code sample: Pushing data to an application that listens on a BlackBerry device Types of push applications Push applications send web content or data to specific BlackBerry® device users.
BlackBerry Java Development Environment Development Guide Types of push requests Applications can send two types of push requests: Request Supported tasks Push storage RIM push • • • sending a server-side push submission specifying a reliability mode for the push submission specifying a deliver-before time stamp for the push submission requesting a result notification of the push submission specifying a deliver-after time stamp for the push submission RIM pushes are stored in RAM.
15: Creating push applications Write a client push application Task Steps Create a listening thread. > Determine if a BlackBerry® device is in 1. a wireless coverage area. Send and receive data on a separate thread so that you do not block the main event. Create code to check if the IPPP service book can be routed. if( ServiceBook.getSB().getRecordByUidAndCid( serviceUID, "IPPP" ) == null ) { // There is no service book return false; } if( ServiceRouting.getInstance().
BlackBerry Java Development Environment Development Guide Task Steps Close the stream connection notifier. > Invoke close() on the stream connection notifier. _notify.close(); Code sample: Listening for data from a web server Example: HTTPPushDemo.java /** * The client side of a simple HTTP Push system. * This application will listen for image data on the specified port and * render the data when it arrives. * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.
15: Creating push applications private boolean _stop = false; private StreamConnectionNotifier _notify; public synchronized void stop() { _stop = true; try { _notify.close(); // Close the connection so thread returns. } catch (IOException e) { System.err.println(e.toString()); } catch (NullPointerException e) { // The notify object likely failed to open, due to an IOException.
BlackBerry Java Development Environment Development Guide input.close(); stream.close(); data = db.getArray(); } catch (IOException e1) { // a problem occurred with the input stream // however, the original StreamConnectionNotifier is still valid System.err.println(e1.toString()); if ( input != null ) { try { input.close(); } catch (IOException e2) { } } if ( stream != null ) { try { stream.close(); } catch (IOException e2) { } } } } _notify.
15: Creating push applications } } // Constructor. public HTTPPushDemo() { _mainScreen = new HTTPMainScreen(); _mainScreen.setTitle(new LabelField(_resources.getString(HTTPPUSHDEMO_TITLE), LabelField.USE_ALL_WIDTH)); _infoField = new RichTextField(); _mainScreen.add(_infoField); _mainScreen.add(new SeparatorField()); _imageField = new RichTextField(); _mainScreen.add(_imageField); _listeningThread = new ListeningThread(); _listeningThread.start(); _infoField.setText(_resources.
BlackBerry Java Development Environment Development Guide Write a server-side push application To create a push application, you can use any programming language that can establish an HTTP connection . The following sections use standard Java™ to demonstrate a server-side push application. Task Steps Specify a port. If you create a client/server push application, you must make sure that the server-side application uses a port number other than 80, 443, 7874, and 8080 to deliver push data.
15: Creating push applications Task Steps Read the server response. 1. To access an input stream, invoke getInputStream(). InputStream ins = conn.getInputStream(); 2. Determine the size of the content. If the size of the content is non zero, open a data input stream, and then retrieve the content. int contentLength = conn.getContentLength(); if (contentLength > 0) { byte[] someArray = new byte [contentLength]; DataInputStream dins = new DataInputStream(ins); dins.readFully(someArray); System.out.
BlackBerry Java Development Environment Development Guide Work with a server-side push request Send a request to cancel a PAP push submission. 1. Use the cancel-message push-id header. For example: 2. To specify the address to which the application submitted the push message, use the address address-value header. This is a required tag. PAGE 22515: Creating push applications Create a RIM push request Task Steps Push content to one or multiple BlackBerry® device users using a RIM push request. 1.
BlackBerry Java Development Environment Development Guide Create a PAP push request See “Appendix: XML control entity attributes” on page 275 for more information about XML control entity attributes. Task Steps Push content to one or multiple 1. BlackBerry® device users using PAP. To push data to a single BlackBerry device user using PAP, send an HTTP POST request using the following format: http://:/pap - The URL to send the PAP push to.
15: Creating push applications Code sample: Pushing data to an application that listens on a BlackBerry device The HTTPPush.java sample application, which uses standard Java™, sends a string of text to a listening client application on the BlackBerry® device using either a RIM push or a PAP push. The application pushes data based on an email address. To test push applications with the BlackBerry device simulator, define a mapping between the email address and the BlackBerry device simulator PIN (2100000A).
BlackBerry Java Development Environment Development Guide //constructors -------------------------------------------------------------/** Creates a new HTTPPushServer instance*/ public HTTPPushServer() { initComponents (); pack (); //sizing code for the main frame setSize(_panel.getWidth(), _panel.
15: Creating push applications setTitle(java.util.ResourceBundle.getBundle(“com/rim/samples/docs/httppush/ resources”).getString(“HTTPPushServer.title”)); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); _panel.setLayout(null); _panel.setPreferredSize(getSize()); _textArea.setToolTipText(java.util.ResourceBundle.getBundle(“com/rim/samples/docs/ httppush/resources”).getString(“HTTPPushServer.
BlackBerry Java Development Environment Development Guide getContentPane().add(_panel); _panel.setBounds(0, 0, 300, 450); }//GEN-END:initComponents private void sendButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sendButtonMouseClicked String text =_textArea.getText(); if(_rimButton.isSelected()) postData(text); else if(_papButton.
15: Creating push applications System.out.println(new String(someArray)); } conn.disconnect(); } catch (IOException e) { System.err.println(e); } } private void readPapTemplate() { try { String papFilename = “com/rim/samples/docs/httppush/pap_push.txt”; InputStream ins = new BufferedInputStream(new FileInputStream(papFilename)); ByteArrayOutputStream bouts = new ByteArrayOutputStream(); copyStreams(ins, bouts); this.requestTemplate = new String(bouts.
BlackBerry Java Development Environment Development Guide mdsConn.setRequestMethod(“POST”); mdsConn.setAllowUserInteraction(false); mdsConn.setDoInput(true); mdsConn.setDoOutput(true); String output output output String output = requestTemplate.replaceAll(“\\$\\(pushid\\)”, pushId); = output.replaceAll(“\\$\\(boundary\\)”, boundary); = output.replaceAll(“\\$\\(notifyURL\\)”, ““ + notifyURL); = output.replaceAll(“\\$\\(pin\\)”, ““ + _pinField.getText()); deliveryMethod = “confirmed”; output = output.
15: Creating push applications bytesRead = ins.read(buffer); System.out.println(buffer); if (bytesRead <= 0) break; outs.write(buffer, 0, bytesRead); } } /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm System.exit (0); }//GEN-LAST:event_exitForm /** * @param args the command line arguments */ public static void main (String args[]) { new HTTPPushServer().show (); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.
BlackBerry Java Development Environment Development Guide output.close(); clientSocket.close(); } catch (SocketTimeoutException ste) { System.out.println(“Notification connection timeout. Restarting...”); } serverSocket.close(); } } catch (Exception exception) { exception.
16 Localizing applications Storing text strings in resource files Storing resources for a locale Files required for localization Add localization support Code sample: Storing text strings in separate resources for locales Retrieve strings from a resource file Code sample: Retrieving strings from a resource file Storing text strings in resource files Design applications so that they are localized (adapted to specific languages and regions) without coding changes.
BlackBerry Java Development Environment Development Guide Files required for localization File required for localization Description Example Resource header This file defines descriptive keys for each localized string. AppName.rrh When the BlackBerry® Integrated Development Environment builds a project, it creates a resource interface with Resource appended to the .rrh file name. For example, if you create AppName.rrh, the interface name is AppNameResource.
16: Localizing applications Task Steps Add resource content files. Create resource content files in the folder where the .java file exists. For example, in the folder that contains CountryInfo.java, create CountryInfo.rrc (root locale), CountryInfo_en.rrc (English), and CountryInfo_fr.rrc (French). 1. On the File menu, click New. 2. Type a file name and location. 3. Click OK. 4. Click Yes. 5. Leave the file empty. 6. To add the .rrc file to the application project, right-click the .
BlackBerry Java Development Environment Development Guide package com.rim.samples.docs.countryinfo; import import import import import import net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.system.*; net.rim.device.api.i18n.*; com.rim.samples.docs.resource.*; /* This sample demonstrates how to store text strings in separate resource files for specific locales rather than providing text strings directly in the code.
16: Localizing applications private MenuItem _closeItem = new MenuItem(_resources, MENUITEM_CLOSE, 200000, 10) { public void run() { onClose(); } }; protected void makeMenu( Menu menu, int instance ) { menu.add(_viewItem); menu.add(_closeItem); } private class InfoScreen extends MainScreen { public InfoScreen() { super(); LabelField lf = new LabelField(); BasicEditField popField = new BasicEditField( _resources.getString(FIELD_POP), null, 20, Field.
BlackBerry Java Development Environment Development Guide Retrieve strings from a resource file Task Steps Retrieve the resource bundle. When the BlackBerry Integrated Development Environment builds your project, it creates an interface for each .rrh resource file. 1. Import the interfaces that the BlackBerry IDE creates. import com.rim.samples.docs.resource.CountryInfoResource; 2. Create a ResourceBundle object to contain the localized resources, such as strings, for an application.
16: Localizing applications import import import import import net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.system.*; net.rim.device.api.i18n.*; com.rim.samples.docs.resource.*; /* This sample demonstrates how to store text strings in separate resource files for specific locales rather than providing text strings directly in the code. In your source code, you retrieve the string from the resource to display the appropriate text for the user locale.
BlackBerry Java Development Environment Development Guide onClose(); } }; protected void makeMenu( Menu menu, int instance ) { menu.add(_viewItem); menu.add(_closeItem); } private class InfoScreen extends MainScreen { public InfoScreen() { super(); LabelField lf = new LabelField(); BasicEditField popField = new BasicEditField( _resources.getString(FIELD_POP), null, 20, Field.READONLY); BasicEditField langField = new BasicEditField( _resources.getString(FIELD_LANG), null, 20, Field.
16: Localizing applications Manage resource files for application suites When creating a suite of applications, organize the resources into separate projects for each locale. Task Steps Create resource projects. 1. Open the BlackBerry® Integrated Development Environment. 2. Create a project for each resource bundle (locale), including the root locale. 3.
BlackBerry Java Development Environment Development Guide 244
17 Testing applications Testing applications using the BlackBerry IDE Testing applications using BlackBerry devices Debugging applications Testing applications using the BlackBerry IDE After you develop and compile your application, you should test it on the BlackBerry® device. The most common first step is to set up the BlackBerry Integrated Development Environment to use a BlackBerry device simulator for testing.
BlackBerry Java Development Environment Development Guide Testing applications using BlackBerry devices After testing your application on the BlackBerry® device simulator, load your application on a live BlackBerry device. When the application loads, you can open and test its functionality and performance. For debugging purposes, attach your BlackBerry device to the BlackBerry Integrated Development Environment debugger to step through your application code.
17: Testing applications Task Steps Remove a breakpoint. 1. Open the source file. 2. In the Edit window, click the line of code that contains the breakpoint you want to remove. 3. On the Debug menu, click Breakpoint > Delete Breakpoint at Cursor. Remove all breakpoints. 1. On the View menu, click Breakpoints. 2. In the breakpoints pane, click Delete All.
BlackBerry Java Development Environment Development Guide Manage a debugging session Task Steps Continue a debugging session. > To resume running the application, on the Debug menu, click Continue. End a debugging session in the BlackBerry® > device simulator. In the BlackBerry device simulator, on the File menu, click Quit. End a debugging session in the BlackBerry Integrated Development Environment. In the main window, on the Debug menu, click Stop Debugging. 1. 2. Read the warning message. 3.
17: Testing applications Install .debug files on your computer To debug applications using a BlackBerry® device, the .debug files in the BlackBerry Integrated Development Environment must match the software version number of the BlackBerry device. BlackBerry device simulator packages contain .debug files for specific BlackBerry devices. 1. Download the BlackBerry device simulator package for your BlackBerry device software version number from the BlackBerry Developer Zone at: http://blackberry.
BlackBerry Java Development Environment Development Guide You can now run your applications on the BlackBerry device and use the BlackBerry Integrated Development Environment debugging tools to test and optimize your application. Step through lines of code in an application In the main window, on the Debug menu, perform any of the following tasks: Task Steps Step over a method call. The BlackBerry® Integrated Development Environment debugger moves to the next line of code.
17: Testing applications 10. Repeat steps 1 through 8, setting breakpoints closer together until they converge on the memory leak. Display objects in memory to locate object leaks Object leaks can cause the JVM to run out of flash memory, which forces a BlackBerry® device to reset.
BlackBerry Java Development Environment Development Guide Right-click an object, and then click Show Recursive References To @nnnnnnnn to display all objects that reference the selected object. An object can indirectly display another object through it. Note: This operation might take a long time to complete. Show the source code or static Double-click Code referencing @nnnnnnnn or Static referencing @nnnnnnnn line to display that source code or static.
17: Testing applications Evaluate (watch) Java expressions The Watch pane lets you specify variables and expressions to watch continuously while debugging your application. 1. Right-click the Watch pane. 2. Perform one of the following tasks: Task Steps Set a new watch. > Click Add Watch. Remove a watch. > Click Delete. Remove all watches. > Click Delete All. See "View threads" on page 253 for more information about viewing the format of threads appearing in the Watch pane.
BlackBerry Java Development Environment Development Guide Make a thread current When you make a thread current, the Call Stack changes to display the calls for the thread. Other windows might display current information relating to the new current thread. 1. From a variable window, right-click a thread. 2. Select Make thread current.
17: Testing applications View the source of a logging message > In the event log pane, on the Build tab, double-click the error message. View classes Select a subset of classes Type the Class Name Prefix and press ENTER. For example, type java.lang. In the classes pane, classes that start with the string typed in the Class Name Prefix field appear. 1. In the classes pane, right-click a class. 2.
BlackBerry Java Development Environment Development Guide Drop-down list Option Description Sort method by Count The profiler tool sorts methods in the profile pane by the number of times the application executed the item. Profiled data (select in “What to profile”) The profiler tool sorts methods in the profile pane by the data you choose to profile. Time (clock ticks) The profiler tool considers execution time (measured in clock ticks).
17: Testing applications 13. In the profile pane, click Refresh. This action retrieves all accumulated profile data from the JVM. This action does not clear Profiler data, so running an application again adds to the data. • Use profile views to view information about the section of code that you just ran. 14. Click Save to save the contents of the profile pane to a comma separated values (.csv) file. View profile data The profile pane has three views.
BlackBerry Java Development Environment Development Guide Run the Coverage tool 1. Set two or more breakpoints in your code. 2. Run the application to the first breakpoint. 3. On the View menu, click Coverage. 4. To reset the information to 0, in the coverage pane, click Clear. 5. Run the application to the next breakpoint. 6. To display the percentage of code that you ran since you clicked Clear, in the coverage pane, click Refresh. The Coverage pane displays the percentage of code that you ran.
17: Testing applications Start the BlackBerry email simulator The BlackBerry® email simulator lets you send and receive email messages between the BlackBerry device simulator and an actual email account, without a BlackBerry Enterprise Server. To retrieve the BlackBerry email simulator, download the BlackBerry Email and MDS Services Simulator Package from the BlackBerry Developer Zone web site: www.blackberry.com/developers 1.
BlackBerry Java Development Environment Development Guide Working with compiled applications When you build a project using the BlackBerry® Integrated Development Environment, the BlackBerry IDE compiles your source files into Java™ bytecode, performs preverification, and creates a single .cod file and .jad file for an application. If an application contains more than 64 KB of bytecode or resource data, the BlackBerry IDE creates a .cod file that contains sibling .cod files. To determine if a .
17: Testing applications Task Steps Save an application .cod file from the BlackBerry > device to your computer. Issue a command using the following format: javaloader save <.cod file> For example: javaloader.exe save MyApplication.cod Save application .cod files listed in the same .jad > file from the BlackBerry device to your computer. Issue a command using the following format: Save application .cod files stored in the same CodeModuleGroup from the BlackBerry device to your computer.
BlackBerry Java Development Environment Development Guide 262
18 Packaging and distributing applications Preverify applications Determine if your code requires signatures Register to use RIM controlled APIs Request code signatures Distributing applications over the wireless network Distributing applications with the BlackBerry Desktop Software Preverify applications To reduce the amount of processing the BlackBerry® device performs when you load your application, partially verify your classes.
BlackBerry Java Development Environment Development Guide If you use any of the following BlackBerry API packages, your application requires code signatures before you can load it on a BlackBerry device: • net.rim.blackberry.api.browser • net.rim.blackberry.api.invoke • net.rim.blackberry.api.mail • net.rim.blackberry.api.mail.event • net.rim.blackberry.api.menuitem • net.rim.blackberry.api.options • net.rim.blackberry.api.pdap • net.rim.blackberry.api.phone • net.rim.blackberry.api.phone.
18: Packaging and distributing applications 6. In the Private Key Password field, type a password of at least eight characters. The private key password protects your private key. If you lose this password, you must register again with RIM. If this password is stolen, contact RIM immediately. 7. Click Register. 8. Click Exit. Restricted access to code signatures The BlackBerry® Signing Authority Tool administrator might place restrictions on your .csi file to limit your access to code signatures.
BlackBerry Java Development Environment Development Guide Request code signatures using a proxy server Task Steps Register signature keys using a proxy server. You can register each .csi file only once. 1. At the command prompt, browse to the BlackBerry® Signature Tool bin directory. For example: C:\Program Files\Research In Motion\BlackBerry JDE 4.2.0\bin 2. Type the following command: Java -jar -Dhttp.proxyHost= -Dhttp.proxyPort=80 SignatureTool.jar .
18: Packaging and distributing applications Distributing applications over the wireless network Method Description User-initiated wireless pull Developers can post their compiled applications to a public or private web site, and BlackBerry® device users can download the application over the wireless network by pointing the web browser on their BlackBerry devices to this URL. When a BlackBerry device user visits the URL, the web browser prompts the BlackBerry device user to install the application.
BlackBerry Java Development Environment Development Guide Task Steps Extract sibling .cod files. To ensure a BlackBerry device user does not override the original .cod file, on the web server, extract the sibling .cod files into a different directory than the directory where the original file exists. 1. Unzip the original .cod file and extract the sibling .cod files. 2. Place each sibling .cod file on a web server. 3. In the .jad file, list the sibling .cod files separately.
18: Packaging and distributing applications Distributing applications with the BlackBerry Desktop Software Deployment method Description Application Loader tool of the BlackBerry® Desktop Manager The Application Loader tool of the BlackBerry Desktop Manager lets you install third-party applications as well as updated system software for the BlackBerry device. It lets BlackBerry device users download applications on their computers and install them on their BlackBerry devices.
BlackBerry Java Development Environment Development Guide My_application.cod 5. Update the application, description, and other tags to reflect the purpose of the .alx file. ... This will push the COD only to 8700s Example: Load an application on a specific BlackBerry device Alien This will push the COD only to 8700s 2006.02.
18: Packaging and distributing applications net_rim_resource.cod net_rim_resource__en.cod net_rim_resource__fr.cod 4. To define an explicit dependency on another application or library, use the tag. Example: Sample .alx file for an application with a nested module Sample Contacts Application Provides the ability to store a list of contacts.
BlackBerry Java Development Environment Development Guide • Round brackets () indicate exclusive (open) range matching. • Missing lower ranges imply 0. • Missing upper ranges imply infinity. For example, [4.0,) indicates any version between 4.0 and infinity. The following example prevents modules from loading on versions of the BlackBerry Device Software earlier than version 4.0. ...
A Appendix: The command line compiler Using the command line compiler Using the command line compiler The BlackBerry® Java™ Development Environment includes RAPC, a command line compiler. RAPC compiles .java and .jar files into .cod files that you can run in the BlackBerry device simulator or load onto a BlackBerry device. The rapc.exe file exists in the bin subdirectory of your BlackBerry JDE installation. Note: net_rim_api.jar is required as an input file when you invoke RAPC.
BlackBerry Java Development Environment Development Guide Option Option format Description -warnkey =0xNNNNNNNN[;...] Generate a warning if you need to add a key to the .csl file. -workspace = Add the to the .debug file for BlackBerry Integrated Development Environment browsing. filename_1.java [] Specify the .java file name if you are compiling from .java files. JAR_filename.jar Specify the .jar file name if compiling from a .jar file.
B Appendix: XML control entity attributes Using XML control entity attributes Using XML control entity attributes Use the PAP DTD to specify the following attributes: Goal description XML control entity attributes Example Specify the equivalent of the REQUEST URI HTTP parameter for RIM push. X-Wap-Application-Id “/” Specify a unique message ID. Additionally, use this control entity attribute to cancel or check the status of a message. Use a URL in combination with a value.
BlackBerry Java Development Environment Development Guide See the Push Access Protocol (WAP-247-PAP-20010429-a) specification at http://www.wmlclub.com for more information about writing server-side push applications using PAP. See the PAP 2.0 DTD for information about the WAP Push DTDs.
C Appendix: .alx files Elements in BlackBerry application .alx files Elements in BlackBerry application .alx files Element Attributes Description application id The application element contains the elements for a single application. The application element can also contain additional nested application elements. Nesting lets you require that, when an application loads onto the BlackBerry® device, its prerequisite modules also load onto the BlackBerry device.
BlackBerry Java Development Environment Development Guide Element Attributes Description fileset Java radio langid Colour The fileset element includes an optional directory element and one or more files elements. It specifies a set of .cod files, in a single directory, to load onto the BlackBerry device. To load files from more than one directory, include one or more fileset elements in the .alx file. The Java attribute specifies the minimum version of the BlackBerry JVM with which the .
Appendix: .alx files Element Attributes Description requires id The requires element is an optional element that specifies the id of a package on which this application depends. This element can appear more than once, if the application depends on more than one application. When an application loads onto the BlackBerry device, all packages that the tag specifies also load onto the BlackBerry device. Note: The BlackBerry Desktop Software Version 3.6 and later supports this element.
BlackBerry Java Development Environment Development Guide 280
D Appendix: BlackBerry application .jad files Properties of BlackBerry application .jad files Properties of BlackBerry application .jad files Required RIM attribute Description RIM-COD-Creation-Time creation time of the .cod file RIM-COD-Module-Dependencies list of modules that the .cod file requires RIM-COD-Module-Name name of the module that the .cod file contains RIM-COD-SHA1 SHA1 hash of the .cod file RIM-COD-Size size (in bytes) of the .cod file RIM-COD-URL URL from which the .
BlackBerry Java Development Environment Development Guide 282
Acronym list A GPS Global Positioning System AES Advanced Encryption Standard API H HTTP application programming interface APN Hypertext Transfer Protocol HTTPS Access Point Name Hypertext Transfer Protocol over Secure Sockets Layer ATR Answer To Reset B I ID identification bpm beats per minute C L LMM Low Memory Manager CAC common access card CDMA Code Division Multiple Access D M MIDP Mobile Information Device Profile P DTD Document Type Definition DTMF Dual Tone Multiple Frequency PAP Push
BlackBerry Java Development Environment Development Guide POST power-on self-test U UDP User Datagram Protocol R RAM UI user interface random access memory URI S Uniform Resource Identifier S/MIME USB Secure Multipurpose Internet Mail Extensions T Universal Serial Bus UTC Coordinate Universal Time TCP Transmission Control Protocol TCP/IP W WAP Transmission Control Protocol/Internet Protocol Wireless Application Protocol Triple DES Triple Data Encryption Standard X XML Extensible Markup Langu
©2006 Research In Motion Limited Published in Canada.