BlackBerry Java Development Environment

Version 4.3.0 Development Guide

BlackBerry Java Development Environment Version 4.3.0 Development Guide Last modified: 19 September 2007 Part number: 12083107 At the time of publication, this documentation is based on the BlackBerry Java Development Environment Version 4.3.0. Send us your comments on product documentation: https://www.blackberry.com/DocsFeedback. ©2007 Research In Motion Limited. All Rights Reserved. The BlackBerry and RIM families of related marks, images, and symbols are the exclusive properties of Research In Motion Limited. RIM, Research In Motion, BlackBerry, “Always On, Always Connected” and the “envelope in motion” symbol are registered with the U.S. Patent and Trademark Office and may be pending or registered in other countries. Bluetooth is a trademark of Bluetooth SIG. Java and JavaScript are trademarks of Sun Microsystems, Inc. Microsoft, ActiveX, Internet Explorer, and Windows are trademarks of Microsoft Corporation. iCal is a trademark of Apple Computer, Inc. vCard is a trademark of the Internet Mail Consortium. Plazmic is a trademark of Plazmic Inc. Wi-Fi and 802.11, 802.11a, 802.11b, 802.11g are trademarks of the Wi-Fi Alliance. All other brands, product names, company names, trademarks and service marks are the properties of their respective owners. The BlackBerry device and/or associated software are protected by copyright, international treaties and various patents, including one or more of the following U.S. patents: 6,278,442; 6,271,605; 6,219,694; 6,075,470; 6,073,318; D445,428; D433,460; D416,256. Other patents are registered or pending in various countries around the world. Visit www.rim.com/patents.shtml for a list of RIM (as hereinafter defined) patents. This document is provided “as is” and Research In Motion Limited and its affiliated companies (“RIM”) assume no responsibility for any typographical, technical or other inaccuracies in this document. In order to protect RIM proprietary and confidential information and/or trade secrets, this document may describe some aspects of RIM technology in generalized terms. RIM reserves the right to periodically change information that is contained in this document; however, RIM makes no commitment to provide any such changes, updates, enhancements or other additions to this document to you in a timely manner or at all. RIM MAKES NO REPRESENTATIONS, WARRANTIES, CONDITIONS OR COVENANTS, EITHER EXPRESS OR IMPLIED (INCLUDING WITHOUT LIMITATION, ANY EXPRESS OR IMPLIED WARRANTIES OR CONDITIONS OF FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, MERCHANTABILITY, DURABILITY, TITLE, OR RELATED TO THE PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE REFERENCED HEREIN OR PERFORMANCE OF ANY SERVICES REFERENCED HEREIN). IN CONNECTION WITH YOUR USE OF THIS DOCUMENTATION, NEITHER RIM NOR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES OR CONSULTANTS SHALL BE LIABLE TO YOU FOR ANY DAMAGES WHATSOEVER BE THEY DIRECT, ECONOMIC, COMMERCIAL, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR INDIRECT DAMAGES, EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, INCLUDING WITHOUT LIMITATION, LOSS OF BUSINESS REVENUE OR EARNINGS, LOST DATA, DAMAGES CAUSED BY DELAYS, LOST PROFITS, OR A FAILURE TO REALIZE EXPECTED SAVINGS. This document might contain references to third party sources of information, hardware or software, products or services and/or third party web sites (collectively the “Third-Party Information”). RIM does not control, and is not responsible for, any Third-Party Information, including, without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other aspect of Third-Party Information. The inclusion of Third-Party Information in this document does not imply endorsement by RIM of the Third Party Information or the third party in any way. Installation and use of Third Party Information with RIM's products and services may require one or more patent, trademark or copyright licenses in order to avoid infringement of the intellectual property rights of others. Any dealings with Third Party Information, including, without limitation, compliance with applicable licenses and terms and conditions, are solely between you and the third party. You are solely responsible for determining whether such third party licenses are required and are responsible for acquiring any such licenses relating to Third Party Information. To the extent that such intellectual property licenses may be required, RIM expressly recommends that you do not install or use Third Party Information until all such applicable licenses have been acquired by you or on your behalf. Your use of Third Party Information shall be governed by and subject to you agreeing to the terms of the Third Party Information licenses. Any Third Party Information that is provided with RIM's products and services is provided "as is". RIM makes 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.

Research In Motion Limited 295 Phillip Street Waterloo, ON N2L 3W8 Canada Published in Canada

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

Contents
1 Creating user interfaces.....................................................................................................................................15 Elements of a BlackBerry device user interface ..........................................................................................15 Screens.......................................................................................................................................................15 UI components..........................................................................................................................................16 Create a screen ................................................................................................................................................ 17 Adding UI components to a screen............................................................................................................... 17 Create UI components............................................................................................................................. 17 Creating custom UI components..................................................................................................................20 Create a custom field ..............................................................................................................................20 Create custom context menus ............................................................................................................... 25 Create custom layout managers ...........................................................................................................26 Create custom lists.................................................................................................................................. 28 Adding menu items to BlackBerry Java Applications................................................................................29 Create a menu item.................................................................................................................................29 Register a menu item ..............................................................................................................................30 Arrange UI components.................................................................................................................................30 Define a layout manager ........................................................................................................................30 Set field focus and navigation ......................................................................................................................30 Listen for field focus changes ........................................................................................................................31 Respond to UI events ......................................................................................................................................31 Listen for field property changes.................................................................................................................. 33 Manage foreground events ........................................................................................................................... 34 Manage drawing areas................................................................................................................................... 34 Code samples................................................................................................................................................... 35 Code sample: Creating custom buttons............................................................................................... 35 Code sample: Creating a custom context menu ................................................................................. 38 Code sample: Creating a custom layout manager .............................................................................40 Code sample: Creating a custom list.....................................................................................................41 Code sample: Creating a new menu item in a BlackBerry Java Application .................................. 42 Using graphics and multimedia.......................................................................................................................45 Using images...................................................................................................................................................45 Use raw images........................................................................................................................................45

2

............................................64 Code sample: Implementing a custom connector ...........................................................................................................................................................................................84 4 ..........................................................................................................58 Create a custom connector for rich media connections................................. 83 Backing up and restoring data..............................................................................................................................48 Start the media player from the BlackBerry Browser ................... 47 Draw an image in color......................60 Code sample: Using a raw image to recreate an encoded image................................................................................................................................................................................................................................................ 47 Using audio................................................................................................................................................................59 Code samples....................................................................................................................................................................................................................................................................................................49 Create a media player... 69 Manage persistent data ..................................................................................................................................................................................................................................54 Using rich media..........................................................................................................................................................................................................................55 Listen for rich media events................................. 83 Types of data synchronization.......................................................... 77 Managing data....................................................... 69 Use BlackBerry persistent storage.............................................46 Drawing and rendering images ..................................................... 57 Code fragment: Managing rich media content download events........................................................... 69 BlackBerry persistent storage ...................48 Start the media player with no content ....................................................................................................................................................................................................................................................................................................................................................................................50 Play media ........................................................................................................................................................................................................................................................................................................................................................... 75 Code samples............................. 75 Code sample: Storing and viewing restaurant information ......................................................................................................................................................................................................................................................55 Playing rich media content ..83 Data synchronization ................................................................................................................Use encoded images............................................ 47 Position an image ....................................................... 73 Use the MIDP record store ................................................................63 Code sample: Implementing a listener to download rich media content .........................60 Code sample: Drawing a new bitmap using an existing bitmap .... 71 Manage custom objects ....................................................................................................... 66 3 Storing data .........................49 Start the media player with content............................................................................................................................................ 75 Code sample: Saving user name and password information.............................................................61 Code sample: Retrieving and displaying a rich media file.......................................................................... 53 Listen for media player events........................................................

............................................................89 Activate synchronization when the BlackBerry device starts.......................................................................................................................................................................................................... 109 Explicitly selecting a gateway ......................... 112 Use HTTPS connections .....................................................................................................................................................90 Code samples........................................ 87 Using SyncObjects...................................................91 Code sample: Using a SyncCollection to back up data over the wireless network............................................................................................................................................................................................................................................................................................................................................................91 Code sample: Letting the BlackBerry Desktop Software to back up and restore BlackBerry Java Application data ... 104 Use APDU to communicate with an object on a SIM card............................................................................................................................................................ 111 Use HTTP authentication ......................................................................................................... 110 Use HTTP connections......88 Add support for backing up data with the BlackBerry Desktop Software .................................................... 108 Creating connections......................................................................................................................... 110 Using the BlackBerry Enterprise Server as an intranet gateway .................................................................................................Add support for backing up data over the wireless network ................................................................................................ 108 Free persistent objects........................................ 107 Invoking garbage collection......................................... 106 Managing memory .................................. 115 Use socket connections............................... 103 Connecting to an application on a SIM card .............................................................. 96 5 Implementing security and trust services.........................107 LMM triggers ........................... 109 Determine the name of the wireless network that the BlackBerry device is registered with ............................................................................................................................................................................109 Fetching data using HTTP or TCP sockets ............................................................................................................................. 109 Verify that the BlackBerry device is in network coverage............................................................................................................................................................................ 115 6 7 ............................................................107 Use the LMM ...............................................................................................86 Notify the system when a SyncCollection changes ................................................... 103 PIN ID restrictions for JSR177 on a BlackBerry device.............................................................................................................................. 103 Use JCRMI to communicate with an object on a SIM card ................................................................ 110 Using the wireless service provider's Internet gateway................................84 Access a SyncCollection ...............................................................107 Reduce the number of objects ........................ 109 Working with network information .................................................................................................................................................................................................................................................................107 Managing low memory........................................................................................................................................................................................

...................................... 136 Register the event source when the BlackBerry device starts ...........132 Work with a Wi-Fi connection ..... 119 Code samples. 141 Code sample: Add a new event source.................................................................................................................................................. 131 Turn on a transceiver for a wireless access family ............................................132 Accessing a wireless network through a wireless access point . 139 Code samples................................. 120 Code sample: Using an HTTP connection to retrieve data ......................................................................................................... 131 Work with wireless access families ..................................................................................................................................................................................................................................................................................................................................................................................................................... 149 9 10 11 .......................................................... 135 Types of notification events ..........................................................................................................................................................................138 Cancel events .........................................133 Determine if the BlackBerry device is in a wireless coverage area ....................................................................................................147 Managing applications..................................................................................................................................................................................................................................................149 Application manager ............................... 120 Code sample: Listening for data on the serial port and rendering the data when it arrives .............Datagram connections........................132 Query the status of the Wi-Fi transceiver on a BlackBerry device............117 Use datagram connections ..................................................................... 136 Triggering events ..........135 Add a new event source ........ 118 Use USB or serial port connections........................................................................................ 119 Use Bluetooth serial port connections..........................................................................137 Respond to deferred events ................................................................................124 8 Working with Wi-Fi connections on a BlackBerry device..... 131 Identify the wireless access families that a BlackBerry device supports...............................................................................................117 Using port connections........................................................................................................................................................ 141 Code sample: Creating a custom notification................................................ 147 Invoke BlackBerry applications ........134 Open a Wi-Fi connection........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ 139 Customize system notifications for immediate events...........................................................................................................................................................................................132 Receive notifications of transceiver events.....................................................................................................................................134 Creating notifications.............................................................. 144 Integrating with BlackBerry applications .......................................................................................................................................................................................................................................................................................

............................................................................................................................................................................... 167 Use the calendar...........................172 Open the address book from your BlackBerry Java Application .........................................................................................................................................................................Retrieve information about BlackBerry Java Applications ............152 The runtime store...........................................157 Work with a message................................................. 150 Determine the services that are available to BlackBerry Java Applications.................. 151 Managing code modules................................ 157 Create new messages......................................... 159 Open a message ................................................................................................................................................................................................................................................................................................................................................................. 163 Work with folders ..................................................................................................................................................................................................................................................... 151 Allow a BlackBerry Java Application to request access to resources ......................................................................................................................................... 150 Communicate with other BlackBerry Java Applications .................. 165 Retrieve attachments...........................................................................................................................................................172 Using tasks...............................172 Use contacts........................................................................................................................................................................................................................ 149 Register BlackBerry Java Applications when the BlackBerry device starts ...........................................................................................152 Create code modules ............................................... 168 Using the address book .................................................................................................................................................................................................................................................................... 161 Reply to a message................................. 162 Forward a message....................................................................................................................................................................................................................................................................................................................................... 154 Code sample: Listening for changes to IT policies ...... 166 Using PIM applications .........................................................................................152 Retrieve an array of handles for existing modules on a BlackBerry device..................................................................................... 154 12 Using the messages application...................................................................................................................................................... 151 Application control ................178 13 .................................................................... 150 Listen for changes to IT policies .............................................153 Code sample ................................................................................................................................................................................................... 167 Start the calendar from your BlackBerry Java Application ............................................................................................................. 165 Create an attachment handler ............ 163 Working with attachments ...................................................................................................153 Share runtime objects ............. 165 Send a message with an attachment .................................................................................................................................................................................................... 151 Retrieve module information ........................................................................ 161 Send a message ............................................................................................................................................... 167 Using the calendar ......................................................

................................................... 189 Use phone call functionality ............................................................................................................ 191 Code sample ....................................................................... 190 Listen for phone events................................................................................................................................................................................. 198 Code sample: Using the BlackBerry Browser.........Start the task application from your BlackBerry Java Application ..............................................................................................................195 Display content in the BlackBerry Browser ................. 189 Add DTMF tones to the send queue ......................................................................... 191 Access and use call logs......................................... 192 Code sample: Calculating the time spent on the phone by a participant ....................................................................................................................................................... 186 14 Using the phone application .............. 211 Code sample: Listening for data from a web server ...................................... 209 Create a PAP push request.......................................................................................................................................................................................................................................................................................................................... 195 Code sample ...............................................................................................................208 Create a RIM push request.............................................................................204 Write a client push BlackBerry Java Application............205 Write a server-side push application ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ 195 Display content in a BlackBerry Browser field ..................................................................................................................................................................................182 Code sample: Creating new recurring appointments....................................................................................................................................................................................... 198 Creating push BlackBerry Java Applications.................... 184 Code sample: Using tasks .............182 Code sample: Displaying a screen that lets BlackBerry device users add new contacts ................................................................................. 192 Using the BlackBerry Browser ................... 179 Code samples.................................................................................................................................................................................................................................................................................................. 210 Code samples...................... 203 Types of push BlackBerry Java Applications............... 223 15 16 17 ........................189 Start the phone application from your BlackBerry Java Application ......................................................................................................................... 211 Code sample: Pushing data to a BlackBerry Java Application that listens on a BlackBerry device 214 Localizing BlackBerry Java Applications.......................................................................................................................178 Use tasks...............................................................203 Types of push requests......................................................................................................... 206 Work with a server-side push request .....................223 Storing text strings in resource files ...............................

......................................239 View local variables............................................... 233 Testing BlackBerry Java Applications using BlackBerry devices.............................................................. 223 Files required for localization...................................... 243 Analyze code coverage .........................................................................................233 Testing BlackBerry Java Applications using the BlackBerry IDE.......................................................................................................................................................................................................................................... 233 Use the BlackBerry Device Simulator to test synchronizing data with the BlackBerry Desktop Software ...............................................................................................................243 Optimize source code using the BlackBerry Integrated Development Environment profiler tool ........................................................................................................................................................................................................................................................................................................................................................................228 Code sample: Retrieving strings from a resource file ............................................................................................................Storing resources for a locale ...........................................................................234 Debugging BlackBerry Java Applications ........................................................................................................................................................................241 View threads...................................................................................230 18 Testing BlackBerry Java Applications................238 Display objects in memory to locate object leaks ...............................................240 View variable or expression information.......................................................................................242 View the call stack........240 View static data ..............................................224 Add localization support ........242 View event logs ....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................245 ..........................................................................234 Debug a BlackBerry Java Application in the BlackBerry IDE.....236 Run a BlackBerry Java Application to the insertion point.............................................................................................226 Manage resource files for BlackBerry Java Application suites ........................................................................................................242 View classes........................................238 View statistics to locate memory leaks ...................................................................................................................236 Debug a BlackBerry Java Application on a BlackBerry device .................................................................................................................................... 227 Code samples..........................................234 Connect the BlackBerry IDE to a BlackBerry device .....................................236 Locate an error in the source code...240 Evaluate (watch) Java expressions.......235 Manage a debugging session ............228 Code sample: Storing text strings in separate resources for locales.........................................................................................................................................236 Step through lines of code in a BlackBerry Java Application ...241 View the data members of a process...........................................................................................................................................234 Use breakpoints...............................................................................224 Retrieve strings from a resource file ......................................................................................................

.........................................251 Controlled APIs ............................................................................................................................................................................................................... 249 19 Packaging and distributing BlackBerry Java Applications ........251 Determine if your code requires signatures ..............................................................................253 Request code signatures using a proxy server..........................................................................................................................................................................................alx files............. 260 Specify supported BlackBerry Device Software...............................255 Perform advanced BlackBerry Java Application distribution tasks ........................................................................................................................................................................267 Appendix: BlackBerry Java Application .............................. 259 Create an application loader file.........................................................................................................................................248 View BlackBerry Java Application information ...................................................................................................................................................................267 Elements in BlackBerry application ................... 261 Appendix: The command line compiler .................................alx files ...............................257 Distributing BlackBerry Java Applications with the BlackBerry Desktop Software ..........................................253 Request code signatures.........................................................247 Working with compiled BlackBerry Java Applications .........................................254 View signature status......................................................................................Start the BlackBerry email simulator....251 Register to use RIM controlled APIs ......................... 263 Using the command line compiler ................255 Distribute applications using wireless pull................................................................271 Accessing application attribute properties from a .......................................................................................................... 256 Modify information in a .................................................................................................271 Properties of BlackBerry Java Application ....252 Restricted access to code signatures ....................................... 259 Specify optional components ..........................................................................................jad files ...................................................................................................................................................................................................................................................................................................jad files.....................................................................254 Request a replacement registration key ..................................................................................................... 265 Appendix: .............................................................................. 272 A B C D ........................................................................................................................ 251 Preverify BlackBerry Java Applications ............... 265 Using XML control entity attributes ......................................................................................................................................................................................263 Appendix: XML control entity attributes................................................................................248 Load and remove BlackBerry Java Applications ...........jad file ..................................... 259 Load a BlackBerry Java Application on a specific BlackBerry device ..................................................................jad file ..........254 Distributing BlackBerry Java Applications over the wireless network ...............................

......................................................... 273 Set the connection time ........Let a BlackBerry device application retrieve name-value pair information from a ........................ 277 ........................276 Acronym list................................273 Use the Eclipse development environment .........................................................................jad file ............................................................................ 273 Connect to the Eclipse development environment .................................................... 272 E Appendix: The Eclipse development environment............................................. 273 Start the JDWP .....................................275 Debug an application using the Eclipse development environment............................................................................................................................................................................................................................................................................................

.

. Do not use Screen objects for typing text. commit a data object to memory or close the BlackBerry Java Application. The user interface APIs initialize simple Screen objects. you can customize the BlackBerry device user interface and implement new field types. For more sophisticated custom BlackBerry Java Applications. The menu object has associated menu items that are runnable objects. For seamless integration of the different input methods. such as international keyboards and the BlackBerry 7100 Series. but only one screen in a BlackBerry Java Application is active at one time. See the BlackBerry Developer Zone at http://www. you can add fields and a menu to the screen and display it to the BlackBerry device user by pushing it on to the UI stack. Once you create a screen. You can also add custom navigation and trackwheel behavior. extend Field or one of its subclasses.blackberry. which perform a specific task when the BlackBerry device user selects one of the items. A BlackBerry® Java® Application may display more than one screen at a time. which is required for complex input methods. The Screen class does not implement disambiguation.1 Creating user interfaces Elements of a BlackBerry device user interface Create a screen Adding UI components to a screen Creating custom UI components Adding menu items to BlackBerry Java 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 Code samples Elements of a BlackBerry device user interface Screens The main structure for a BlackBerry® device user interface is the Screen object. menu items may invoke the necessary code to establish a network connection. as required. For example.com/developers for knowledge base articles about displaying and working with screens.

which are rectangular regions that a Manager contains. Each screen can appear only once in the display stack. create your own custom types by extending the Field class or one of its subclasses. Use a FullScreen class to provide an empty screen that you can add UI components to in a standard vertical layout. it removes the screen off the top of the stack and displays the next screen on the stack. By default. The screen at the top of the stack is the active screen that the BlackBerry device user sees. BasicEditField. use a Screen class and add a Manager to it. because each screen uses a separate thread. a FullScreen class contains a single vertical field manager. The BlackBerry JVM throws a runtime exception if a Screen that the BlackBerry Java Application pushes to the stack already exists. redrawing it as necessary. For another layout style. To create a specialized field component (such as a text field that contains multiple elements). which is an ordered set of Screen objects. When a BlackBerry Java Application closes a screen. When a BlackBerry Java® Application displays a screen. BlackBerry Java Applications must remove screens from the display stack when the BlackBerry device user finishes interacting with them so that the BlackBerry Java Application uses memory efficiently. with a SeparatorField after the title main scrollable section contained in a VerticalFieldManager default menu with a Close menu item default close action when the BlackBerry device user clicks the Close menu item or presses the Escape key MainScreen How the BlackBerry JVM manages screens The BlackBerry® JVM maintains Screen objects in a display stack. A field’s layout requirements determine the size of the field. LabelField 16 . EditField. Managers provide scrolling for the fields that they contain. The MainScreen class provides the following UI components: • • • • default position of a screen title. such as horizontal or diagonal.BlackBerry Java Development Environment Development Guide Types of screens Screen Type Default Standard vertical BlackBerry style Class Screen FullScreen Description 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. UI components Fields represent all UI components. or AutoTextEditField. Use a MainScreen object for the first screen of your BlackBerry Java Application to maintain consistency with other BlackBerry Java Applications. Use only a few modal screens at one time. it pushes the screen to the top of the stack.PasswordEditField. Traditional field Button Check box Date Dialog box Drop-down list Radio button Text Text label BlackBerry® Field ButtonField CheckboxField DateField PopupScreen NumericChoiceField or ObjectChoiceField RadioButtonField RichTextField. The MainScreen class provides features that are common to standard BlackBerry® Java® Applications.

> Create an instance of a CheckboxField. Manager manageLayout = new HorizontalFieldManager( VERTICAL_SCROLLBAR). create an instance of a NumericChoiceField. 2. Create a check box. choiceItems)). > Create an instance of a GaugeField. Adding UI components to a screen 1. Create a numeric drop-down list for a large range of numbers. PopupScreen popUp = new PopupScreen(manageLayout). mainScreen. Add the UI component to your extension of a screen class. To create a drop-down list that contains objects. To create a drop-down list that contains numbers. create an instance of an ObjectChoiceField. Add a bitmap. Create a numeric drop-down list > > > Create an instance of a BitmapField. BitmapField myBitmapField = new BitmapField(). Create UI components To create an instance of a component. CheckboxField myCheckbox = new CheckboxField("First checkbox".add(new ObjectChoiceField("Select an option:". See the API Reference for more information on Field classes. Create an instance of a ButtonField using a style parameter.1: Creating user interfaces Traditional field List BlackBerry® Field ListField Create a screen > Extend the Screen class or one of its subclasses. NumericChoiceField myNumericChoice = new NumericChoiceField( "Select a number: ". "Option three"}. > String choiceItems[] = {"Option one". 1. Steps 1. ButtonField mySubmitButton = new ButtonField("Submit"). Create a button. 10). Task Create a pop-up screen.providing an object array as a parameter. true). you can use more than one constructor. "Option two". mainScreen. Create an instance of a PopupScreen using the Manager object. true). CheckboxField myCheckbox = new CheckboxField("First checkbox".add(myCheckbox). FullScreen or MainScreen. 2. 20. Create an instance of a UI component. Create an alphanumeric drop-down list. Create an instance of a subclass of the Manager class. 17 .

Steps 1. GaugeField percentGauge = new GaugeField("Percent: ". DateField. 18 . > Create an instance of an EditField. "".PERCENT) > Create an instance of a LableField to add a text label to a screen. ""). 29.currentTimeMillis() as a parameter to return the current time. RadioButtonGroup rbGroup = new RadioButtonGroup().add(rbField2). Create an instance of a RadioButtonGroup.add(rbField). EditField. BasicEditField bf = new BasicEditField("BasicEditField: ". 1. > Create an instance of a GaugeField.FILTER_UPPERCASE). Create an instance of a BasicEditField. RadioButtonField rbField = new RadioButtonField("First field").FILTER_DEFAULT). ""). RadioButtonField rbField2 = new RadioButtonField("Second field"). "". AutoTextEditField autoT = new AutoTextEditField("AutoTextEditField: ". > > Create an instance of a RichTextField . rbGroup. LabelField title = new LabelField("UI Component Sample". 3. LabelField. providing the value returned by System. 2.ELLIPSIS)). Create a text label. Create a read-only field that you can format using different fonts and styles. 100.DATE_TIME). > Create an instance of a PasswordEditField. GaugeField. Create an AutoText edit field. EditField edit = new EditField("EditField: ". > Create an instance of an AutoTextEditField. EditField.add() to add the RadioButtonFields to the RadioButonGroup and make sure the BlackBerry device user can select only one option at a time. Create an instance of a RadioButtonField for each option you want to make available to the BlackBerry® device user. Invoke RadioButtonGroup. > Create an instance of a DateField. For example. System. rbGroup. Create a date field. Create an editable text field that contains no default formatting but accepts filters. Some filters render some AutoText entries ineffective.BlackBerry Java Development Environment Development Guide Task Create a radio button. Create an editable text field that lets BlackBerry® device users to access special characters. 10. PasswordEditField pwd = new PasswordEditField("PasswordEditField: ". FILTER_LOWERCASE renders an AutoText entry that contains capitalization ineffective.currentTimeMillis(). Create a field that displays a progress bar for the numbers that the BlackBerry® device user selects. the following instance uses a constructor that lets you provide a default initial value for the PasswordEditField. 10. RichTextField rich = new RichTextField("RichTextField"). DateField dateField = new DateField("Date: ". Create a password field. For example.

String fieldOne = new String("Mark Guo").addChildNode(0. String fieldTwo = new String("Amy Krul"). implement the TreeFieldCallback interface. 3. Specify whether a folder is collapsible by invoking TreeField. A TreeField contains parent and child nodes. int node1 = myTree. ListField myList = new ListField(). Create an instance of a ListField.addChildNode(node2. ListCallback myCallback = new ListCallback(). int y.drawText(text. Create the items that you want to display in a ListField. 6.addChildNode(node1.. mainScreen. int node2 = myTree. fieldOne). int width.. g. TreeField myTree = new TreeField(myCallback. y). myTree. Add the ListField to the MainScreen. 4. int node10 = myTree.. int node. 2. . Field. myList.add(myTree). 2. 5. To draw a TreeField. . Set the call back of the ListField to be the ListCallback.getCookie(node). int node4 = myTree. int node3 = myTree. fieldTwo).setExpanded() on the TreeField object.1: Creating user interfaces Task Create a field that lets a BlackBerry® device user select a range of items in the list. Create a field that displays a folder or tree relationship between items (such as documents or message folders).. fieldTwo). String fieldOne = new String("Main folder"). } } 19 . Steps 1.setCallback(myCallback). int indent) { String text = (String)_tree. Graphics g.add(myList.add(myList. Your implementation of TreeFieldCallback should add fields to the tree.setExpanded(node4.addChildNode(node3. false). fieldOne). fieldThree).. fieldFour). Use the ListCallBack object to add items to the ListField. 1. Create an instance of a ListCallback.FOCUSABLE). TreeCallback myCallback = new TreeCallback().add(myList). mainScreen. myCallback. . fieldTen). See "Create a callback object" on page 33 for more information on callbacks. private class TreeCallback implements TreeFieldCallback { public void drawTreeItem(TreeField _tree. indent.addChildNode(0. myCallback..

public static final int TRIANGLE = 2. this(label. Steps You can only add custom context menu items and custom layouts to a custom field. Create a custom field Task Create a custom field. > Implement constructors to define the label. > Extend the Field class. content menus. _font = getFont(). shape. int shape) { this(label. and style of the custom button. public static final int OCTAGON = 3. _shape = shape. private int _labelWidth. 0). shape.getHeight(). _labelHeight = _font. RECTANGLE. shape. or one of its subclasses. _label = label. and style of the custom public CustomButtonField(String label) { button. implementing the DrawStyle interface to specify the characteristics of the custom field and turn on drawing styles. use the BlackBerry® APIs. private int _shape. public class CustomButtonField extends Field implements DrawStyle { public static final int RECTANGLE = 1.BlackBerry Java Development Environment Development Guide Creating custom UI components To create custom fields. 0). style). long style) { this(label. RECTANGLE. layout managers. } public CustomButtonField(String label. _labelWidth = _font. } public CustomButtonField(String label. private Font _font. int shape. private String _label. } 20 . } public CustomButtonField(String label. long style) { super(style). } Define the label. and lists. private int _labelHeight.getAdvance(_label).

setExtent( width.getHeight().min() to return the smaller of the specified width and height and the preferred width and height of the field. invoke Math. } case RECTANGLE: default: return _labelWidth + 8. int height) { _font = getFont().getAdvance(_label). } } 21 . invoke Field. height ).1: Creating user interfaces Task Specify the arrangement of the objects in the field. getPreferredWidth() ). public int getPreferredWidth() { switch(_shape) { case TRIANGLE: if (_labelWidth < _labelHeight) { return _labelHeight << 2. • To set the required dimensions for the field. using the relative dimensions to make sure that the label does not exceed the dimensions of the component.min( width. and locale strings. _labelHeight = _font. } case OCTAGON: if (_labelWidth < _labelHeight) { return _labelHeight + 4. width = Math. getPreferredHeight() ). perform the following actions: • To calculate the available width and height. Within your implementation. > Implement getPreferredWidth(). cached fonts. Define the preferred width of a custom component. Steps 1.setExtent(int. } else { return _labelWidth << 1. Implement layout().min( height. protected void layout(int width. _labelWidth = _font. } The manager of the field invokes layout() to determine how the field arranges its contents in the available space. } else { return _labelWidth + 8. height = Math. 2. • Recalculate the pixel layout. Arrange field data so that you perform the most complex calculations in layout() instead of in paint().int).

Steps > Implement getPreferredHeight(). using the relative dimensions of the field label to determine the preferred height. } case RECTANGLE: return _labelHeight + 4.BlackBerry Java Development Environment Development Guide Task Define the preferred height of a custom component. } return 0. case OCTAGON: return getPreferredWidth(). } else { return _labelWidth. public int getPreferredHeight() { switch(_shape) { case TRIANGLE: if (_labelWidth < _labelHeight) { return _labelHeight << 1. } 22 .

x. h-1). } The fields manager invokes paint() to redraw the field whenever an area of the field is marked as invalid. w . textX. graphics. graphics.ELLIPSIS | DrawStyle.drawLine(0. > Change the appearance > of the default focus indicator. x. Steps 1. w-1. getHeight()). case OCTAGON: int x = 5*w/17. 0). x2. graphics. graphics. 0). protected void paint(Graphics graphics) { int textX. x3). h-1. case RECTANGLE: default: graphics. x3. int m = (w>>1)-1. x3. h-1. textWidth = w .HALIGN_MASK ).6). Perform complex calculations in layout()instead of in paint(). m. x3.drawLine(0. 0. x). x3. textWidth ). graphics. } graphics.FOCUSABLE style and implement Field. x2. Paint a field only within > the visible region. textY = (w-_labelHeight) >> 1. x2). (int)( getStyle() & DrawStyle. h-1).getClippingRect(). x3. Implement paint(). break.drawLine(x. textY = 2. 0.drawLine(0. x2).h). textY = h >> 1. switch(_shape) { case TRIANGLE: int h = (w>>1). Override Field. w. 0).drawLine(x2.min(_labelWidth. textWidth = Math.drawLine(0.min(_labelWidth. graphics. Manage focus events.drawLine(x3. textWidth. x. 0.1: Creating user interfaces Task Define the appearance of the custom field. break. graphics. x3). Use the Field. x. graphics. int x3 = w-1. textX = 4.textWidth) >> 1. x2). 0.drawText(_label. 2. textX = (w . Invoke Graphics.drawLine(x. w-1. x. graphics. graphics.drawRect(0. break. graphics. 0.drawLine(0. 23 . x2.drawLine(m. int w = getWidth(). textWidth = Math.6.moveFocus().drawLine(x2. int x2 = w-x-1. textY.drawFocus(). textX = (w-textWidth) >> 1. textY.

} See “Code sample: Creating custom buttons” on page 35 for more information. _labelWidth = _font. 24 . public String getLabel() { return _label. } public void setShape(int shape) { _shape = shape.getAdvance(_label). Steps > Implement the Field set() and get() methods. } public void setLabel(String label) { _label = label. updateLayout().BlackBerry Java Development Environment Development Guide Task Add component capabilities. } public int getShape() { return _shape. updateLayout().

Steps > In your field class. } Create the BlackBerry® MDS Java Application menu.getActiveScreen().makeMenu(). create the custom context menu items. 200000. 200000.getUiApplication(). 25 . if (!contextMenu. protected void makeContextMenu(ContextMenu contextMenu) { contextMenu. } } } See “Code sample: Creating a custom context menu” on page 38 for more information. > In your main BlackBerry® MDS Java Application class. } }.1: Creating user interfaces Create custom context menus Task Create the custom context menu items. MENUITEM_ONE.getContextMenu() on the return value to determine which fields receive custom menu items. 10) { public void run() { onMyMenuItemA(). } }. 10) { public void run() { onMyMenuItemB(). protected void makeMenu(Menu menu) { Field focus = UiApplication.addSeparator(). contextMenu. > In your main BlackBerry Java Application class.add(contextMenu). MENUITEM_ONE.addItem(myContextMenuItemB). if (focus != null) { ContextMenu contextMenu = focus. Provide a context menu. private MenuItem myContextMenuItemB = new MenuItem( _resources. override makeContextMenu(). menu.getLeafFieldWithFocus( ).getLeafFieldWithFocus() and Field.isEmpty()) { menu. private MenuItem myContextMenuItemA = new MenuItem( _resources. override Screen.getContextMenu(). invoking Screen.addItem(myContextMenuItemA).

Return a preferred field height. Override layout().getPreferredWidth(). public int getPreferredHeight() { int height = 0. public int getPreferredWidth() { int width = 0. class DiagonalManager extends Manager { public DiagonalManager(long style){ super(style). } 26 . Override getPreferredHeight() so that it returns the preferred field height for the manager. i<numberOfFields. Steps > Extend the Manager class or one of its subclasses.getPreferredHeight().. Organize more than one TextField or Manager object.BlackBerry Java Development Environment Development Guide Create custom layout managers Task Create a custom layout manager. ++i) { height += getField(i). } > > > Override the respective getPreferredWidth() methods for the TextField or Manager objects. } Return a preferred field width. } return height. int numberOfFields = getFieldCount(). for (int i=0. int numberOfFields = getFieldCount(). for (int i=0. > Override getPreferredWidth() so that it returns the preferred field width for the manager.. Organize multiple TextFields horizontally. i<numberOfFields. } . } return width. ++i) { width += getField(i).

Field field. By default. x += field. y += field. boolean alt) { int index = this. int numberOfFields = getFieldCount(). Control how each child field is added to the screen by calling setPositionChild() and layoutChild() for each field that the manager contains. int y = 0. Override nextFocus(). } else { return index. Steps 1. the custom manager invokes paint() to repaint all of the fields without regard to the clipping region. if(alt) { if(direction < 0) { // action to perform if trackwheel is rolled up } else { // action to perform if trackwheel is rolled down } } if (index == this. invoke setExtent(). x. > Implement subpaint().getPreferredWidth().nextFocus(direction.1: Creating user interfaces Task Specify the arrangement of the child fields. 2. setPositionChild(field. > > In sublayout().y).getFieldWithFocusIndex()) { return super. 27 . Specify how the fields receive focus. Override sublayout() to retrieve the total number of fields in the manager.setPosition(x. } Set the size of the child fields. alt). width. y).getPreferredHeight().height). protected int nextFocus(int direction. } } Repaint the fields when the visible region changes. for (int i=0. ++i) { field = getField(i). field. protected void sublayout(int width. i<numberOfFields.getFieldWithFocusIndex(). layoutChild(field. height). } setExtent(width. See “Code sample: Creating a custom layout manager” on page 40 for more information. int height) { int x = 0.

insert(fieldThree. myCallback.insert(fieldTwo. int index.getScreenWidth(). Create the ListField and ListCallback objects for the list.setCallback(myCallback). w). Create a callback object. int index) { return listElements. } Let the field repaint a row. String fieldThree = new String("Field three label"). 28 . } Return a preferred width for the list. > Implement ListFieldCallback.insert(fieldOne. 3. See “Code sample: Creating a custom list” on page 41 for more information.add(myList).drawText() using parameters that specify the row to paint. String fieldTwo = new String("Field two label").get(). private Vector listElements = new Vector(). and then insert each ListField object into the ListFieldCallback.insert(1). . This association lets the callback add items to the list. 0. return a preferred width for the list. ListCallback myCallback = new ListCallback(). public int getPreferredWidth(ListField list) { return Graphics. myList. mainScreen. myList.drawListRow(). myCallback. public Object get(ListField list.elementAt(index). String fieldOne = new String("Field one label"). 0. g. 0). Invoke ListField. 2.drawText(text. int w) { String text = (String)listElements. y. 1). Graphics g. ListField myList = new ListField(). } Let the field retrieve an entry from the list. 2). public void drawListRow(ListField list.BlackBerry Java Development Environment Development Guide Create custom lists Task Let users select multiple items in a list. int y.elementAt(index). Implement the ListFieldCallback interface. myList. private class ListCallback implements ListFieldCallback { // The listElements vector contain the entries in the list. myList.insert(2). invoking Graphics.. specify an index at which to insert each entry on the ListField object.setCallback() to associate the ListFieldCallback with the ListField. > Implement ListFieldCallback. list.. > In the implementation of getPreferredWidth(). Steps > > Declare lists as MULTI_SELECT. } Assign the callback and add entries to the 1. myCallback.insert(0). To add entries to the list. create the entries.

if ( c ! null ) { new ContactsDemo().rim. public String toString() { return "Open the Contacts Demo application". Create a menu item Task Define a menu item. } A higher number means that the menu item appears lower in the menu. Steps > Extend the abstract ApplicationMenuItem class. > Invoke ApplicationMenuItem() SampleMenuItem() { super(20). } 29 .. > Implement run(). } Specify the behaviour of the menu item.enterEventDispatcher(). public class SampleMenuItem extends ApplicationMenuItem { . expected a Contact instance"). return null.blackberry. } Specify the menu item text.api. Specify the position of the menu item in the menu. // An error occurs if this does not work. } Dialog. > Implement toString(). public Object run(Object context) { Contact c = (Contact)context. in the net.. } else { throw new IllegalStateException( "Context is null.alert("Viewing a message in the messaging view").menuitem package.1: Creating user interfaces Adding menu items to BlackBerry Java Applications The Application Menu Item API. lets you add menu items to BlackBerry® Java® Applications. The ApplicationMenuItemRepository class lets you add or remove menu items from BlackBerry Java Applications.

Steps On an instance of a Screen. mainScreen.add(bitmapField). VerticalFieldManager vfm = new VerticalFieldManager(Manager. vfm. TestApplicationMenuItem tami = new TestApplicationMenuItem(). 30 .VERTICAL_SCROLL).addMenuItem(). ApplicationMenuItemRepository repository = ApplicationMenuItemRepository..add(bitmapField2).getInstance(). Arrange UI components To arrange components on a screen. Create your BlackBerry Java Application menu item.. tami).BlackBerry Java Development Environment Development Guide Register a menu item Task Retrieve the BlackBerry® MDS Java Application menu item repository. Define a layout manager Task Create a layout manager. repository. use BlackBerry® API layout managers .addMenuItem(ApplicationMenuItemRepository. 3. Steps > Invoke ApplicationMenuItemRepository. Invoke ApplicationMenuItemRepository. Add the layout manager to the screen. The following four classes extend the Manager class to provide predefined layout managers: • • • • VerticalFieldManager HorizontalFieldManager FlowFieldManager DialogFieldManager To create a custom layout manager.addMenuItem(ApplicationMenuItemRepository. > Invoke the constructor.addMenuItem()using the MENUITEM_MAPS field. > Invoke ApplicationMenuItemRepository. Add UI components to the layout manager. Add the menu item to the repository. complete the following actions: 1. tami). repository. extend Manager.add(vfm) Set field focus and navigation UIEventListeners let BlackBerry® Java® Applications respond to a change to a UI object. See “Code sample: Creating a new menu item in a BlackBerry Java Application” on page 42 for more information. . Instantiate the appropriate Manager subclass. > Add the menu item to BlackBerry® Maps. vfm.MENUITEM_MAPS.MENUITEM_ADDRESSCARD _VIEW. 2.getInstance().

int dy. private class FocusListener implements FocusChangeListener { public void focusChanged(Field field. int eventType) { if (eventType == FOCUS_GAINED) { // Perform action when this field gains the focus. Assign your implementation to a Field by invoking setChangeListener().} } } FocusListener myFocusChangeListener = new FocusListener().STATUS_TRACKWHEEL) { //Input came from the trackwheel } else if ((status & KeypadListener. Your implementation of FocusChangeListener should specify what action occurs when the field gains. 31 .navigationClick(status.Screen class (or one of its subclasses) and overriding the following navigation methods: navigationClick(int status.STATUS_TRACKWHEEL) == KeypadListener. For example.rim. use the new Screen navigation methods and avoid using the TrackwheelListener.1: Creating user interfaces Listen for field focus changes 1. } See the API Reference for the class net. int time) When you create a new UI BlackBerry® Java® Application. or navigationMovement methods of the Screen or Field classes.STATUS_FOUR_WAY) { //Input came from a four way navigation input device } return super. In your implementation of one of the navigationClick. perform a bitwise AND operation on the status parameter to yield more information about the event. > If your existing UI BlackBerry Java Application implements the TrackwheelListener.api. navigationUnclick.device. to determine the type of input mechanism that triggered an event. 2.STATUS_FOUR_WAY) == KeypadListener.system.} if (eventType == FOCUS_LOST) { // Perform action when this field loses focus.api. loses. int time) navigationMovement(int dx. or changes the focus by implementing focusChanged().rim.ui. Steps > Manage navigation events by extending the net. time). in your implementation of the navigationClick(int status. Implement FocusChangeListener. update your BlackBerry Java Application to use the new Screen navigation methods. • • • • • Interpret the status parameter of the navigation methods. int time) { if ((status & KeypadListener. int time) navigationUnclick(int status. int time) method. create code such as the following: public boolean navigationClick(int status. Respond to UI events Task Respond to UI navigation events. myField.device.} if (eventType == FOCUS_CHANGED) { // Perform action when the focus changes for this field. int status.setFocusListener(myFocusChangeListener).KeypadListener for a listing of other status modifiers.

Make sure your extension of the makeMenu() method of the Screen class invokes Screen. Provice menu support. uses the TrackwheelClick() method of the 3. Update your BlackBerry Java Application to use an extension of the Screen class. make sure to invoke the Screen class constructor using the DEFAULT_MENU property. Provide menu support in a 1. using a FullScreen or Screen. TrackwheelListener. > Extend the Screen class. In the constructor of your Screen class extension. > Specify the DEFAULT_MENU and DEFAULT_CLOSE parameters in the constructor to provide default navigation. 32 . Steps > Use the Screen class and its subclasses to provide a menu for the BlackBerry device users to perform actions. Provide screen navigation when Creating a MainScreen object provides default navigation to your BlackBerry® Java® Application.makeMenu() and adds the required menu items for the current UI BlackBerry Java Application.BlackBerry Java Development Environment Development Guide Task Respond to BlackBerry® device user interaction. BlackBerry® Java® Application that 2. Avoid using buttons or other UI elements that take up space on the screen. FullScreen fullScreen = new FullScreen(DEFAULT_MENU | DEFAULT_CLOSE).

In your extension of makeMenu() cache a reference to the “menu” parameter in the screen. define a Close menu item explicitly. 3.add(viewItem). inspect the cached Menu object to determine which menu item the BlackBerry® device user selected. Steps Perform the actions in one of the following options: Option 1 1.} 6.} 3. int context) { if (context != FieldChangeListener. Listen for field property changes 1. private MenuItem closeItem = new MenuItem("Close". 2. 4.. 200000. override toString() to specify the name of the menu item. When you add your own menu items. this action invokes the run() method. public void run() { Dialog. In your extension of OnMenu(). menu. } else { // Perform action if application changed field. protected void makeMenu(Menu menu. Implement the FieldChangeListener interface. } 5. Option 2 1. In your extension of the MenuItem class.OnMenu(). Extend the MenuItem class. 10) { public void run() { onClose(). adding instances of the extended MenuItem class. To add the menu items to the screen. int instance) { menu. Assign your implementation to a field by invoking setChangeListener(). } } } // . If you do not use localization resources. 4. private MenuItem viewItem = new MenuItem("View Message". do not override the onMenu()method. Override the onMenu()method.PROGRAMMATIC) { // Perform action if user changed field. private class FieldListener implements FieldChangeListener { public void fieldChanged(Field field.makeMenu()..inform("This is today’s message").1: Creating user interfaces Task Manage selected menu items. 2. 2. override Screen. Create a run() method that implements the behavior that you expect to occur when the BlackBerry device user clicks a menu item. invoke Screen. 100. In your code. Use the result of this inspection to trigger the appropriate menu action. 33 . When a BlackBerry device user selects a MenuItem.add(closeItem). 5. 10).

drawRect(15.activate() when it brings a BlackBerry® Java® Application to the foreground. 2.fillRect(10. Invert a specified XYRect object. 30). When you invoke drawing methods by first calling pushRegion(). which is composed of an X co-ordinate and a Y co-ordinate. 0. the bottom portion of the XYRect object extends past the bounds of the graphics context and clips it. 30). 15. graphics. The XYRect is translated from its origin of (1.popContext(). XYRect rectangle = new XYRect(1. graphics. Specify the portion of the Graphics object to push onto the stack. 30).pushRegion(rectangle). Invert an area. > Invoke translate(). 15. 1) to an origin of (20. 1. rectangle.popContext(). 0). XYRect rectangle = new XYRect(topLeft. graphics. 30. Each XYPoint represents a point on the screen.drawRect(15.translate(newLocation). When you make drawing calls with pushContext().pushContext(rectangle. XYPoint bottomRight = new XYPoint(50. graphics. 20). 20). 10). divide it into XYRect objects. graphics.fillRect(10. Create an instance of an XYPoint object and an XYRect object. After you invoke pushContext() (or pushRegion()). Translate an area. graphics. Manage foreground events The system calls Application. 1. graphics. specify that the region origin should not adjust the drawing offset. Invoke pushContext() or pushRegion(). To limit this area. graphics. 30. graphics. 34 . After translation.invert(rectangle). bottomRight). XYPoint newLocation = new XYPoint(20. Task Create rectangular clipping areas. 30). Steps 1.pushContext(rectangle). XYPoint topLeft = new XYPoint(10. 50). 30. 3. 10. // invert the entire XYRect object graphics.popContext(). 30. 100.BlackBerry Java Development Environment Development Guide FieldListener myFieldChangeListener = new FieldListener() myField. 10. 3. Manage drawing areas The Graphics object represents the entire drawing surface that is available to the BlackBerry® Java® Application. 2. graphics. specify that the region origin should adjust the drawing offset. 100). 4.setChangeListener(myFieldChangeListener). provide the portion of the Graphics object to invert.

int _shape. */ public CustomButtonField(String label.samples. } /* Constructs a button with specified label and style. _label = label. and the default style and shape. import net. long style) { super(style). and the default style. int shape. RECTANGLE.system. _labelHeight = _font. Font _font. long style) { this(label. } /* Constructs a button with specified label and shape. int _labelHeight.*. */ package com. 0). This sample demonstrates how to create custom UI fields. shape. All rights reserved. public static final int OCTAGON = 3. import net. _font = getFont(). } 35 . 0). _labelWidth = _font. /* Constructs a button with specified label. int shape) { this(label.getHeight(). private private private private private String _label.rim. and style */ public CustomButtonField(String label. public static final int TRIANGLE = 2.1: Creating user interfaces Code samples Code sample: Creating custom buttons Example: CustomButtonField.custombuttons.api.getAdvance(_label).ui.*.java * Copyright (C) 2001-2005 Research In Motion Limited. /** * CustomButtonField is a class that creates button fields of various * shapes. and the default shape.device. style). */ public CustomButtonField(String label. */ public class CustomButtonField extends Field implements DrawStyle { public static final int RECTANGLE = 1. int _labelWidth. shape. */ public CustomButtonField(String label) { this(label. _shape = shape.java /** * CustomButtonField.docs. RECTANGLE.device.api.rim. } /* Constructs a button with specified label.rim.

i.getAdvance(_label). case OCTAGON: int x3 = getWidth().(i << 1). int x = 5 * x3 / 17. x. } /* Sets the label. --i) { graphics. int h = w >> 1. graphics. 1). updateLayout(). } } /* Returns the label.BlackBerry Java Development Environment Development Guide /* Method that draws the focus indicator for this button and * inverts the inside region of the shape. graphics. */ public void setShape(int shape) { _shape = shape. ++i) { graphics. x3 = x3 . x2 = x2 . */ protected void drawFocus(Graphics graphics. x2 . } break. for (int i=h-1. } /* Sets the shape. getWidth() .2. */ public String getLabel() { return _label. 1). getHeight() .2). case RECTANGLE: graphics. getWidth() . i<x. _labelWidth = _font. } /* Returns the shape. x2+i. } /* Retrieves the preferred width of the button.invert(1. */ public void setLabel(String label) { _label = label. i>=2.invert(1+i. updateLayout(). h .((i+1)<<1). */ public int getPreferredWidth() { 36 . w . for (int i=1. x-i.1.((i+1)<<1).1.invert(1. boolean on) { switch(_shape) { case TRIANGLE: int w = getWidth().x + 1). int x2 = x3 .invert(i.x. 1.invert(1+i. getWidth() . } break. */ public int getShape() { return _shape. break. getWidth() . 1).2.

min( height. */ protected void paint(Graphics graphics) { 37 . } /* * Redraws this button.getAdvance(_label). } return 0. // Set dimensions. } /* Lays out this button’s contents. **/ protected void layout(int width. // Calculate width. _labelHeight = _font. } case OCTAGON: if (_labelWidth < _labelHeight) { return _labelHeight + 4.min( width. height ). getPreferredHeight() ). } case RECTANGLE: return _labelHeight + 4. } else { return _labelWidth. // Calculate height. } case RECTANGLE: default: return _labelWidth + 8. The field’s manager invokes this method during the * repainting process to instruct this field to repaint itself. case OCTAGON: return getPreferredWidth(). width = Math. int height) { // Update the cached font in case it has been changed.getHeight(). _labelWidth = _font. } else { return _labelWidth << 1. } } /* Retrieves the preferred height of the button. _font = getFont(). getPreferredWidth() ). } else { return _labelWidth + 8. * This field’s manager invokes this method during the layout * process to instruct this field to arrange its contents. given an * amount of available space. setExtent( width. */ public int getPreferredHeight() { switch(_shape) { case TRIANGLE: if (_labelWidth < _labelHeight) { return _labelHeight << 1. height = Math.1: Creating user interfaces switch(_shape) { case TRIANGLE: if (_labelWidth < _labelHeight) { return _labelHeight << 2.

drawLine(0. graphics. 0. x2. x2). graphics. 0). textY. break. int x2 = w-x-1. 0. x3. w . textWidth ).docs.HALIGN_MASK ). 0.java * Copyright (C) 2001-2005 Research In Motion Limited.drawRect(0.samples. graphics. textWidth = Math.6. x. case OCTAGON: int x = 5*w/17.drawLine(0. w.min(_labelWidth. x2). graphics. textX = 4.drawLine(x. x. graphics. graphics. textX.textWidth) >> 1. textY = 2. textX = (w-textWidth) >> 1. case RECTANGLE: default: graphics. 0. h-1). h-1).drawText(_label. */ package com. textWidth = w . w-1. x3). switch(_shape) { case TRIANGLE: int h = (w>>1). w-1. x3. x2. int x3 = w-1.drawLine(m.java /** * ContextMenuSample.BlackBerry Java Development Environment Development Guide int textX. 38 .rim. } graphics. x2. int w = getWidth(). int m = (w>>1)-1.drawLine(x2. textWidth. x3). graphics.6). x3.ELLIPSIS | DrawStyle. x). graphics. graphics.drawLine(0.drawLine(x3. 0). textX = (w . x2).drawLine(0. } } Code sample: Creating a custom context menu Example: ContextMenuSample. m. x. 0). x.drawLine(x. textY = (w-_labelHeight) >> 1. break. x3. x. h-1.min(_labelWidth. graphics. x3. break. graphics. h-1.contextmenus. All rights reserved. textY = h >> 1. textY. (int)( getStyle() & DrawStyle. getHeight()).h). textWidth = Math. 0.drawLine(0.drawLine(x2.

ui. 200000.docs. public static void main(String[] args) { ContextMenuSample app = new ContextMenuSample().api.rim. net. } MyContextField(String text) { super(text). com. mainScreen.device.i18n. } }.addItem(myContextMenuItemA). ContextMenuSampleResource.enterEventDispatcher(). MENUITEM_TWO.*.*. public class ContextMenuSample extends UiApplication implements ContextMenuSampleResource { private MyContextField myContextField. 200000.resource.getBundle( ContextMenuSampleResource.device.ui.*.*. private static class MyContextField extends RichTextField { private MenuItem myContextMenuItemA = new MenuItem( _resources.BUNDLE_NAME).device.rim. net.api. private static ResourceBundle _resources = ResourceBundle. } }.rim. } // Inner class to define a new field. } protected void makeContextMenu(ContextMenu contextMenu) { contextMenu.add(myContextField).device. 10) { public void run() { onMyMenuItemA(). contextMenu.component. } private void onMyMenuItemB() { // Perform an action when user selects menu item.rim. 39 . 10) { public void run() { onMyMenuItemB().system.api. private MenuItem myContextMenuItemB = new MenuItem( _resources.samples. MyContextField myContextField = new MyContextField(“Field label: “).*. MENUITEM_ONE.rim.*.1: Creating user interfaces import import import import import import net.container. private void onMyMenuItemA() { // Perform an action when user selects menu item.addItem(myContextMenuItemB). } } public ContextMenuSample() { MainScreen mainScreen = new MainScreen().api. net.api. net.device.rim. app.BUNDLE_ID.ui.

device.java /** * DiagonalManager. i<numberOfFields.docs.ui. */ package com. import import import import net. net. Field field. net.device. ++i) { field = getField(i).getPreferredWidth().custommenu. ++i) { width += getField(i). int numberOfFields = getFieldCount().getPreferredHeight().device. 40 . All rights reserved. ++i) { height += getField(i). } } Code sample: Creating a custom layout manager Example: DiagonalManager.component. for (int i=0. } return height. i<numberOfFields. int y = 0. for (int i=0. } public int getPreferredWidth() { int width = 0. } return width. height ). net.rim.api.java * Copyright (C) 2001-2005 Research In Motion Limited.api.*.*. layoutChild( field.system.samples.*. } public int getPreferredHeight() { int height = 0. i<numberOfFields.api.*.container.rim.rim. } protected void sublayout(int width.BlackBerry Java Development Environment Development Guide pushScreen(mainScreen).ui.rim. int numberOfFields = getFieldCount().ui. int numberOfFields = getFieldCount(). width. for (int i=0. class DiagonalManager extends Manager { public DiagonalManager(long style) { super(style). int height) { int x = 0.rim.device.api.

*/ package com.elementAt(index).*. } } } Code sample: Creating a custom list Example: SampleListFieldCallback.getPreferredWidth().ui. 0.ui.api.device. y += field.drawText(text. } setExtent(width. int w) { String text = (String)listElements.samples. x. app. g.getFieldWithFocusIndex()) { return super.rim. import import import import import java.rim.component.enterEventDispatcher(). net.height).rim.util. if(alt) { if(direction < 0) { // action to perform if trackwheel is rolled up } else { // action to perform if trackwheel is rolled down } } if (index == this. } else { return index. int y.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. x += field. w). public static void main(String[] args) { SampleListFieldCallback app = new SampleListFieldCallback(). boolean alt) { int index = this.api.*. } 41 . public class SampleListFieldCallback extends UiApplication { private ListField myList. Graphics g.nextFocus(direction. alt).*.getPreferredHeight(). public void drawListRow( ListField list. int index. } private static class ListCallback implements ListFieldCallback { private Vector listElements = new Vector().*.*. net. net.listfields.1: Creating user interfaces setPositionChild(field.java /** * SampleListFieldCallback. } protected int nextFocus(int direction.api.device.docs. y.container.system.getFieldWithFocusIndex().api.device.ui.rim.rim.device. net. y). 0.

String p.insert(fieldOne. String fieldThree = “ListField three”.addElement(toInsert). pushScreen(mainScreen). myList. } public void erase() { listElements.insert(2). Example: DemoAppMenuItem. 1). 2).insert(fieldTwo. s).indexOf(p. } public int getPreferredWidth(ListField list) { return Graphics. int s) { return listElements. int index) { listElements. ListCallback myCallback = new ListCallback().samples.menuitem. * the Contacts Demo application appears. */ package com. } public int indexOfList(ListField list.java /** * DemoApplicationMenuItem. myList = new ListField(). myCallback.getScreenWidth(). myCallback. 42 . String fieldOne = “ListField one”.BlackBerry Java Development Environment Development Guide public Object get(ListField list.add(myList). 0).insert(1).insert(0).insert(fieldThree. myList. * * The following code example creates a menu item that appears when * a user views a contact in the address book.setCallback(myCallback). } } Code sample: Creating a new menu item in a BlackBerry Java Application The menu item appears when a BlackBerry® device user views a contact in the address book. When a user clicks the menu item. mainScreen.docs.java * Copyright (C) 2003-2007 Research In Motion Limited. } public void insert(String toInsert. When a BlackBerry device user clicks the menu item. myList. myList.elementAt(index). String fieldTwo = “ListField two”. } } public SampleListFieldCallback() { MainScreen mainScreen = new MainScreen(). int index) { return listElements. myCallback.removeAllElements().rim. the ContactsDemo application appears.

menuitem.rim.samples.ui.addMenuItem(location.rim. net. app. addMenuItem(ARG_LAUNCH_CONTACT_DEMO.docs. new String[]{ARG_LAUNCH_CONTACT_DEMO}).ContactsDemo().blackberry. new ContactsDemoMenuItem()). amir.pim. net.pdap. long location. ApplicationDescriptor app = ApplicationDescriptor. } private static void addMenuItem(String argOfAppl. javax. } else { String appToLaunch = args[0].enterEventDispatcher(). if(ARG_LAUNCH_CONTACT_DEMO.exit(0). //private static final String ARG_LAUNCH_APP2 = “2”.1: Creating user interfaces import import import import import net.*.blackberry.contactsdemo... locationToAddMenuItem. net. System. ApplicationMenuItem applMenuItem) { ApplicationMenuItemRepository amir = ApplicationMenuItemRepository. public final class DemoAppMenuItem extends Application { private static final String ARG_LAUNCH_CONTACT_DEMO = “1”.rim.device.system.*.*.length == 0) { DemoAppMenuItem app = new DemoAppMenuItem().api.rim. //set the argument so that we know which app we want to have launched app = new ApplicationDescriptor(app.api.getInstance().rim.microedition.equals(appToLaunch)) { new com.*. etc public static void main(String[] args) { if(args == null || args.Dialog.device. } //add more else ifs here } } DemoAppMenuItem() { long locationToAddMenuItem = ApplicationMenuItemRepository.api. app).api. applMenuItem.currentApplicationDescriptor(). //. } /** * Create the menu item classes here 43 .enterEventDispatcher().MENUITEM_ADDRESSCARD_VIEW.component.*.

will call the main method of this app. } public String toString() { return “Open the Contacts Demo”.BlackBerry Java Development Environment Development Guide */ private static class ContactsDemoMenuItem extends ApplicationMenuItem { ContactsDemoMenuItem() { super(20). //on invokation.requestForeground(). } return null. expected a Contact instance”). } public Object run(Object context) { BlackBerryContact c = (BlackBerryContact)context. //an error if this doesn’t work if ( c != null ) { Application. with argument as specified in addMenuItem } else { throw new IllegalStateException( “Context is null. } } } 44 .getApplication().

2. original. int[] argb = new int[original. see if they are identical.println("Bitmap rendered incorrectly with RGB data. 0. } .equals()."). Compare two images to > Invoke Bitmap.INFORMATION). Retrieve image data. void getARGB(int[] argbData. Bitmap original = Bitmap.getHeight()).2 Using graphics and multimedia Using images Drawing and rendering images Using audio Using rich media Code samples Using images Use raw images Task Allow BlackBerry® Java® Applications to use raw image data.getWidth().getHeight()].out. int y. original. invoke Bitmap.println("Success! Bitmap renders correctly with RGB data.getARGB(). 0.out. 0.getWidth() * original. 1. int scanLength.equals(original)) { System. original. } else if(!restored. int x.getPredefinedBitmap(Bitmap. int offset. Steps > To retrieve raw image data from a specified region of a bitmap and store the data in an integer array. int width.getARGB(argb.").equals(original)) { System. invoke Bitmap. To store the raw image data of the new or predefined bitmap in the integer array.getWidth().getARGB(). Initialize an integer array. if(restored. original. int height).

imagedemo. Steps 1. Invoke EncodedImage. } try { EncodedImage image = EncodedImage. BitmapField field = new BitmapField(). Provide one of the following modes as a parameter to the method: • DECODE_ALPHA: decodes an alpha channel. Invoke Class."). Save an image to the project folder or sub-folder.createEncodedImage(). } catch (IllegalArgumentException iae) { System.ImageDemo"). which EncodedImage. .out.createEncodedImage() throws if the byte array that you provide as a parameter does not contain a recognized image format.createEncodedImage(data.png"). private InputStream input. See “Code sample: Using a raw image to recreate an encoded image” on page 60 for more information. 1. 2.docs. Add the image to the project in the BlackBerry® Integrated Development Environment. // Store the contents of the image file. 46 . 2. } Encode an image. if you set the scaling factor to 2. For example. 0. } catch (IOException e) { // Handle exception. if one exists (this is the default mode) • DECODE_NATIVE: forces the BlackBerry® Java® Application to decode the bitmap to the native bitmap type of the handheld software application • DECODE_READONLY: marks the decoded bitmap as read-only • Set the image display size.rim. > Invoke EncodedImage.println("Image format not recognized. private byte[] data = new byte[2430]. } Display an encoded image. The inverse of the integer specified by the scale parameter scales the image.. data. 1.read(data).forName("com. the image decodes at 50% of its original size.out.. Set the decoding mode. Invoke EncodedImage. To add the BitmapField to the screen. To assign the encoded image to a BitmapField. // Read the image data into the byte array.getResourceAsStream() to retrieve the image as an input stream of bytes.BlackBerry Java Development Environment Development Guide Use encoded images Task Access an image. 2. 1. } catch (ClassNotFoundException e) { System.println("Class not found"). try { input. 3. 2.setImage(). invoke BitmapField. Check for an IllegalArgumentException. getResourceAsStream("/images/example.setImage(image).setScale().samples. invoke add(). add(field). try { input = Class.setDecodeMode().length). This method creates an instance of EncodedImage using the raw image data in the byte array. field.

Determine the number of colors that the BlackBerry® device supports. 30). 1.getGraphics(). Use the whole screen. 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 • 47 . 30. BitmapField surfaceField = new BitmapField(surface).getNumColors(). 30. 100).isColor(). Invoke one of the following methods: • Graphics. 1.drawRect(15. graphics.2: Using graphics and multimedia Drawing and rendering images Position an image Task Use an individual field.add(surfaceField). Set the pixel transparency in the drawing area. Invoke Screen. mainScreen. 15. Invoke Graphics. Define a global alpha value within the following range: • 0 (0x0000): completely transparent • 255 (0x00FF): fully opaque Determine raster operations that the BlackBerry® Java® Application supports. graphics.setGlobalApha() • Graphics. Steps 1. Graphics graphics = new Graphics(surface). Draw an image in color Task Determine whether the BlackBerry® device supports color display. 2. Make sure your methods perform their drawing functions within the boundaries of the screen. 2. 30). 2. 1. 10.fillRect(10.getGlobalAlpha() 2. Graphics graphics = Screen.getGraphics(). Steps > Invoke Graphics. > Invoke Graphics. Bitmap surface = new Bitmap(100.isRopSupported(int). Add the BitmapField to the screen. Invoke the Graphics() constructor.

out. 0xCC0000 }. Determine if a drawing style is set. Turn a drawing style off. 50. Steps > Invoke Graphics. null. int[] X_PTS = { 0.getWidth().drawRGB(argb.drawShadedFilledPath(X_PTS. } Turn a drawing style on. 48 . } See “Code sample: Drawing a new bitmap using an existing bitmap” on page 61 for more information.getHeight()). 240.setDrawingStyle(int drawStyle. BitmapField. Graphics graphics = new Graphics(restored).println("Bad arguments. restored.drawShadedFilledPath(): public void drawShadedFilledPath(int[] xPts. Y_PTS. 1. } catch (IllegalArgumentException iae) { System. restored.println("Error occurred during drawing: " + e). int[] yPts. 0. Invoke Browser.isDrawingStyleSet(int drawStyle).getHeight()). > > > Invoke Graphics. invoke Graphics. BitmapField field = new BitmapField(original. Bitmap restored = new Bitmap(original. BitmapField surfaceField = new BitmapField(surface). 50. alpha defined.getWidth(). Create a Graphics object using the empty bitmap as the drawing surface."). boolean off). Use a monochrome bitmap as The STAMP_MONOCHROME option enables BlackBerry® Java® Applications to use monochrome bitmaps as stamps by rendering the nontransparent region in color.BlackBerry Java Development Environment Development Guide Task Draw a set of shaded. The following example draws a path that blends from blue to red: Bitmap surface = new Bitmap(240. byte[] pointTypes.getDefaultSession(). BrowserSession soundclip = Browser. Using audio Start the media player from the BlackBerry Browser 1. This option applies to bitmaps that are 1 bit and have a stamp. restored. int[] offsets). } catch(Exception e) { System. filled paths. 240 }.setDrawingStyle(int drawStyle.getWidth(). original. original. To draw a new image using raw data retrieved from the original. Invoke Graphics.rawRGB().STAMP_MONOCHROME).getDefaultSession(). 0. Invoke Graphics. Graphics graphics = new Graphics(surface). add(surfaceField). int[] Y_PTS = { 20. Draw an image on an empty bitmap. 0xCC0000. int[] colors. Create an empty bitmap. null). drawColors.getType().out. boolean on). 2. 20 }. int[] drawColors = { 0x0000CC. 0. 0x0000CC. try { graphics. 0. The example below copies the type and size from an existing bitmap. 3. 160). try { graphics.

MIDlet. Invoke BrowserSession.UiApplication.device. reg. soundclip.invoke(Invocation invocation) using the new Invocation object as a parameter.invoke(invocation).content.content package.microedition.Application or net.. 49 .midlet. use a media type supported by the media player as a parameter.. The classname parameter is the name of the class in the application that extends javax.microedition. Start the media player with no content 1. Import javax. The classname parameter is the name of the class in the application that extends javax.content.getRegistry().api. 3. net. Invoke Registry. Invoke Registry.mp3" ).microedition.MIDlet.api.api. Invoke Registry.UiApplication.rim.getRegistry(String classname). 4.microedition. Import the javax.ui.system.invoke(invocation).displaypage(). net. storing a reference to the returned object in a Registry object.Application or net. Import the javax. reg. Invoke Registry.content package.CONTENT_HANDLER_MEDIA_PLAYER). Registry reg = Registry.microedition. Create a new instance of an Invocation object. 4.system.device. Registry reg = Registry. storing a reference to the object in an Invocation object. storing a reference to the returned object in a Registry object.midlet. Create a new instance of an Invocation object. Start the media player with content 1. BlackBerryInvocation. Invocation invocation = new Invocation(file://. null. 2.invoke(Invocation invocation) using the new Invocation object as a parameter.rim.ui.rim.microedition. and store a reference to the object in an Invocation object.device.).getRegistry(String classname).api.getRegistry().device. Invocation invocation = new Invocation(null.displayPage( "file:///SDCard/BlackBerry/music/TarzanYell. 2.rim. 3.2: Using graphics and multimedia 2. Import javax.

createPlayer("rtsp://streaming. The type parameter represents the input media content type. You determine the tempo by multiplying the tempo modifier by 4 to keep it within the byte range of 1 to 127. String type). Task Create a player for a sequence of tones.start(). Create a player for media from an input stream. Invoke Manager. } catch (IOException ioEx) { } catch (MediaException meEx) {} Create a player for streaming For BlackBerry devices that operate on EDGE networks. use the API items in the javax. Steps > Use the ToneControl to permit playback of a BlackBerry® device user-defined sequence of tones in an unvarying pitch. RecordStore recSt. passing an RTSP locator as a parameter. > Invoke Manager. try { InputStream inpStr = new ByteArrayInputStream((store. Player p = Manager.com/streaming_video. Check for a MediaException if null is the content type. See “Access media player functionality” on page 89 for more information on media player controls. int recId.createPlayer(inpStr.createPlayer(String locator). Invoke Manager. Real Time Streaming Protocol (RTSP) functionality is media. 2. Tempos in the range of 20 bpm to 508 bpm equate to a tempo modifier range of 5 to 127.createPlayer(InputStream stream. Create a player for media from a URL. 50 . p.BlackBerry Java Development Environment Development Guide Create a media player To play audio on a BlackBerry® device.getRecord(recId)).media package (JSR 135) to create a media player and then add functionality to it.rim. The string parameter must use URI syntax that describes the media content.microedition. "audio/mpeg"). available only over a Wi-Fi® connection. Manager. Tempo is the beats per minute with 1 beat equal to 1/4 note. > 1.createPlayer(String locator).3gp").

control. Store a reference to the Player object that the call to createPlayer(String locator)returns. where locator is a string in URI syntax that describes the video content.realize(). Start a try block. Invoke Manager. // C note (byte)(C4 + 2).Field" as the arg parameter.TEMPO. Invoke Player.rim. Field videoField.USE_GUI_PRIMITIVE. // Note length 8 (quaver) = 1/8th of a note duration byte byte byte byte byte C4 = D4 = E4 = G4 = rest ToneControl.avi"). Object arg).initDisplayMode( VideoControl. // version 1 // set tempo 51 . VideoControl _videoControl. Check for any exceptions that may have occurred within the try block. 2. } catch ( Exception e ) { System.initDisplayMode(int mode.VideoControl").rim. invoke Player.getControl( "javax. 6. using as a parameter a string representation of the VideoControl class. 7. // value value value value rest = = = = 60 62 64 67 (middle C) (a whole step) (a major third) (a fifth) byte[] mySequence = { ToneControl. For example. _videoControl = (VideoControl)_videoPlayer.api.getControl(). VideoControl. Use the arg parameter to specify the UI primitive that will display the video. in a BlackBerry Application.ui.createPlayer(String locator). videoField = (Field)_videoControl.VERSION. _videoPlayer. 4. // 30 x 4 = tempo of 120 bpm byte duration = 8. 5.C4. Steps 1. ToneControl. Cast the returned object as a VideoControl object. _videoPlayer = Manager.realize(). To enable a Player to get the information it requires to acquire media resources.2: Using graphics and multimedia Task Create a player that displays a video in a field.api.out. try { 3. tempo.println( "Exception: " + e. "net. See the API reference for the BlackBerry Java Development Environment for more information.toString() ).createPlayer("file:///SDCard/BlackBerry/videos/ soccer1. } Code fragment: Creating a player for a sequence of tones Example: Sequence of tones // "Mary Had A Little Lamb" has "ABAC" structure // Use block to repeat "A" section byte tempo = 30. // D note (byte)(C4 + 4). use "net. // E note (byte)(C4 + 7). // G note = ToneControl.Field" ). invoke VideoControl. 1. Player _videoPlayer. To initialize the mode that a videoField uses to display the video.media.ui. casting the object that this method returns as a Field object. and Field variables.device.device.SILENCE. Create Player.microedition.

duration try{ Player p = Manager. D4. // // Content of "A" section E4. duration. E4.forName("com. duration.length . G4. // // Play "A" section ToneControl. D4. E4.microedition. duration. c. E4.BlackBerry Java Development Environment Development Guide // // Start define "A" section ToneControl. "audio/mpeg"). InputStream is = clazz. D4. duration. p. duration. cnt >= 0. duration.BLOCK_START. C4. 0. 0. duration. rest.rim. D4.setSequence(mySequence). D4.media.mp3").getResourceAsStream("/ TarzanYell.TONE_DEVICE_LOCATOR). // // Play "C" section D4. E4.prefetch(). duration. --cnt) { if (types[cnt]. duration. for (int cnt = types. 0. 0. duration. E4.createPlayer (is.PLAY_BLOCK. duration.createPlayer(Manager.AudioDemo"). duration.getSupportedContentTypes(null).realize().samples. }. ToneControl c = (ToneControl)p.getControl("ToneControl"). duration.start(). rest. // // Repeat "A" section ToneControl.realize(). C4. G4. duration. E4.1. p.Manager. duration. duration. player.PLAY_BLOCK. } catch (IOException ioe) { } catch (MediaException me) { } Code fragment: Creating a player for media from an input stream Example: Play an MP3 audio file //First we determine the supported content types String types[] = Manager. duration. // // End define "A" section ToneControl. duration. rest. duration.BLOCK_END. // // Play "B" section D4.equals("audio/mpeg")) { try { //Retrieve the MP3 file Class clazz = Class. player. 52 . //Create an instance of the player from the InputStream Player player = javax. duration.

microedition.net/abc. > Invoke Player. Invoke Player. To provide additional functionality for a media player.createPlayer("http://www. try { Determine the controls that a 1.media package contains a number of Control interfaces. Invoke Player.rim.equals("audio/midi ")) { //this is where you would play midi files } } } Play media You can use the API items in the javax.getControls().media package (JSR 135) to create a BlackBerry® Java® Application that can play media. The Player returns to the Prefetched state when you invoke Player.start(). media player supports. use one or more of the controls that the media player supports. The javax.microedition. You can use the same object to access multiple controls: for example.test. See the API Reference in the BlackBerry® Java® Development Environment for more information about the javax. 53 .start().start(). Steps 1.stop() or when it reaches the end of the media file. one object can be both a VolumeControl and a ToneControl. Player p = Manager.2: Using graphics and multimedia //start the player player.wav").media package.prefetch(). } catch (Exception ex) { } } else if (types[cnt].realize(). 2.microedition. Invoke Player. Task Prepare the media player. Start the media player.equals("audio/x-wav ")) { //this is where you would play wav files } else if (types[cnt]. p. } catch (MediaException pe) { } catch (IOException ioe) { } 2.

Implement the methods of the VideoControl interface to give a BlackBerry® Java® Application a variety of video support features.prefetch(). private void doPlay() throws IOException. p. 2. Task Listen for changes to the media player state. invoke addPlayerListener.media package (JSR 135) to create a BlackBerry® Java® Application that can listen for and send media player events.stop(). Adjust the volume of the media player.start(). To register the player listener.realize(). Listen for media player events You can use the API items in the javax. 2. Close the media player. if ( event == PlayerListener.getControls() to retrieve a VideoControl object.microedition. Object eventData) {// Release resources player. public void playerUpdate(Player player. } 54 .END_OF_MEDIA ) // Add code for actions if the end of media is reached. > Invoke Player. p.rim.addPlayerListener(this).String event. Define a volume value in the following range: • 0: no volume • 100: maximum volume level The PlayerListener sends a VOLUME_CHANGED event when its state changes.BlackBerry Java Development Environment Development Guide Task Enable video playback support Steps 1. MediaException {Player p = Manager. p. a registered player listener. including the following: • control over the mode of video display (one of USE_GUI_PRIMITIVE or USE_DIRECT_VIDEO) • control over the location of the video with respect to the canvas that displays the video • access to the X-coordinate and the y-coordinate of the video with respect to the GUI object that displays the video • displaying or hiding video • resizing the video image 1. Invoke VolumeControl(). 2. Object eventData).mp3").close(). p.com/rim.createPlayer("http://www. Steps 1. Invoke Player. } Send a media player event to > Invoke playerUpdate(Player player. String event. Implement PlayerListener.

To play PME content that exists on BlackBerry devices.out.2.createMedia("http://webserver/sample. } catch (MediaException me) { System.getUI()).out. Play rich media content Task Set the PME object for playback. Note: To display content created in Plazmic® Media Engine Version 4. Steps > Invoke MediaPlayer.println("Error: “ + me. base_url) to set a base URL.”). screen.NO_VERTICAL_SCROLL | Screen. The first time that you invoke MediaManager. When you invoke createMedia() subsequently.").2: Using graphics and multimedia Using rich media Playing rich media content To play rich media content. try { player.println("Error: requested content was not downloaded. Retrieve a UI object that displays rich media content. and add it to a Screen for display.2. Cast the object that getUI() returns as a Field.println("Error: requested content type is not supported.out. Create a MediaManager object. the URI must be absolute.createMedia(). 1.add((Field)player. Screen screen = new Screen(Screen.2.setProperty(“URI_BASE”.pme"). } catch (IOException ioe) { System. Invoke MediaManager. use methods from the MediaManager class. } Allow an application’s screen To display content created in Plazmic Media Engine Version 4. Version 4. 2. use the following classes: • • To retrieve PME content on BlackBerry® devices or networks. to display content created in > Create an instance of a screen object using the NO_VERTICAL_SCROLL and NO_HORIZONTAL_SCROLL Plazmic Media Engine fields (inherited from the Manager class).createMedia(). See “Playing rich media content” on page 55 for more information on how to create a screen that does not support scrolling. 55 .setMedia(media).NO_HORIZONTAL_SCROLL). unless you first invoke MediaManager. } 2. MediaPlayer player = new MediaPlayer(). the screen must not support scrolling. try { Object media = manager. the screen must not support scrolling. MediaManager manager = new MediaManager(). use methods from the MediaPlayer class. } catch (MediaException me) { System. the URL that the method used previously is the base. Invoke MediaPlayer.getUI().setMedia(). Download rich media content 1.getCode()).

start().getMessage()). Steps 1.REALIZED) { try { player.BlackBerry Java Development Environment Development Guide Task Play rich media content.getState() == MediaPlayer.start(). Check the media player state. } catch(MediaException me) { System.getCode() + me. if(player. See “Code sample: Retrieving and displaying a rich media file” on page 63 for more information. 56 . Invoke MediaPlayer. } } 2.println("Error occurred during media playback: " + me.out.

break. int eventParam. private MediaManager manager = new MediaManager(). break. > Invoke addMediaListener() on the MediaPlayer and MediaManager objects. 57 . } } } Register the listener. int event. private MediaListenerImpl _listener = new MediaListenerImpl(). public final class MediaListenerImpl implements MediaListener { public void mediaEvent(Object sender.addMediaListener(_listener). case MEDIA_REALIZED: // Perform action.2: Using graphics and multimedia Listen for rich media events Task Listen for media engine events. player. 2. Object data) { switch(event) { case MEDIA_REQUESTED: // Perform action. Implement the MediaListener interface to let your BlackBerry® Java® Application listen for media engine events.addMediaListener(_listener). break. case MEDIA_COMPLETE: // Perform action. private MediaPlayer player = new MediaPlayer(). break. case MEDIA_IO: // Perform action. Steps 1. Implement mediaEvent() to handle all possible media events. manager.

pme").BlackBerry Java Development Environment Development Guide Task Steps Load content in the 1. To retrieve the URL string of the content. } break... when the content the application downloads finishes loading on the BlackBerry® device. and play it when 2.LOADING_STARTED: 58 . print a message to the console. 3. To download content for future playback. invoke MediaPlayer.getStatus(). Extend the net.println("Error playing media” + me. int event. 4.getMessage()). In your implementation of mediaEvent(). background. add code to manage the MEDIA_REALIZED event that occurs the download is complete. For the LOADING_FAILED status.LoadingStatus class. player.createMediaLater().. 2.getMessage().mediaengine.setMedia(data). } } Track the progress of a download. To retrieve the error code. To retrieve the detailed message.start().. invoke LoadingStatus. } catch(MediaException me) { System.. case MEDIA_REALIZED: try { player.setMedia(data). and manage each status.getCode() + me. . 1. To retrieve the download status. To start playback.mediaEvent(). int eventParam. invoke MediaPlayer. } break. 3.out. 4. For each normal status. when the MEDIA_IO event occurs. To register the content that the data parameter specifies. cast the Object in the data parameter to a LoadingStatus object. Object data) { switch(event) { .. int eventParam.getStatus()) { case LoadingStatus. } . manager. invoke LoadingStatus.getSource().. Object data) { switch(event) { . int event. 3. invoke MediaManager. Code fragment: Managing rich media content download events Example: Code fragment: Managing rich media content download events public void mediaEvent(Object sender. Manage a failed download. public void mediaEvent(Object sender. 2. break.plazmic. perform the following actions: 1.start(). In MediaListener. case MEDIA_IO: { LoadingStatus s = (LoadingStatus)data.io.rim. switch(s. invoke LoadingStatus.getCode(). invoke LoadingStatus..createMediaLater("http://webserver/sample.

Steps > Implement the net. create a custom Connector.Connector interface. int code = s.plazmic.rim.println("Loading completed"). String). } // End switch s. break. break.getStatus().getMessage().out. case MediaException. switch (code) { case MediaException. Implement InputStream getInputStream(String. break.getMessage() + "\n" + s.LOADING_FAILED: String errorName = null. } } System. break. break. } else { // default unidentified error errorName = "Loading Failed".out. Implement void setProperty(String. > 59 .getSource() + "\n" + s.REQUEST_TIMED_OUT: errorName = "Request timed out" + "\n" + s.LOADING_READING: System.out. break.UNSUPPORTED_TYPE: errorName = "Unsupported type" + s. } errorName += "\n" + s.println("Parsing in progress"). default: { if (code > 200) { // A code > 200 indicates an HTTP error errorName = "URL not found". Return an input stream to read content > from a URI. ConnectionInfo). break. case LoadingStatus. case MediaException.println("Loading in progress").mediaengine. } See “Code sample: Implementing a listener to download rich media content” on page 64 for more information. break.LOADING_FINISHED: System.INTERRUPTED_DOWNLOAD: break. case LoadingStatus.getSource().getSource().INVALID_HEADER: errorName = "Invalid header" + "\n" + s. case MediaException.getSource().println(errorName). case LoadingStatus.2: Using graphics and multimedia System.out. Set custom connector properties.getCode(). Task Implement a custom connector.getCode() + ": " + s.io. Create a custom connector for rich media connections To add support for a custom protocol or to override default behavior. break.

BlackBerry Java Development Environment Development Guide Task Release the custom connection. byte[] data = new byte[IMAGE_SIZE].container. public ImageDemoScreen() { super().component.setConnector(new CustomPMEConnector(manager. Register a custom connector. net. */ package com.api.rim. try { 60 . setTitle(new LabelField(“Image Demo Sample”)). } public ImageDemo() { pushScreen(new ImageDemoScreen()).enterEventDispatcher(). Steps > > Implement void releaseConnection(ConnectionInfo).device.java * Copyright (C) 2001-2005 Research In Motion Limited.*. See “Code sample: Implementing a custom connector” on page 66 for more information.device.*.system.*.docs. Code samples Code sample: Using a raw image to recreate an encoded image Example: ImageDemo.java /** * ImageDemo.samples.rim.imagedemo.rim. In your main method.api. java.ui.api.io. InputStream input.device.getDefaultConnector())).*. app.device.rim. MediaManager manager = new MediaManager().setConnector(). net.java sample retrieves raw data from an image that is included in its project. and then uses that raw data to recreate an EncodedImage. manager. /* The ImageDemo.rim.ui.api. net.*. import import import import import net.ui. All rights reserved. */ public class ImageDemo extends UiApplication { public static void main(String[] args) { ImageDemo app = new ImageDemo(). } } final class private private private ImageDemoScreen extends MainScreen { static final int IMAGE_SIZE = 2430. invoke MediaManager.

java /* * DrawDemo.rim.api. System. } else if (input != null) { System.api. net. data.imagedemo.ui.”).out.rim.device.read(data).println(“Error: input stream is not initialized.createEncodedImage(data.docs.rim.device.println(“OK: input stream is initialized.png”).docs.rim.2: Using graphics and multimedia input = Class.java * Copyright (C) 2002-2005 Research In Motion Limited. It then displays the original and restored images.”). } catch (ClassNotFoundException e) { System. } catch (IOException e) { // Handle exception. */ package com.*. Example: DrawDemo.rim.java sample retrieves raw data from a predefined bitmap image.ImageDemo”).”). } catch (IllegalArgumentException iae) { System.drawing. } try { EncodedImage image = EncodedImage.samples.println(“Class not found”). and then draws a new bitmap using the data.”). net. net.rim. It then displays the original and restored images. */ public class DrawDemo extends UiApplication { 61 .java sample retrieves raw data from a predefined bitmap image.api.getResourceAsStream(“/images/ hellokitty.component.out.println(“Image format not recognized. 0.ui. try { int code = input.out. the DrawDemo.container. import import import import net.system.device.device.out. } if(input == null) { System.*.*.getBitmap())). add(new BitmapField(image. } } } } Code sample: Drawing a new bitmap using an existing bitmap To draw a new bitmap image.println(“Total number of bytes read into buffer: “ + code + “ .forName(“com.samples.api.out. /* The DrawDemo.*.ui.length).

LabelField title = new LabelField(“UI Demo”.equals(original)) { System. 0.getHeight()]. restored. } } final class DrawDemoScreen extends MainScreen { public DrawDemoScreen() { super(). add(new LabelField(“Restored bitmap: “)). // Draw new image using raw data retrieved from original image. try { graphics. app. } if(restored.getPredefinedBitmap(Bitmap.getWidth(). 0.getHeight()). int[] argb = new int[original. Graphics graphics = new Graphics(restored).equals(original)) { System.getWidth(). // Retrieve raw data from original image.getWidth(). original. restored. setTitle(title). add(new LabelField(“Original bitmap: “)).drawRGB(argb.println(“Bitmap rendered incorrectly with RGB data.”).STAMP_MONOCHROME).USE_ALL_WIDTH).BlackBerry Java Development Environment Development Guide public static void main(String[] args) { DrawDemo app = new DrawDemo(). 0.getWidth().println(“Success! Bitmap renders correctly with RGB data.enterEventDispatcher().”).getWidth() * original.getHeight()). restored. } public DrawDemo() { pushScreen(new DrawDemoScreen()). 0.out. original.getARGB(argb. BitmapField field2 = new BitmapField(restored).out. original. original. original. 0. Bitmap original = Bitmap.getWidth(). } catch(Exception e) { System. } BitmapField field1 = new BitmapField(original. } } 62 . 0. } else if(!restored. add(field2).getType(). original. LabelField. Bitmap restored = new Bitmap(original.out.INFORMATION).println(“Error occurred during drawing: “ + e). BitmapField. add(field1).getHeight()).

start().*.println(me.println(me.getMessage()).rim.mediaengine. Example: MediaSample.out. System. All rights reserved.ui.device. setTitle(title).io.println(me. System.samples. import net.out.container.component.pme file from a web server and displays it on the BlackBerry® device. } catch (IOException ioe) { } catch (MediaException me) { System.pme”).api.java /** * MediaSample. MediaPlayer player = new MediaPlayer().ELLIPSIS | LabelField.ui. import import import import import java. MediaManager manager = new MediaManager(). LabelField. player.println(me.getMessage()).api.*. public class MediaSample extends UiApplication { public static void main(String[] args) { MediaSample app = new MediaSample(). app.device.out.plazmic. System.enterEventDispatcher().mediasample.system.rim. */ package com.out.*. } catch(MediaException me) { System.println(“Error occured during media playback: “). net. net.println(“Error during media loading: “).rim.out.getCode()).java * Copyright (C) 2001-2005 Research In Motion Limited. } final static class MediaSampleScreen extends MainScreen { public MediaSampleScreen() { super().api.rim.device.2: Using graphics and multimedia Code sample: Retrieving and displaying a rich media file The MediaSample. LabelField title = new LabelField(“Media Sample”.device.*. try { Object media = manager.java sample retrieves a .getCode()). try { player.getUI()).docs.*.api.rim.setMedia(media).rim. net. System.out.createMedia(“http://webserver/SVGFILE. } public MediaSample() { pushScreen(new MediaSampleScreen()).USE_ALL_WIDTH). } add((Field)player. net.ui. } 63 .*.

*. } public MediaSample2() { _screen = new MediaSample2Screen(). case MEDIA_REALIZED: try { 64 . break.api.*. public class MediaSample2 extends UiApplication { private MediaPlayer player = new MediaPlayer(). net. private MediaManager manager = new MediaManager().println(“Media requested”). break.out.ui.docs.system.mediaengine.*. int event. private MediaSample2Screen _screen.mediaengine.io.device. case MEDIA_COMPLETE: System. import net.api. Example: MediaSample2. pushScreen(_screen). public static void main(String[] args) { MediaSample2 app = new MediaSample2().rim. int eventParam.*. import import import import import java.out. } public final class MediaListenerImpl implements MediaListener { public void mediaEvent(Object sender. All rights reserved.component.java sample implements a listener to download media content in the background and display the download status to the console.device.rim.enterEventDispatcher().container.java /** * MediaSample2.plazmic. Object data) { switch(event) { case MEDIA_REQUESTED: System. net.rim.api. private MediaListenerImpl _listener = new MediaListenerImpl().java * Copyright (C) 2001-2005 Research In Motion Limited. import net.rim.samples.io.ui.rim.BlackBerry Java Development Environment Development Guide } } } Code sample: Implementing a listener to download rich media content The MediaSample2.plazmic. app.*.rim.device.*. net. net.rim.*.ui.api.device. */ package com.println(“Media completed”).mediasample.

s.getSource().getSource() + “\n” + s. switch(s.getCode() + me. } // End switch s.UNSUPPORTED_TYPE: errorName = “Unsupported type” + s.getStatus().getCode().getMessage()). break. break. int code = s. default: { if (code > 200) { // A code > 200 indicates an HTTP error.getStatus()) { case LoadingStatus.out.2: Using graphics and multimedia player.println(“Loading completed”). } else { // Default unidentified error. } } System.getSource().out. case LoadingStatus. case MediaException. case MEDIA_IO: { LoadingStatus s = (LoadingStatus)data.INTERRUPTED_DOWNLOAD: break. player.println(“Parsing in progress”). case MediaException.INVALID_HEADER: errorName = “Invalid header” + “\n” + break.getCode() + “: “ + s. errorName = “URL not found”. errorName = “Loading Failed”. } catch(MediaException me) { System. } errorName += “\n” + s.setMedia(data).LOADING_FAILED: String errorName = null.LOADING_READING: System.LOADING_FINISHED: System.REQUEST_TIMED_OUT: errorName = “Request timed out” + “\n” + break. case MediaException.println(errorName).start().out.getMessage() + “\n” + s. 65 s.println(“Loading in progress”). .getMessage(). break.getSource().LOADING_STARTED: System. break.println(“Error during media loading: “ + me.out. switch (code) { case MediaException. case LoadingStatus.out. } break. break. break. case LoadingStatus.

*. add((Field)player. setTitle(title).delegate = delegate.*.io.createMediaLater(“http://test. info. public class CustomPMEConnector implements Connector { private Connector delegate.java * Copyright (C) 2003-2005 Research In Motion Limited.setConnection(new MyProtocolConnection()). MediaException { if (uri. */ package com.pme file.rim. } public InputStream getInputStream(String uri. } } } Code sample: Implementing a custom connector The CustomPMEConnector.io.com/SVGBS0001. LabelField.startsWith(“myprotocol://”)) { // Perform special tasks. import net.addMediaListener(_listener).mediaengine.rim.addMediaListener(_listener). manager.rim.pme”).getUI()).mediasample.BlackBerry Java Development Environment Development Guide break. CustomPMEConnector(Connector delegate) { this. private InputStream input.docs. ConnectionInfo info) throws IOException.mediaengine.plazmic. // OpenMyInputStream() is a custom method that opens 66 . Example: CustomPMEConnector.samples. manager. import java.pme”). All rights reserved.ELLIPSIS | LabelField.plazmic. player.rim. } } } } final class MediaSample2Screen extends MainScreen { public MediaSample2Screen() { super().*. info.java sample provides a framework for implementing a custom connector. LabelField title = new LabelField(“Media Sample”.rim. import net.setContentType(“application/x-vnd.java /* * CustomPMEConnector.USE_ALL_WIDTH). // Change this to the location of a test .

releaseConnection(info).getConnection(). } return input. } private InputStream openMyInputStream(String uri) { InputStream input = null. } else { input = delegate. } public void releaseConnection(ConnectionInfo info) throws IOException.. MediaException { Object o = info. String value) { delegate.2: Using graphics and multimedia //stream for “myprotocol://” input = openMyInputStream(uri). } } public void setProperty(String property...setProperty(property. } } } 67 .. } public void close() { // . if (o instanceof MyProtocolConnection) { ((MyProtocolConnection)o). value). // @todo: open stream here return input. info). } // Inner class that defines the connection class. public static class MyProtocolConnection { public MyProtocolConnection() { // . // Perform cleanup. } else { delegate.getInputStream(uri.close().

BlackBerry Java Development Environment Development Guide 68 .

When writing a BlackBerry Java Application specifically for BlackBerry devices. With the BlackBerry® Enterprise Server. See the API reference for the BlackBerry Java Development Environment for more information about the RecordStore class. third-party BlackBerry Java Applications are enabled to use persistent storage (ALLOW_USE_PERSISTENT_STORE is TRUE). system administrators can use IT policies to control the use of persistent storage by third-party BlackBerry Java® Applications. In MIDP 2.3 Storing data Use BlackBerry persistent storage Manage persistent data Manage custom objects Use the MIDP record store Code samples Use BlackBerry persistent storage Storage method BlackBerry® persistence model Description The BlackBerry persistence model provides a flexible and efficient way to store data. Contact RIM for information on controlling access to the data. • • In MIDP. Administrative control . the class of the custom type must use the Persistable interface. a MIDlet suite can share the record store with other MIDlet suites. Micro Edition. if an application creates a record store using the RecordStore. use the BlackBerry persistence model.0 and later. To store custom object types. BlackBerry® Java® Applications on the BlackBerry device that are digitally signed by Research In Motion can access the data in the persistent store. MIDP records store data only as byte arrays. BlackBerry Java Applications can share data at the discretion of the BlackBerry Java Application that creates the data. Administrators can set ALLOW_USE_PERSISTENT_STORE to TRUE or FALSE. This policy does not affect the MIDP record store. In the BlackBerry persistence model. Code signing specifies that only authorized BlackBerry Java Applications can access the data.AUTHMODE_ANY field. • The BlackBerry persistence model lets you save any Object in the persistent store. As a result. searching for data in the persistent store is faster than searching in the record store model. BlackBerry persistent storage Feature Security Description By default. By default. store persistent data as records in RecordStore objects. • MIDP record stores The MIDP record store allows a BlackBerry Java Application to be portable across multiple devices that are compatible with the Java Platform.

If the BlackBerry JVM performs an emergency garbage collection operation due to low memory. Data in the PersistentObject retains the values from the last commit in order to preserve data integrity. If the device fails during this operation. partially completed transactions are committed when the BlackBerry device starts. partial updates are not made if an error occurs during a commit. outstanding transactions are committed immediately to avoid compromising data integrity.BlackBerry Java Development Environment Development Guide Feature Data integrity Description To maintain the integrity of data in persistent storage. Outstanding transactions are not committed during normal garbage collection operation. 70 .

> Invoke forceCommit() while synchronizing the monitor object. 3. Commit a monitor object separately from a batch transaction. Steps Each PersistentObject has a unique long key. 2. } Store an object persistently. If any commit in the batch fails. 2.rim. Invoke PersistentStore. the entire batch transaction fails. 1. 71 . synchronized(store) { store. To use a batch transaction to commit objects to the persistent store.rim. static { store = PersistentStore. Right-click this string and click Convert ‘com.commit(). using the unique long key as a parameter. This method retrieves the persistent store monitor that locks the object. Create a single static PersistentObject. Include a comment in your code to indicate the string that you used to generate the unique long key. 3. Synchronize on the object. such as com. Select this string.samples. 2. 2.getPersistentObject. } Store objects in a batch transaction. To save the new content to the persistent store.samples. store.setContents(userinfo). password}. 4. String[] userinfo = {username. type a string value. static PersistentObject store. Invoke commit() as necessary. Invoke setContents() on a PersistentObject.getSynchObject(). This method replaces existing content with the new content. invoke commit().docs. 1. Create a persistent data store.getPersistentObject( 0xa1a569278238dad2L ).userinfo’ to long. invoke PersistentStore. In the BlackBerry® Integrated Development Environment. 1.docs.userinfo. 1.3: Storing data Manage persistent data Task Create a unique long key.

> > Invoke PersistentStore. Steps 1. and remove references to it. Remove specific persistent data from a BlackBerry® Java® Application.BlackBerry Java Development Environment Development Guide Task Retrieve persistent data. } else { currentusernamefield.getContents() returns. then all persistent objects that the . To delete individual data. 2. synchronized(store) { String[] currentinfo = (String[])store. providing as a parameter a unique key for the PersistentObject.setText(currentinfo[0]).cod file created are deleted. treat the data as normal objects.cod file that defines a PersistentStore. If you delete the . Invoke getContents() on a PersistentObject.alert(_resources. perform an explicit cast on the object that PersistentObject. To convert to your desired format. currentpasswordfield.setText(currentinfo[1]). 72 .destroyPersistentObject().getString(APP_ERROR)). if(currentinfo == null) { Dialog. A garbage collected operation removes the data. } } Remove all persistent data from an BlackBerr®y Java® Application.getContents().

setContents(_data). Steps 1. Manage custom objects Task Create an object to store data. public static final int SPECIALTY = 3. 2. Create a Vector object in which to store multiple objects. ++i) { _elements[i] = new String(""). public static final int PHONE = 2. public static final int ADDRESS = 1. public RestaurantInfo() { _elements = new String[4]. private static Vector _data. //key is hash of test. store. i < _elements. Create a single static PersistentObject.3: Storing data See “Code sample: Saving user name and password information” on page 75 for more information.restaurants _data = (Vector)store. > In the class for the objects that you want to store. } public void setElement(int id. for ( int i = 0. store.getContents(). synchronized (store) { if (_data == null) { _data = new Vector(). } } public String getElement(int id) { return _elements[id]. implement the Persistable interface.commit().samples. } } 73 . } } } Store data persistently. static { store = PersistentStore. String value) { _elements[id] = value. PersistentObject store.length().getPersistentObject( 0xdec6a67096f833cL ). private static final class RestaurantInfo implements Persistable { private String[] _elements. public static final int NAME = 0.

_data.SPECIALTY)). phonefield.PHONE. Invoke setContents().setElement(RestaurantInfo. 3.SPECIALTY. phonefield. The following code fragment creates a RestaurantInfo object and uses its set methods to define its components.setText(info. Add the object to a vector by invoking addElement().getText()). Steps 1.addElement(info). store.setText(info. addressfield. 2. info. 5. info.getText()). synchronized(store) { 4. > Invoke _data.setContents(_data).commit().} } } See “Code sample: Storing and viewing restaurant information” on page 77 for more information. info. specialtyfield. 74 .getElement( RestaurantInfo.setText(info. } Retrieve the most recently saved object. namefield. Define an object.lastElement().setElement(RestaurantInfo.getElement(RestaurantInfo.PHONE)).lastElement().setElement(RestaurantInfo. namefield.BlackBerry Java Development Environment Development Guide Task Save an object.getText()).getElement(RestaurantInfo. specialtyfield.getText()). invoke commit() on the PersistentObject.NAME)).getElement(RestaurantInfo. store. info.NAME.setText(info. To save the updated data. public void run() { synchronized(store) { _data = (Vector)store.setElement(RestaurantInfo.getContents(). Synchronize with the persistent object so that other threads cannot make changes to the object at the same time.ADDRESS)). if (!_data.isEmpty()) { RestaurantInfo info = (RestaurantInfo)_data. RestaurantInfo info = new RestaurantInfo().addressfield.ADDRESS.

net.*.*. int).component.rim.rim.device.openRecordStore("Contacts". false). Add a record. net.util.api. 0).rim. String dataString = new String(data).container. */ package com. Steps > Invoke openRecordStore().getBytes().ui. Example: UserInfo.3: Storing data Use the MIDP record store Task Create a record store. 75 . type new user names and passwords and save changes. Invoke openRecordStore().ui. null. the method returns all records) • comparator: specifies a RecordComparator object to determine the order in which the method returns the records (if null.enumerateRecords(null.device.userinfo.samples. and specify true to indicate that the method should create the record store if the record store does not exist.addRecord(_data. Retrieve a record. Invoke enumerateRecords() with the following parameters: • filter: specifies a RecordFilter object to retrieve a subset of record store records (if null.java /** * UserInfo. Invoke getRecord(int.device. and provide the following parameters: • a record ID • a byte array • an offset RecordStore store = RecordStore. _data. All rights reserved. Invoke addRecord().length()). 0.rim. > > int id = store. byte[] data = new byte[store.device. store. byte[]. RecordEnumeration e = store.system. the method returns the records in any order) • keepUpdated: determines if the method keeps the enumeration current with the changes to the record store RecordStore store = RecordStore.getRecordSize(id)]. 1. 2. false). true).getRecord(id.java * Copyright (C) 2001-2005 Research In Motion Limited.rim. net.docs. Code samples Code sample: Saving user name and password information This code sample demonstrates how to create a BlackBerry® Java® Application for BlackBerry device users to view their current user names and passwords.*.api.api.*. import import import import import net. net.openRecordStore("Contacts". Retrieve all records.*.api. data.device.ui.api.rim.

import net.BlackBerry Java Development Environment Development Guide import java.getText().docs. } } } }.inform(_resources.commit(). password}. private AutoTextEditField usernamefield.setContents(userinfo). } else { currentusernamefield.resource.device. } public UserInfo() { 76 .setText(null). public class UserInfo extends UiApplication implements UserInfoResource { private static PersistentObject store. UserInfoResource. String password = passwordfield. } }.samples.getContents(). private AutoTextEditField currentpasswordfield.rim.getString(APP_SUCCESS)). store = PersistentStore.setText(currentinfo[0]). if(currentinfo == null) { Dialog.api.getBundle( UserInfoResource. 110.getText().rim.getPersistentObject(0xa1a569278238dad2L).getString(MENUITEM_GET). import com.*.BUNDLE_NAME). String[] userinfo = {username. passwordfield. store. app.getString(MENUITEM_SAVE).alert(_resources. 11 ) { public void run() { synchronized(store) { String[] currentinfo = (String[])store. } private MenuItem saveItem = new MenuItem( _resources.util. private PasswordEditField passwordfield. } Dialog. private MenuItem getItem = new MenuItem( _resources.BUNDLE_ID. private static ResourceBundle _resources.setText(currentinfo[1]).i18n.enterEventDispatcher().*. synchronized(store) { store.getString(APP_ERROR)). 110.setText(null). public static void main(String[] args) { UserInfo app = new UserInfo(). usernamefield. currentpasswordfield. static { _resources = ResourceBundle.*. 10) { public void run() { String username = usernamefield. private AutoTextEditField currentusernamefield.

docs.api.container.ui.add(separator). currentpasswordfield = new AutoTextEditField( _resources. */ package com. } private final class UserMainScreen extends MainScreen { protected void makeMenu( Menu menu. 0). } public void close() { Dialog.*. ““).add(passwordfield). pushScreen(mainScreen).*. mainScreen.component. import net.getString(APP_EXIT)).system.add(saveItem). usernamefield = new AutoTextEditField( _resources. mainScreen. Example: Restaurants.rim.*.rim. menu.add(currentpasswordfield). import net.add(currentusernamefield). int instance ) { menu.getString(FIELD_PASSWORD).java * Copyright (C) 2004-2005 Research In Motion Limited.close(). ““). } } } Code sample: Storing and viewing restaurant information This code sample lets BlackBerry® device users save information about multiple restaurants and view information about the most recently saved restaurant. super.device.getString(APPLICATION_TITLE))).setTitle(new LabelField( _resources. mainScreen. ““). mainScreen.restaurants.rim. mainScreen. currentusernamefield = new AutoTextEditField( _resources. ““).api.add(usernamefield). mainScreen.ui. SeparatorField separator = new SeparatorField(). import net.getString(FIELD_NAME).samples.api.alert(_resources. super.device.api.3: Storing data MainScreen mainScreen = new UserMainScreen().device.makeMenu(menu. import net.java /** * Restaurants.getString(FIELD_CURRENTPASSWORD).rim. passwordfield = new PasswordEditField( _resources.*.device.add(getItem). 77 .rim.ui.getString(FIELD_CURRENTNAME).

specialtyfield.getText()).browser.docs.isEmpty()) { RestaurantInfo info = (RestaurantInfo)_data.addElement(info).PHONE. info.setText(null).setElement(RestaurantInfo.setText(null).getContents(). net.setElement(RestaurantInfo.getElement(RestaurantInfo. EditField specialtyfield.getText()).rim.i18n.getElement(RestaurantInfo.PHONE)).lastElement().getText()). } }.rim.NAME. info. private MenuItem saveItem = new MenuItem(_resources. java.resource.setText(““).getString(MENUITEM_GET). private static PersistentObject store.getString(APP_SUCCESS)). private static ResourceBundle _resources. phonefield. EditField phonefield.WEBSITE)). info.rim. info.getText()).api.setText(info.commit().inform(_resources.*. namefield.setText(info. _data.setContents(_data).*. net.blackberry. } 78 . websitefield.ADDRESS)). 11) { public void run() { synchronized(store) { _data = (Vector)store. 110.getText()). AutoTextEditField addressfield.*. specialtyfield.*.*.getElement(RestaurantInfo. if (!_data. websitefield.invoke.api.util. private static Vector _data.getElement(RestaurantInfo.NAME)).getElement(RestaurantInfo. com.device. addressfield.util.rim.device. info.setElement(RestaurantInfo.setText(info. addressfield.SPECIALTY)). store.api.SPECIALTY. 10) { public void run() { RestaurantInfo info = new RestaurantInfo(). namefield.setText(info.setText(““). specialtyfield.setElement(RestaurantInfo. addressfield. namefield.WEBSITE.blackberry. } Dialog. EditField websitefield.setElement(RestaurantInfo. public class Restaurants extends UiApplication implements RestaurantResource { private private private private private AutoTextEditField namefield.ADDRESS.rim.setText(““).api.getString(MENUITEM_SAVE).samples. net.setText(info. synchronized(store) { store. 110.BlackBerry Java Development Environment Development Guide import import import import import import net. phonefield. phonefield. private MenuItem getItem = new MenuItem(_resources.*. phonefield.

APP_TYPE_PHONE.ARG_CALL. } } } public static void main(String[] args) { Restaurants app = new Restaurants().getPersistentObject(0xdec6a67096f833cL). 12) { public void run() { synchronized(store) { String phoneNumber = phonefield.getString(ALERT_NO_WEBSITE)).getString(MENUITEM_BROWSER). } else { BrowserSession visit = Browser. phoneNumber). } else { PhoneArguments call = new PhoneArguments(PhoneArguments.BUNDLE_NAME).getString(ALERT_NO_PHONENUMBER)).getText().getText(). Invoke. store = PersistentStore.length() == 0) { Dialog. if (websiteUrl.alert(_resources. RestaurantResource. if (_data == null) { _data = new Vector().commit().setContents( _data ).length() == 0) { Dialog.3: Storing data } } }. // Key is hash of test.getBundle( RestaurantResource. 79 .alert(_resources. call). store. 110.getString(MENUITEM_PHONE).restaurants. app.samples.displayPage(websiteUrl). } } } }.invokeApplication(Invoke. private MenuItem phoneItem = new MenuItem(_resources. static { _resources = ResourceBundle.getDefaultSession(). private MenuItem browserItem = new MenuItem(_resources. } } } }. } private static final class RestaurantInfo implements Persistable { // Data. visit. synchronized (store) { _data = (Vector)store.getContents().enterEventDispatcher(). 12) { public void run() { synchronized(store) { String websiteUrl = websitefield. store. if ( phoneNumber. 110.BUNDLE_ID.

getString(FIELD_ADDRESS). } } private final class RestaurantsMainScreen extends MainScreen { protected void makeMenu( Menu menu. ADDRESS = 1. phonefield = new EditField( _resources.getString(APPLICATION_TITLE))).alert(_resources. for ( int i = 0.add(saveItem).getString(FIELD_SPECIALTY). namefield = new AutoTextEditField( _resources.close(). ““). WEBSITE = 3.MAX_VALUE. super.BlackBerry Java Development Environment Development Guide private String[] _elements. websitefield = new EditField( _resources. ““). } public void setElement(int id.getString(FIELD_WEBSITE). 80 . public static public static public static public static public static final final final final final int int int int int NAME = 0.getString(FIELD_NAME). ++i) { _elements[i] = ““.add(getItem). // Fields. specialtyfield = new EditField( _resources.getString(FIELD_PHONE). String value) { _elements[id] = value.makeMenu(menu. PHONE = 2. ““. menu. addressfield = new AutoTextEditField( _resources.length. Integer.FILTER_DEFAULT). Integer. Integer. ““. int instance ) { menu. } public void close() { Dialog. } } public Restaurants() { MainScreen mainScreen = new RestaurantsMainScreen(). menu.add(browserItem). SPECIALTY = 4.FILTER_URL). public RestaurantInfo() { _elements = new String[4]. BasicEditField.MAX_VALUE. super.FILTER_PHONE). instance). BasicEditField.getString(APP_EXIT)). mainScreen.add(phoneItem). i < _elements. menu.MAX_VALUE. } } public String getElement(int id) { return _elements[id]. BasicEditField.setTitle(new LabelField( _resources. ““.

} } 81 . mainScreen.add(websitefield).add(namefield).add(addressfield).add(specialtyfield). pushScreen(mainScreen). mainScreen. mainScreen.add(phonefield). mainScreen.3: Storing data mainScreen.

BlackBerry Java Development Environment Development Guide 82 .

By default. so you must build the synchronization logic into your BlackBerry Java Application. A BlackBerry® Java® Application uses a USB connection to a computer to synchronize data with a desktop BlackBerry Java Application. When the automatic wireless backup process runs on the BlackBerry Enterprise Server. the process saves BlackBerry Java® Application data with the user account settings and the other BlackBerry device data that backs up.4 Managing data Data synchronization Backing up and restoring data Code samples Data synchronization Research In Motion (RIM) does not provide tools or BlackBerry® Java® Applications for synchronizing data to remote data sources. wireless backup is active on the BlackBerry Enterprise Server. the BlackBerry Desktop Manager. and a desktop BlackBerry Java Application that can read data from the BlackBerry device using the BlackBerry Desktop Manager Plug-Ins adapter. A BlackBerry® Java® Application uses a USB connection to a computer and native USB protocols to synchronize data with a desktop application. See the BlackBerry Enterprise Server for Microsoft Exchange Feature and Technical Overview for more information about the BlackBerry Enterprise Server. See the BlackBerry Java Development Environment Fundamentals Guide for more information creating BlackBerry Java Applications for synchronizing data on a BlackBerry® device. A BlackBerry device user must manually start the synchronization process by running the BlackBerry Desktop Manager Plug-in. Types of data synchronization Synchronization type Wireless (BlackBerry® Enterprise Server) Description The automatic wireless backup process on a BlackBerry Enterprise Server is designed to back up data from the BlackBerry device to the BlackBerry Enterprise Server. Desktop-based (USB protocols) . This type of synchronization requires the use of the BlackBerry Desktop Synchronization APIs. which notifies the BlackBerry Java Application on the BlackBerry device to send the data to the desktop application. Wireless (XML data) Desktop-based (BlackBerry® Desktop Manager Plug-in) A BlackBerry® Java® Application uses XML APIs to generate and parse XML-formatted data to send and receive over a wireless connection.

getInstance(). create code that activates the synchronization process. ++i) { if (args[i]. Setup the BlackBerry® > Enterprise Server™ to back up the BlackBerry Java® Application data using automatic wireless backup. Right-click the project. 9. 3. public static void main(String[] args) { boolean startup = false. type init. } } if (startup) { //enable application for synchronization on startup SerialSyncManager. 5. } else { RestaurantsSync app = new RestaurantsSync().enableSynchronization(new RestaurantsSync()). } } The first time the BlackBerry device starts. Click OK. i<args. 4. and then click Properties. click Alternate CLDC Application Entry Point. Activate the synchronization process when the BlackBerry® device starts. Select the Auto-run on startup option. MIDlet applications do not support this task. 1. In the Project type drop-down list. create a project. 8. In the Arguments passed to field.length. Create a project that acts as an alternate entry point to the main BlackBerry® Java® Application. 6. click the project that starts the synchronization process. for (int i=0. Make sure the value you type in the Arguments passed to field matches the value in the startsWith argument in your BlackBerry Java Applications main method. the Alternate CLDC Application Entry Point project passes an argument to the BlackBerry Java® Application so that the BlackBerry Java Application registers only once. Click the Application tab.startsWith("init")) { startup = true. 2.enterEventDispatcher(). In the BlackBerry® Integrated Development Environment. 7. > In the main method. app. In the Alternate entry point for drop-down list. 84 .BlackBerry Java Development Environment Development Guide Backing up and restoring data Add support for backing up data over the wireless network Task Steps Implement the OTASyncCapable and CollectionEventSource interfaces. Select the System module option.

_schema. 85 .4: Managing data Task Steps Provide a BlackBerry® Java® > In your implementation of the OTASyncCapable interface. _schema.setDefaultRecordType(DEFAULT_RECORD_TYPE). KEY_FIELD_IDS).setKeyFieldIds(DEFAULT_RECORD_TYPE. in a SyncCollection. implement the getSchema()method Application with schema data public SyncCollectionSchema getSchema() for a SyncCollection.setKeyFieldIDs() method. Uniquely identify each record > Invoke the SyncCollectionSchema. private static final int[] KEY_FIELD_IDS = new int[] {FIELDTAG_FIRST_NAME. Invoke the SyncCollectionSchema. so it uses the default record type: private static final int DEFAULT_RECORD_TYPE = 1.setDefaultRecordType()method. } Uniquely identify each record > type in a SyncCollection. _schema = new SyncCollectionSchema(). FIELDTAG_LAST_NAME}. The following example shows only one record type. {// returns our schema return _schema.

} return collection. 1.getPersistentObject(PERSISTENT_KEY). collection ).setContents( _contacts ). Steps > To ensure the BlackBerry® Java® Application works with only one version of the SyncCollection. implement a static method that returns an instance of the SyncCollection. To provide the BlackBerry® Java® Application with access to the newest SyncCollection data from the PersistentStore. private PersistentObject _persist.commit(). _contacts = (Vector)_persist. Create a method to provide the BlackBerry Java Application with the newest SyncCollection data before a wireless data backup session begins.getRuntimeStore(). // The persistable object for the // The actual contacts. rs. } } Retrieve the SyncCollection from the PersistentStore. } 4. static OTABackupRestoreContactCollection getInstance() { RuntimeStore rs = RuntimeStore.get( AR_KEY ). _contacts = (Vector)_persist. synchronized( rs ) { OTABackupRestoreContactCollection collection = (OTABackupRestoreContactCollection)rs. } 86 . _persist = PersistentStore.getPersistentObject( PERSISTENT_KEY ). private static final long PERSISTENT_KEY = 0x266babf899b20b56L.BlackBerry Java Development Environment Development Guide Access a SyncCollection Task Retrieve an instance of the SyncCollection from the RunTimeStore. 3.put( AR_KEY.getPersistentObject() method using the ID of the SyncCollection. Create code to manage the case where the SyncCollection you retrieve from the PersistentStore is empty. invoke the PersistentStore. private Vector _contacts.getContents(). _persist. public void beginTransaction() { _persist = PersistentStore. if( _contacts == null ) { _contacts = new Vector().getContents(). 2. _persist. Store the returned data in a vector object. contacts. if( collection == null ) { collection = new OTABackupRestoreContactCollection().

Create a private vector object to store the collection of SyncCollection listeners for the BlackBerry Java Application. Implement the CollectionEventSource. object ). listener ).removeListener() method to remove a CollectionListener from the collection of SyncCollection listeners for the BlackBerry® Java® Application. i++ ) { CollectionListener cl = (CollectionListener)_listeners. cl.4: Managing data Notify the system when a SyncCollection changes Task Steps Use a collection listener to The system invokes CollectionEventSource. 1. wireless backup.fastAddListener( _listeners.elementRemoved(). listener ).elementAdded( this. When a CollectionListener is no longer required. } Remove a collection listener. using the ListenerUtilities. Notify the system when an element in a SyncCollection is replaced. private Vector _listeners.elementUpdated().elementAt( i ).elementAdded(): for( int i=0. > Invoke CollectionListener. > Invoke CollectionListener.addCollectionListener() to create a notify the system when a CollectionListener for each SyncCollection the BlackBerry®Java® Application makes available for SyncCollection changes. public void removeCollectionListener(Object listener) {_listeners = ListenerUtilities. making sure the method adds a CollectionListener to the vector. i<_listeners. } return true. 2.addCollectionListener() method. _listeners = new CloneableVector(). public void addCollectionListener(Object listener) { _listeners = ListenerUtilities. > Implement the CollectionEventSource. 87 . removeCollectionListener.removeListener( _listeners. > Invoke CollectionListener.removeCollectionListener()method. the system invokes CollectionEventSource. } Notify the system when an element is added to a SyncCollection.size(). } Notify the system when an element is removed from a SyncCollection.

commit(). public void endTransaction() { _persist. } Access a specific SyncObject. SyncObject[] contactArray = new SyncObject[_contacts. --i) { contactArray[i] = (SyncObject)_contacts.setContents(_contacts).size() . > Implement the getSyncObject() method. save the newest SyncCollection data. 88 . } Add a SyncObject to the SyncCollection. } See “Code sample: Using a SyncCollection to back up data over the wireless network” on page 91 for more information.1.size() . if ( so. > Create a method that adds SyncObjects to the PersistentStore object.elementAt(i). } Save a SyncCollection. i >= 0. for (int i = _contacts. i >= 0. public SyncObject getSyncObject(int uid) { for (int i = _contacts.1. Before a wireless backup session ends. Steps > Implement the getSyncObjects() method. --i) { SyncObject so = (SyncObject)_contacts. } return null.BlackBerry Java Development Environment Development Guide Using SyncObjects Task Retrieve SyncObjects from the SyncCollection. > Invoke the setContents() and commit()methods. _contacts. public SyncObject[] getSyncObjects() {//Retrieve the contact data.getUID() == uid ) return so.size()]. } return contactArray. public boolean addSyncObject(SyncObject object) { // Add a contact to the PersistentStore object. _persist.elementAt(i).addElement(object). using the _uid parameter to retrieve a specific SyncObject.

create a constructor that accepts a unique ID as a parameter and sets the _uid variable to this value.length. > In the persistable class.SyncCollection. synchronized objects. private static final class RestaurantInfo implements Persistable. public class RestaurantsSync extends UiApplication implements RestaurantsSyncResource. ++i) { _elements[i] = "". > In the persistable class. depending on the design of the BlackBerry Java Application. public RestaurantInfo(int uid) { _elements = new String[4]. for (int i = 0. SyncObject { Create a unique ID for a synchronization object.4: Managing data Add support for backing up data with the BlackBerry Desktop Software Task Steps Let your BlackBerry® Java® Implement the SyncCollection and SyncConverter interfaces by the same class or by separate Application maintain a collection of classes. when creating a SyncObject. } _uid = uid. } 89 . private int _uid. producing and > Change the main class for the BlackBerry Java Application to implement the SyncCollection processing valid synchronization data and SyncConverter interfaces. public int getUID() { return _uid. SyncConverter Let persistable objects be synchronization objects. i < _elements. Let your main BlackBerry® Java® Application retrieve the unique ID of the synchronization object. implement the getUID() method to return a unique ID for synchronization operations. > Modifiy a class that implements the Persistable interface to implement the SyncObject interface. create an instance variable for storing a unique ID for synchronization operations. In the persistable class. } Enable your main BlackBerry® Java® > Application to create a synchronization object using a unique ID.

Click the Application tab. } } if (startup) { //enable the BlackBerry Java Application for synchronization on startup SerialSyncManager.length. click the project that implements synchronization. } } Create a project that acts as an alternate entry point to the main BlackBerry® Java® Application. 5. 3. Make sure the value you type in the Arguments passed to field matches the value in the startsWith argument in the main method of the BlackBerry Java Application. In the BlackBerry® Integrated Development Environment. 9. 1. 8.BlackBerry Java Development Environment Development Guide Activate synchronization when the BlackBerry device starts Task Activate synchronization when the BlackBerry® device starts. If the BlackBerry Java Application is a MIDlet. Right-click the project. ++i) { if (args[i]. } else { RestaurantsSync app = new RestaurantsSync().enableSynchronization(new RestaurantsSync()). Steps The first time the BlackBerry device starts. and then click Properties. type init. In the Alternate entry point for drop-down list. See “Code sample: Letting the BlackBerry Desktop Software to back up and restore BlackBerry Java Application data” on page 96 for more information. arguments cannot pass to the BlackBerry Java Application when the BlackBerry device starts. 2. In the Project type drop-down list. In the Arguments passed to field. 4. Select the System module option. app. create code that activates the synchronization process. the Alternate CLDC Application Entry Point project passes an argument to the BlackBerry Java® Application so that the BlackBerry Java Application registers only once. Click OK. public static void main(String[] args) { boolean startup = false. 6. create a project. for (int i=0. click Alternate CLDC Application Entry Point. i<args.enterEventDispatcher(). 7. > In the main method of the BlackBerry Java Application.startsWith("init")) { startup = true.getInstance(). Select the Auto-run on startup option. 90 .

Basically a serially syncable collection * with few added interfaces.i18n.*. the only) record type private static final int[] KEY_FIELD_IDS = new int[] { know which fields uniquely define a record FIELDTAG_FIRST_NAME. import import import import import import import java.util.samples.java * * AUTO_COPYRIGHT_SUB_TAG */ package com.device. */ class OTABackupRestoreContactCollection implements SyncConverter.synchronization.*.rim.device.java /* * OTABackupRestoreContactCollection.*.api.device. private static final int FIELDTAG_LAST_NAME = 2. net. // the persistable object for the contacts // the actual contacts // listeners to generate events when contacts // lets us know about the data we are backing private static final int FIELDTAG_FIRST_NAME = 1. SyncCollection. net.*. net. net.rim.rim. java. /** * A collection enabled for OTA backup/restore.rim.samples.OTABackupRestoreContactCollection private private private are added private up PersistentObject _persist. // the id for the default (and // key fields . Vector _contacts.device. private static final int DEFAULT_RECORD_TYPE = 1.io. FIELDTAG_LAST_NAME }.rim.device.rim.otabackuprestoredemo. private static final int FIELDTAG_EMAIL_ADDRESS = 3.api.api._persist private static final long AR_KEY = 0xef780e08b3a7cf07L. net.util.collection. // com.otabackuprestoredemo.api. CollectionEventSource { private static final long PERSISTENT_KEY = 0x266babf899b20b56L.device.rim.device.OTABackupRestoreContactCollection. // com.samples.*.*.system.api.lets the server 91 .*. SyncCollectionSchema _schema. Vector _listeners.otabackuprestoredemo.device.rim. OTASyncCapable.4: Managing data Code samples Code sample: Using a SyncCollection to back up data over the wireless network Example: OTABackupRestoreContactCollection.

getFirst().write(first. if( collection == null ) { collection = new OTABackupRestoreContactCollection().getContents(). String last = ((ContactData)object). DataBuffer buffer.put( AR_KEY. _schema. //in compliance with desktop sync format buffer.getPersistentObject( PERSISTENT_KEY ). _persist. rs. KEY_FIELD_IDS). _schema.writeByte(0).length()+1). buffer. } _listeners = new CloneableVector(). buffer.commit().getBytes()). String email = ((ContactData)object). } static OTABackupRestoreContactCollection getInstance() { RuntimeStore rs = RuntimeStore. synchronized( rs ) { OTABackupRestoreContactCollection collection = (OTABackupRestoreContactCollection)rs. _persist.getBytes()). buffer. collection ). buffer.writeByte(FIELDTAG_FIRST_NAME). buffer. int version) { if (version == getSyncVersion()) { if (object instanceof ContactData) { String first = ((ContactData)object).setKeyFieldIds(DEFAULT_RECORD_TYPE. 92 .setDefaultRecordType(DEFAULT_RECORD_TYPE).writeByte(FIELDTAG_LAST_NAME).writeByte(0).getEmail(). } return collection. if( _contacts == null ) { _contacts = new Vector().writeShort(first.getLast().BlackBerry Java Development Environment Development Guide private OTABackupRestoreContactCollection() { _persist = PersistentStore. // set up the schema for the collection _schema = new SyncCollectionSchema(). buffer. _contacts = (Vector)_persist.length()+1).setContents( _contacts ). buffer. } } //SyncConverter methods---------public boolean convert(SyncObject object.getRuntimeStore().writeShort(last.write(last.get( AR_KEY ).

} //SyncCollection methods---------public boolean addSyncObject(SyncObject object) { // add a contact to the persistent store _contacts.readFully(bytes).readFully(bytes).setContents( _contacts ). contact. break. case FIELDTAG_LAST_NAME: data. _persist. } } return contact. byte[] bytes = new byte[length]. switch (data. //trim null-terminator contact.available() > 0) { int length = data.addElement(object).writeShort(email.println(e.4: Managing data buffer.readFully(bytes). } return null. int version.setLast(new String(bytes).readByte()) { case FIELDTAG_FIRST_NAME: data.readShort().setFirst(new String(bytes). } public SyncObject convert(DataBuffer data.setEmail(new String(bytes).readFully(bytes).trim()). buffer. _persist. 93 . buffer. return true.toString()). break.write(email. //other fields not supported break.commit(). break. buffer. contact. } } return false. int UID) { try { ContactData contact = new ContactData(UID).length()+1). } catch (EOFException e) { System. default: data.trim()). while(data.getBytes()). case FIELDTAG_EMAIL_ADDRESS: data.trim()).writeByte(0).err.writeByte(FIELDTAG_EMAIL_ADDRESS).

this method would look much the same as addSyncObject } public boolean removeAllSyncObjects() { return false. cl. } public boolean updateSyncObject(SyncObject oldObject. //na .size()].elementAt(i). //na } public void setSyncObjectDirty(SyncObject object) { //na } public void clearSyncObjectDirty(SyncObject object) { //na 94 . SyncObject newObject) { return false.size() .this method would look much the same as addSyncObject } public boolean removeSyncObject(SyncObject object) { return false. } return true. } return contactArray. --i) { contactArray[i] = (SyncObject)_contacts. object ). //na } public SyncObject[] getSyncObjects() { SyncObject[] contactArray = new SyncObject[_contacts. i++ ) { CollectionListener cl = (CollectionListener)_listeners. i<_listeners.BlackBerry Java Development Environment Development Guide // we want to let any collection listeners we have that the collection has been changed for( int i=0.size() .elementAt(i).1.1.getUID() == uid ) return so. i >= 0. } return null. } public SyncObject getSyncObject(int uid) { for (int i = _contacts. //na . --i) { SyncObject so = (SyncObject)_contacts.size(). if ( so.elementAt( i ). i >= 0. for (int i = _contacts.elementAdded( this. } public boolean isSyncObjectDirty(SyncObject object) { return false.

} public String getSyncName() { return “OTABackupRestoreContacts”.size().4: Managing data } public int getSyncObjectCount() { _persist = PersistentStore. _contacts = (Vector)_persist.setContents(_contacts).fastAddListener( _listeners.getContents().getPersistentObject(PERSISTENT_KEY).commit(). listener ).getPersistentObject(PERSISTENT_KEY).getContents(). _persist. _contacts = (Vector)_persist. } public void removeCollectionListener(Object listener) { _listeners = ListenerUtilities. } public String getSyncName(Locale locale) { return null. } public void beginTransaction() { _persist = PersistentStore. } 95 . } //CollectionEventSource methods -------------------------------------------public void addCollectionListener(Object listener) { _listeners = ListenerUtilities. } public int getSyncVersion() { return 1. } //OTASyncCapable methods --------------------------------------------------public SyncCollectionSchema getSchema() { // returns our schema return _schema. return _contacts.removeListener( _listeners. } public void endTransaction() { _persist. listener ). } public SyncConverter getSyncConverter() { return this.

device. final int FIELDTAG_SPECIALTY = 4.java /** * RestaurantsSync.*. static static static static static static static PersistentObject store.synchronization.api.rim.rim. final int FIELDTAG_PHONE = 2. } } Code sample: Letting the BlackBerry Desktop Software to back up and restore BlackBerry Java Application data Example: RestaurantsSync.*.ui.system. ResourceBundle _resources.rim. private static RestaurantsSync _instance. public class RestaurantsSync extends UiApplication implements RestaurantsSyncResource. final int FIELDTAG_ADDRESS = 3.api. 96 . } public ContactData contactAt( int index ) { return (ContactData)_contacts. net. EditField phonefield. AutoTextEditField addressfield. net.rim. SyncCollection.elementAt( index ).component.rim. net.size().api.ui.java * Copyright (C) 2001-2005 Research In Motion Limited.*. SyncConverter { private static final long KEY = 0xdec6a67096f833cL.resource.io.rim.*.device.*. com. net.container.*.rim.rim.*.rim. Vector _data.samples. EditField specialtyfield.device.util.device.util.*.i18n. All rights reserved. java. private private private private private private private private private private private AutoTextEditField namefield.api.docs.api. net.samples. import import import import import import import import import import java.restaurantssync. net. */ package com. final int FIELDTAG_NAME = 1.device.device.*.api.*.docs.ui.api. net.BlackBerry Java Development Environment Development Guide public int size() { return _contacts.device.

} }. specialtyfield.addElement(info). addressfield. synchronized(store) { store.setText(info.getText()).getContents(). info.setText(info. info. 10) { public void run() { RestaurantInfo info = new RestaurantInfo().getText()). namefield. static { _resources = ResourceBundle.lastElement().getPersistentObject(KEY). store.setContents( _data ). } } } public static void main(String[] args) { boolean startup = false.setText(null). for (int i=0. MENUITEM_SAVE.setElement(RestaurantInfo. if (!_data. addressfield.NAME)).NAME. specialtyfield.4: Managing data private MenuItem saveItem = new MenuItem(_resources.getElement(RestaurantInfo. info. namefield. MENUITEM_GET. namefield.BUNDLE_NAME).getContents().setElement(RestaurantInfo.length.getElement( RestaurantInfo.setText(info. info. ++i) { if (args[i].getElement(RestaurantInfo.ADDRESS)).setText(info.setElement(RestaurantInfo. phonefield.PHONE.commit(). addressfield. 11) { public void run() { synchronized(store) { _data = (Vector)store.setElement(RestaurantInfo. phonefield.getBundle(RestaurantsSyncResource. synchronized (store) { _data = (Vector)store. 97 . specialtyfield. RestaurantsSyncResource.getText()).setContents(_data).inform(_resources. } } } }.getString(APP_SUCCESS)).startsWith(“init”)) { startup = true. phonefield.getElement(RestaurantInfo. 110.setText(null).ADDRESS. _data.BUNDLE_ID. if ( _data == null ) { _data = new Vector(). store = PersistentStore.commit().isEmpty()) { RestaurantInfo info = (RestaurantInfo)_data. private MenuItem getItem = new MenuItem(_resources.PHONE)). store.SPECIALTY)). } Dialog.SPECIALTY. store.setText(““).setText(““). i<args. 110.getText()).

} public void setElement(int id. } else { RestaurantsSync app = new RestaurantsSync(). public static final int PHONE = 2. i < _elements.getInstance(). } private static final class RestaurantInfo implements Persistable. public int getUID() { return _uid. String value) { _elements[id] = value. app. } return _instance. } } public static RestaurantsSync getInstance() { if (_instance == null) { _instance = new RestaurantsSync(). ++i) { _elements[i] = ““. int UID) { try { 98 .length. public static final int ADDRESS = 1.getInstance()). for (int i = 0. for ( int i = 0.enterEventDispatcher().length. SyncObject { private String[] _elements.enableSynchronization( RestaurantsSync. } } // SyncConverter methods. int version. ++i) { _elements[i] = ““. } public String getElement(int id) { return _elements[id]. public SyncObject convert(DataBuffer data. SyncManager. i < _elements.BlackBerry Java Development Environment Development Guide } } if (startup) { // Enable application for synchronization on startup. } } public RestaurantInfo(int uid) { _elements = new String[4]. public static final int SPECIALTY = 3. private int _uid. } public RestaurantInfo() { _elements = new String[4]. public static final int NAME = 0. } _uid = uid. // Data.

break. String phone = ((RestaurantInfo)object). } } return info. info.readFully(bytes).write(phone.readByte()) { case FIELDTAG_NAME: data. String address = ((RestaurantInfo)object). int version) { if (version == getSyncVersion()) { if (object instanceof RestaurantInfo ) { String name = ((RestaurantInfo)object).println(e.toString()).getElement( RestaurantInfo.setElement(RestaurantInfo. buffer.ADDRESS). break.setElement(RestaurantInfo. buffer. case FIELDTAG_PHONE: data. buffer. info. info. byte[] bytes = new byte[length].ADDRESS.writeShort(phone.setElement(RestaurantInfo.readShort(). new String(bytes). buffer.writeByte(0).write(name. } catch (EOFException e) { System. break.trim()). break.trim()). new String(bytes).readFully(bytes). new String(bytes).getElement( RestaurantInfo.readFully(bytes). case FIELDTAG_ADDRESS: data.writeShort(name.readFully(bytes). switch (data.trim()).SPECIALTY). String specialty = ((RestaurantInfo)object). while(data. DataBuffer buffer.trim()).PHONE). 99 . new String(bytes). //trim null-terminator info.getBytes()). break.writeByte(FIELDTAG_PHONE).readFully(bytes).4: Managing data RestaurantInfo info = new RestaurantInfo(UID).SPECIALTY.length()+1).available() > 0) { int length = data.NAME.err. } return null.NAME).getBytes()).getElement( RestaurantInfo. } public boolean convert(SyncObject object.setElement(RestaurantInfo.getElement( RestaurantInfo. case FIELDTAG_SPECIALTY: data. buffer. buffer.PHONE. default: data. buffer.writeByte(FIELDTAG_NAME).writeByte(0). buffer.length()+1).

} } return false. } public SyncObject[] getSyncObjects() { SyncObject[] array = new SyncObject[_data. _data = (Vector)store.getBytes()). if (so. _data = (Vector)store. buffer.getContents().getContents(). return _data.size()].write(address. } public void beginTransaction() { store = PersistentStore.size() . return true.writeByte(0). i>= 0.writeShort(specialty.write(specialty.writeByte(0).size().length()+1). --i) { SyncObject so = (SyncObject)_data.commit(). store. } public String getSyncName() { return “Restaurant Synchronization Demo”.size() -1.1. } public void endTransaction() { store.length()+1).writeByte(FIELDTAG_ADDRESS). } public SyncObject getSyncObject(int uid) { for (int i = _data. buffer. } return null.elementAt(i). buffer.getUID() == uid ) return so. } return array. } public SyncConverter getSyncConverter() { return this. buffer.writeShort(address. buffer. } 100 .getPersistentObject(KEY). --i) { array[i] = (SyncObject)_data. } public String getSyncName(Locale locale) { return getSyncName().BlackBerry Java Development Environment Development Guide buffer. buffer.getPersistentObject(KEY). i >= 0. } public int getSyncObjectCount() { store = PersistentStore.getBytes()).elementAt(i). for (int i = _data.setContents(_data). buffer.writeByte(FIELDTAG_SPECIALTY).

add(phonefield). addressfield = new AutoTextEditField( _resources.getString(APPLICATION_TITLE))).getString(FIELD_NAME).makeMenu(menu. mainScreen. ““.MAX_VALUE.add(addressfield). specialtyfield = new EditField(_resources. } public boolean isSyncObjectDirty(SyncObject object) { return false.getString(FIELD_SPECIALTY). int instance ) { menu.MAX_VALUE. return true. super.setTitle(new LabelField( _resources.add(namefield). } public boolean removeAllSyncObjects() { _data. Integer.FILTER_PHONE). ““). mainScreen. menu. } private final class RestaurantsMainScreen extends MainScreen { protected void makeMenu( Menu menu.removeAllElements(). } public boolean removeSyncObject(SyncObject object) { return false. } public boolean addSyncObject(SyncObject object) { _data. } public RestaurantsSync() { MainScreen mainScreen = new RestaurantsMainScreen(). BasicEditField. phonefield = new EditField( _resources. } public void close() { 101 . ““. namefield = new AutoTextEditField(_resources. BasicEditField. mainScreen.add(specialtyfield).FILTER_DEFAULT). instance). mainScreen.getString(FIELD_ADDRESS).getString(FIELD_PHONE).addElement(object).add(saveItem). mainScreen. pushScreen(mainScreen).add(getItem). } public void setSyncObjectDirty(SyncObject object) { } public boolean updateSyncObject(SyncObject oldObject. Integer. } public void clearSyncObjectDirty(SyncObject object) { // Not applicable.4: Managing data public int getSyncVersion() { return 1. return true. SyncObject newObject) { return false. ““).

BlackBerry Java Development Environment Development Guide Dialog.close(). super.alert(_resources. } } } 102 .getString(APP_EXIT)).

2. The 3GPP USIM application is listed as application one on the SIM card and uses PIN IDs 0x01 and 0x81.1 or greater to create a BlackBerry Java Application that uses the APDU and JCRMI APIs. The BlackBerry Java Applications are classified as applications one through eight. to call the methods of an application on a SIM card. The APDU API enables BlackBerry Java Applications on a BlackBerry device to use the APDU protocol to communicate with an application on a SIM card. PIN ID restrictions for JSR177 on a BlackBerry device You can load up to eight applications onto a SIM card. .org/en/home/ index. BlackBerry Java Applications that implement JRS177 can only use the following PIN ID ranges: 0x02 to 0x08. where 1 <= i <= 8. see http://jcp.5 Implementing security and trust services Connecting to an application on a SIM card Connecting to an application on a SIM card For BlackBerry® devices that operate on EDGE networks. and 0x82 to 0x88. For more information on creating BlackBerry Java Applications that support JSR177. The JCRMI API enables BlackBerry Java Applications on a BlackBerry device to use the Java Card Remote Method Invocation protocol to communicate with a BlackBerry Java Application on a SIM card. A BlackBerry Java Application only requires PIN IDs for PIN related functions in JSR177 such as EnterPin. you can create BlackBerry Java® Applications that use the APDU and JCRMI APIs defined by JSR 177. and ChangePin. Note that PIN1 for application i is defined as 0x0i. You must use the BlackBerry® Java® Development Environment Version 4. You can associate two PIN IDs with each BlackBerry Java Application. UnblockPin. EnablePin. and PIN2 for the same application is defined as 0x8i.

UserException. public class Wallet_Stub extends RemoteStub implements Remote.Short(m)}).RemoteException e) { throw e. e).RemoteException("undeclared checked exception".UserException e) { throw e.rmi. } catch (java. Create a stub class that extends the javax. new java.rmi. public interface Wallet extends Remote { public short getBalance() throws RemoteException.Remote interface and includes the methods the BlackBerry® Java® Application will call on the remote object.RuntimeException e) { throw e. } catch (java. } } 104 . e).lang. UserException.lang. } catch (java. UserException { try { ref. } } public void debit(short m) throws RemoteException. public void credit(short m) throws RemoteException.Exception e) { throw new java.Remote interface.rmi. UserException. Wallet { public short getBalance() throws RemoteException.lang.RuntimeException e) { throw e.Exception e) { throw new java.framework.} 2.RemoteException("undeclared checked exception".RemoteStub class and implements the java.Short) $result). UserException.microedition. public void debit(short m) throws RemoteException.lang. public byte[] getAccountNumber() throws RemoteException. Create an interface that extends the java. } catch (java.rmi. } catch (java.jcrmi.invoke("debit(S)V".RemoteException e) { throw e. UserException { try { Object $result= ref.shortValue().Object[] {new java.BlackBerry Java Development Environment Development Guide Use JCRMI to communicate with an object on a SIM card 1. } catch (javacard.UserException e) { throw e. } catch (java.lang.rmi. return ((java.framework.rmi.lang. null).invoke("getBalance()S". } catch (javacard.lang.

3.Exception e) { throw new java.Object[] {new java.67.RemoteException("undeclared checked exception". } catch (javacard. } catch (java. } 105 . } catch (java. } catch (java.invoke("getAccountNumber()[B".UserException e) { throw e. connection = (JavaCardRMIConnection) Connector. e). new java. } catch (java. Create BlackBerry Java Application code that opens a connection to and calls methods on the remote object. null).7. e).invoke("credit(S)V".Short(m)}). } catch (java.5: Implementing security and trust services public void credit(short m) throws RemoteException.lang.RuntimeException e) { throw e.open("jcrmi:0. } catch (javacard.rmi. UserException { try { Object $result=ref.4. UserException { try { ref.rmi.lang. } } public byte[] getAccountNumber() throws RemoteException.UserException e) { throw e. return (byte[])$result.0.rmi.lang.0. JavaCardRMIConnection connection = null. if(connection==null){ fail("Null connection returned"). } } } 3.framework.lang.RemoteException e) { throw e.RuntimeException e) { throw e.1F.lang.AID=A0.RemoteException e) { throw e.rmi.RemoteException("undeclared checked exception".Exception e) { throw new java.framework.3").2C.lang. } catch (java.

(byte)0x24. Send and receive APDU messages.1F. acn = (APDUConnection)Connector.open() using the locator string and casting the returned object as an APDUConnection object. 1.3.0. 2.0. storing the return value in a byte array. 106 .open(testURL). Create a byte array containing a command APDU. acn. Steps 1. String testURL = "apdu:0. Task Open an APDU connection. Invoke exchangeAPDU() using the byte array command. APDUConnection acn = null. (byte)0x64}.close().close(). (byte)0x04.BlackBerry Java Development Environment Development Guide Use APDU to communicate with an object on a SIM card You can create a BlackBerry® Java® Application that uses the APDU protocol to send and receive message information between a BlackBerry Java Application and an application on a SIM card.7. > Invoke APDUConnection.2C. Close the APDU connection.4.67. 2. Invoke Connector.3". byte[] command = {(byte)0x00.exchangeAPDU(command). See the API Reference for more information on using the APDUConnection interface.target=A0. Create a locator string that begins with apdu and specifies the slot number and the card application identifier. byte[] responseAPDU = acn.

Reduce the number of objects To use the BlackBerry® Integrated Development Environment to identify unnecessary objects. 4. 7. Open the Objects window and click Snapshot. View multiple snapshots in the Objects window. Description The free flash memory threshold depends on the amount of free RAM in the system. 2. The free flash memory threshold varies between 400 KB and 800 KB. Open the Objects window. 6. complete the following steps: 1. Run the BlackBerry Java® Application to the first breakpoint. Open the BlackBerry IDE. 9. Click Compare to Snapshot. 8. Run the BlackBerry Java Application to the second breakpoint. . 5. Place two breakpoints in the code surrounding an area of high object creation.6 Managing memory Invoking garbage collection Reduce the number of objects Managing low memory Invoking garbage collection See the Garbage Collection in the BlackBerry® Java® Development Environment whitepaper and the BlackBerry Java Development Environment Fundamentals Guide for more information about garbage collection operations. 3. Managing low memory LMM triggers The following conditions can cause the LMM to free memory resources: Condition Available flash memory falls below acceptable thresholds. Determine which objects can be removed.

Enable the BlackBerry Java Application to register the LowMemoryListener with the LMM when the BlackBerry Java Application starts for the first time. enable the BlackBerry® Java® Application to remove stale data. Manage low priority events. Delete the object from its data structure. such as very old email messages or old calendar appointments.BlackBerry Java Development Environment Development Guide Condition Low number of persistent object handles on a BlackBerry® device. In an implementation of freeStaleObject(). Inform the BlackBerry® JVM that it can now remove the object. > Implement the freeStaleObject(int) method of the LowMemoryListener interface. Use the LMM Task Register your BlackBerry® Java® Application with the LMM. remove references to the persistent object. implement the LowMemoryListener interface. Manage events that the LowMemoryListener receives. The implementation of freeStaleObject() method should return true if persistent data is released. or return false otherwise. In an implementation of freeStaleObject(). enable the BlackBerry® Java® Application to release transitory variables and any variables that are currently not necessary for complete functionality.markAsRecoverable(). invoke LowMemoryManager. removing all stale objects. Register the listener only once. The BlackBerry® device system invokes the implementation of freeStaleObject(int) when device memory is low. Commit changes to data collections. > > Free resources manually. > > In the BlackBerry® Java® Application. Manage medium priority events. In an implementation of freeStaleObject(). Steps 1. 2. perform the following actions: > Invoke freeStaleObject(int) from the BlackBerry Java® Application. Free persistent objects Task Remove references to the object. 108 . enable the BlackBerry® Java® Application to remove objects in the BlackBerry Java Application on a Least Recently Used basis.. such as cached data. Manage high priority events. In the BlackBerry Java Application. Low number of object handles on a BlackBerry® device Description The number of persistent object handles falls below 1000. The LMM seldom specifies a priority higher than low priority. To manually free resources. invoke PersistentObject. Steps 1. The number of object handles falls below 1000. 2. In an implementation of freeStaleObject().commit(). > In an implementation of freeStaleObject().

api. Verify that the BlackBerry device is in network coverage > Use the CoverageInfo class and CoverageStatusListener interface of the net. You can design your BlackBerry Java Application to rely on the default gateway that is available to the BlackBerry device user. or you can customize your code to explicitly select a preferred gateway. a BlackBerry Java Application can use one of two wireless gateways to proxy the connection to the Internet or the corporate intranet. The BlackBerry device must be registered with a wireless network for this method to work.device.system package to make sure that the BlackBerry® device is in network coverage.out. HTTPS. System.getCurrentNetworkName(). Working with network information Determine the name of the wireless network that the BlackBerry device is registered with > Invoke RadioInfo. When establishing the connection over the cellular network.getCurrentNetworkName().7 Creating connections Fetching data using HTTP or TCP sockets Working with network information Datagram connections Using port connections Code samples Fetching data using HTTP or TCP sockets BlackBerry® Java® Applications for BlackBerry devices can use standard HTTP. and TCP socket protocols to establish connections over the wireless network. .rim. String networkName = RadioInfo.println (“Network Name: “ + networkName ).

including traffic destined for the Internet. 110 . BlackBerry Java Applications can communicate with application servers and web servers that reside on the corporate intranet. Using the BlackBerry Enterprise Server as an intranet gateway Enterprise customers host the BlackBerry® Enterprise Server behind their corporate firewall to enable access from BlackBerry devices to the corporate intranet. Using the wireless service provider's Internet gateway BlackBerry® Java® Applications for BlackBerry devices can connect to the Internet using the Internet gateway that the wireless service provider provides. If your BlackBerry Java Application connects to the Internet rather than to the corporate intranet. you can also use either the BlackBerry Internet Service or the Internet gateway of the wireless server provider to manage connections. and use the wireless service provider’s Internet gateway as a default connection type if the BlackBerry Internet Service is not available. However.0 Part 1: Understanding TCP and HTTP transport options for Java applications for BlackBerry for more information on managing wireless connectivity and how to effectively use each of the gateways. and you are targeting non-enterprise customers. which makes the network request to the Internet through the corporate firewall. However. see the whitepaper Managing Wireless Data Transport in the BlackBerry Solution v4. you may find it useful to use the BlackBerry Internet Service. When you use the BlackBerry Enterprise Server as an intranet gateway. testing your BlackBerry Java Application against the different Internet gateways and achieving a consistent and reliable experience can be challenging. you might be able to use the BlackBerry Enterprise Server that belongs to the customer as a gateway as well. The BlackBerry Mobile Data System™ component of the BlackBerry Enterprise Server includes the BlackBerry MDS™ Services. In these scenarios. which provides an HTTP and TCP/IP proxy service to let third-party BlackBerry Java® Applications use it as a secure gateway for managing HTTP and TCP/IP connections to the intranet. this approach can often yield good results. all traffic between your BlackBerry Java Application and the BlackBerry Enterprise Server is automatically encrypted using AES or triple DES encryption. Some operators also provide a WAP gateway that lets HTTP connections occur over the WAP protocol. network requests travel behind the corporate firewall to the BlackBerry Enterprise Server. Most wireless service providers provide their own Internet gateway that offers direct TCP/IP connectivity to the Internet. BlackBerry Java Applications for BlackBerry devices can use either of these gateways to establish connections to the Internet. If your BlackBerry Java Application connects to the Internet. If you write your BlackBerry Java Application for BlackBerry device users who are on a specific wireless network.BlackBerry Java Development Environment Development Guide Explicitly selecting a gateway Set up your BlackBerry® Java® Application to use the preferred gateway for a connection and to use the default gateway only when the preferred gateway is not available. Because the BlackBerry Enterprise Server resides behind the corporate firewall and provides inherent data encryption. enterprise customers can set an IT policy to enforce that the BlackBerry Enterprise Server is the gateway for all wireless network traffic. In the Technical Knowledge Center on the BlackBerry Developer Zone. In this case. if you write your BlackBerry Java Application for BlackBerry device users on a variety of wireless networks.

system package to make sure that the BlackBerry device is in network coverage.com/myContent". 2. conn.setRequestMethod(HttpConnection. Cast the returned object as an HttpConnection or a StreamConnection object.rim. Send and receive data. 1. InputStream in = conn. Set header fields. conn = (HttpConnection)Connector. 111 .setRequestMethod(). Invoke openInputStream() and openOutputStream() on the HTTPConnection. Invoke getRequestProperty() on the HttpConnection. Steps > Use the CoverageInfo class and CoverageStatusListener interface of the net. HttpConnection conn = null.openOutputStream(). verify that the BlackBerry® device is in network coverage. Retrieve header fields.open(). String URL = "http://www.setRequestProperty("User-Agent".myServer.device.POST). Set the HTTP request method (GET or POST).1"). See “Code sample: Using an HTTP connection to retrieve data” on page 120 for more information. Open an HTTP connection. specifying http as the protocol.openInputStream().getRequestProperty("Content-Language").7: Creating connections Use HTTP connections Task Before opening an HTTP connection.open(URL). Invoke Connector. > > > > Invoke HttpConnection.2. "BlackBerry/3. Invoke setRequestProperty() on the HttpConnection.api. String lang = conn. OutputStream out = conn. conn.

2. UiApplication.txt ")."Unauthorized Access:\n Do you wish to log in?"). "Basic " + new String(encoded)). Determine the status of the HTTP connection.getUiApplication(). Invoke HttpConnection. using the HTTP location of the protected resource. s.api. verify that the BlackBerry® device is in network coverage. HttpConnection httpConn = (HttpConnection)s.open("http://mysite. 3. false. httpConn = (HttpConnection)s. //Close the connection. switch (status) case (HttpConnection.invokeAndWait(new Runnable()) { public void run() { dialogResponse = Dialog. Retrieve login information from a BlackBerry® device user.ask. 2. } } Process the response of the BlackBerry® device user.txt"). httpConn.encode(login. > Open a new HTTPConnection and add the authorization header by invoking HTTPConnection. byte[] encoded = Base64OutputStream. 2. Create a run()method and within it implement a dialog object to ask the BlackBerry device user for login information.close(). 0. Steps > Use the CoverageInfo class and CoverageStatusListener interface of the net. Create code that manages an unauthorized HTTP connection attempt. Invoke Connector.open(). false).open("http:// mysite. StreamConnection s = (StreamConnection)Connector. Use the BlackBerry® device user login information to access the protected resource. Open an HTTP connection.rim. > 1. Cast and store the StreamConnection object as an HTTPConnection object. s = (StreamConnection)Connector. Retrieve the login information and close the current connection. (Dialog.D_YES_NO. Encode the login information.getResponseCode().YES) {String login = "username:password".device.getResponseCode().length().com/myProtectedFile. 1. Create code that manages a Yes dialog response.getResponseCode().BlackBerry Java Development Environment Development Guide Use HTTP authentication Task Before opening an HTTP connection. 3. Cast and store the returned object as a StreamConnection.setRequestProperty("Authorization".getBytes(). if (dialogResponse == Dialog.HTTP_UNAUTHORIZED).system package to make sure that the BlackBerry device is in network coverage. int status = httpConn.setRequestProperty()using the encoded login information. int status = httpConn.com/ myProtectedFile. login. 1. 112 .

"Unauthorized Access:\n Do you wish to log in?").D_YES_NO. //Retrieve the login information from somewhere.open("http://mysite.7: Creating connections Code fragment: Using HTTP authentication to connect to a protected internet resource Example: Using HTTP authentication to connect to a protected Internet resource HttpConnection httpConn = null.txt"). httpConn = (HttpConnection)s. try { s = (StreamConnection)Connector. //A login and password is required. //Download and process data.ask (Dialog.getResponseCode().HTTP_OK): //Connection is 200 OK. //Close the connection. switch (status) { case (HttpConnection. //You could prompt the user for this information or //retrieve this from elsewhere if it is saved within //your application. case (HttpConnection. UiApplication. break.getUiApplication(). StreamConnection s = null. 113 . but //we ask the user if they want to log-in.invokeAndWait(new Runnable() { public void run() { dialogResponse = Dialog. if (dialogResponse == Dialog.YES) { String login = "username:password".com/myProtectedFile. //Login information is hard coded here for brevity. int dialogResponse.HTTP_UNAUTHORIZED): //Connection is 401 UnAuthorized. } }). while(keepGoing) { int status = httpConn. boolean keepGoing = true. keepGoing = false.

keepGoing = false. } } //Close the connection. //Handle failed connection. s.setRequestProperty("Authorization". 0.encode(login. break.com/myProtectedFile. httpConn = (HttpConnection)s.open("http://mysite. } break. } catch (IOException e) { //Handle the exception. "Basic " + new String(encoded)). false. //Add the authorized header.close(). httpConn.txt "). false). default: //The connection failed for some other reason.length(). login. //Encode the login information in Base64 format. } else { //Handle failed connection.close().BlackBerry Java Development Environment Development Guide s. //Open a new connection. } 114 .getBytes(). byte[] encoded = Base64OutputStream. s = (StreamConnection)Connector. keepGoing = false.

HttpsConnection stream = (HttpsConnection)Connector. Open an HTTPS connection. If you do not specify the optional deviceside parameter. BlackBerry 7510. If BlackBerry MDS Services is not available. Task Before opening a socket connection. Cast the returned object as an HttpsConnection object. you will not be able to use end-to-end TLS. BlackBerry 7520.EndToEndDesired"). the deviceside parameter will specify whether or not the connection uses BlackBerry® MDS Services [(deviceside=false)] or direct TCP [(deviceside=true)].rim.open(): • Specify that an end-to-end HTTPS connection must be used from the BlackBerry® device to the target server: EndToEndRequired.device. Use socket connections Although you can implement HTTP over a socket connection.open(). On all other BlackBerry devices.rim.device. you should use an HTTP connection for the following reasons: • • Socket connections do not support BlackBerry® Mobile Data System™ features. 115 . specifying HTTPS as the protocol.open("https:// host:443/. add one of the following parameters to the connection string that passes to Connector. If the BlackBerry device does not support end-to-end TLS. 2. verify that the BlackBerry® device is within network coverage. • Specify that an end-to-end HTTPS connection should be used from the BlackBerry device to the target server. then a proxy connection is used: EndToEndDesired.system package to make sure that the BlackBerry device is in network coverage. BlackBerry® Java® Applications that use socket connections typically require significantly more bandwidth than BlackBerry Java Applications that use HTTP connections Note:In the ‘Open a Socket connection’ tasks that follow. BlackBerry MDS Services is used by default. and the BlackBerry device user permits proxy TLS connections. > To open an HTTPS connection in end-to-end mode. Specify the connection mode. the BlackBerry device uses direct TCP.api.open("https:// host:443/"). If your BlackBerry device is associated with a BlackBerry Enterprise Server and uses an HTTPS proxy server that requires authentication. Steps > Use the CoverageInfo class and CoverageStatusListener interface of the net. verify that the BlackBerry® device is in network coverage. BlackBerry 7100i). the following results occur: • • The connection uses direct TCP by default for any BlackBerry on the iDEN network (BlackBerry 6510 Wireless Handheld. such as push. Steps > Use the CoverageInfo class and CoverageStatusListener interface of the net. HttpsConnection stream = (HttpsConnection)Connector.7: Creating connections Use HTTPS connections Task Before opening an HTTPS connection.api. Invoke Connector.system package to make sure that the BlackBerry device is in network coverage. 1.

apn=internet.close(). length). ++i ) { input[i] = (char)_in. private static String URL = "socket:// local_machine_IP:4444. appending the deviceside=true parameter to the end of the URL. > Invoke openInputStream() and openOutputStream(). 116 . StreamConnection conn = null. conn. StreamConnection conn = null. BlackBerry Java®Applications must input their local machine IP explicitly because localhost is not supported. Open a socket connection over direct TCP.length(). StreamConnection conn = null. }.open(). The tunnelauthusername and tunnelauthpassword parameters can be omitted from the connection URL if they are not required by the APN.open(). int length = data. > Invoke Connector.tunnelauthpassword=user165password". If you are creating a direct TCP connection. Close the Socket connection. specifying APN information. specifying socket as the protocol. Make sure that the BlackBerry® Java® Application implements exception handling.openInputStream()).open(URL). for ( int i = 0. > Invoke Connector. Each of the close() methods throws an IOException. _in.deviceside=true". • The tunnelauthusername parameter contains the user name to connect to the APN.openOutputStream()). _out. specifying socket as the protocol and appending the deviceside=false parameter to the end of the URL. 0.read(). String data = "This is a test". Connections through the BlackBerry® MDS Services are automatically routed by the BlackBerry device. InputStreamReader _in = new InputStreamReader(conn.write(data.close().com. private static String URL = "socket:// local_machine_IP:4444. Steps > Invoke Connector.BlackBerry Java Development Environment Development Guide Task Open a socket connection using BlackBerry® MDS Services. conn = (StreamConnection)Connector. i < length. therefore. > Invoke close() on the input and output streams and the socket connection. Open a socket connection over direct TCP.deviceside=true. OutputStreamWriter _out = new OutputStreamWriter(conn.tunnelauthus ername =user165. • The tunnelauthpassword parameter contains the password for the tunnelauthusername. char[] input = new char[length]. no APN information is required.open(URL). _out.deviceside=false". private static String URL = "socket:// local_machine_IP:4444.open(). conn = (StreamConnection)Connector.close(). Specify the following APN parameters: • The APN parameter contains the APN over which the connection will be made. conn = (StreamConnection)Connector.open(URL). specifying socket as the protocol. appending the deviceside=true parameter to the end of the URL. Send and receive data. use these parameters.

Using UDP connections requires that you work closely with service providers. they cannot guarantee that a subsequent network connection will be successful. Invoke Datagram. verify that the BlackBerry® device is in network coverage. 117 . src-port is the local source port (optional). Open a datagram connection. 2. If a BlackBerry® Java® Application attempts to send a datagram on a datagram connection and the recipient is not listening on the specified source port. Specify the source port number.newDatagram(). > Invoke send() on the datagram connection.7: Creating connections Datagram connections Datagrams are independent packets of data that applications send over networks.setData().length). specifying udp as the protocol. Send data on the datagram connection. Steps > Use the CoverageInfo class and CoverageStatusListener interface of the net. > > host is the host address in dotted ASCII-decimal format.src_port]/ apn"). buf.open(). Invoke Connector. Use a datagram connection to send and receive datagrams. Even though the CoverageInfo class and the CoverageStatusListener interface can determine if the BlackBerry device that your BlackBerry Java® Application is on is in network coverage.length). conn. an IOException is thrown. For example.6343/. Datagram outDatagram = conn.setData(buf. the address for a CDMA network connection would be udp:// 121.send(outDatagram). 1. > > Invoke DatagramConnection.0. outDatagram. (DatagramConnection)Connector. dest-port is the destination port at the host address (optional for receiving messages).device.open("udp://host:dest_port[.api.0. including the trailing slash mark. buf. including an APN for GPRS networks.newDatagram(buf.0:2332. where: • • • • Receive datagrams from all ports at the specified host. Use datagram connections To use a datagram connection. you must have your own infrastructure to connect to the wireless network. Cast the returned object as a DatagramConnection object. A Datagram object is a wrapper for the array of bytes that is the payload of the datagram.rim. apn is the network APN in string format.system package to make sure that the BlackBerry device is in network coverage. Verify that your service provider supports UDP connections. Make sure that the BlackBerry Java Application implements exception handling. Omit the destination port in the connection string. Add data to a diagram. byte[] buf = new byte[256]. You can send and receive datagrams on the same port. Open a datagram connection on a nonGPRS network. Task Before opening a datagram connection. Create a datagram.

String received = new String(inDatagram. This type of connection also lets BlackBerry Java Applications communicate with a peripheral device that plugs into the serial or USB port. Datagram inDatagram = conn. convert the data to the appropriate format. Close the datagram connection. conn. > Invoke getData(). 118 .BlackBerry Java Development Environment Development Guide Task Steps Invoke receive() on the datagram connection.length). Invoke close() on the input and output streams.newDatagram(buf. and on the datagram connection object. Since the receive() method blocks other operations until it receives a data packet. > Using port connections Using a serial or USB connection. Receive data on the datgram connection. Extract data from a datagram. BlackBerry® Java® Applications can communicate with desktop applications when they are connected to a computer using a serial or USB port. > byte[] buf = new byte[256]. buf.receive(inDatagram). use a timer to retransmit the request or close the connection if a reply does not arrive.getData()). If you know the type of data that you are receiving.

baudrate=9600.stopbits=1").getSerialPortInfo() returns as a parameter. private static final int JUST_OPEN = 4. 2. 1. BluetoothSerialPortInfo[] info = BluetoothSerialPort. Connector. Make sure the BlackBerry® Java® Application implements exception handling. String contents = _din. DataOutputStream _dout = _conn. The close() method can throw IOExceptions.open().toString(). Send data on the Bluetooth connection.openInputStream(). _dout. DataInputStream _din = _conn. Use the write methods on the output stream to write data. 119 .writeInt(JUST_OPEN). Receive data on the USB or serial port connection.parity=none.rim. providing the serial port information that BluetoothSerialPort.READ_WRITE ). part of the JSR 82 implementation. private StreamConnection _conn = (StreamConnection)Connector.api.bitsperchar=8. _din. DataOutputStream _dout = _bluetoothConnection. 2. and initiate a server or client Bluetooth serial port connection to a computer or other Bluetooth enabled device. Use the write methods on the output stream to write data. StreamConnection _bluetoothConnection = (StreamConnection)Connector. _dout.getSerialPortInfo().device. Invoke close() on the input and output streams.close().readUTF().close(). Close the USB or serial port connection.7: Creating connections Use USB or serial port connections Task Open a USB or serial port connection. Use a non-main event thread to read data from the input stream. 2.open(). 2.close(). conn. Invoke openInputStream() or openDataInputStream(). Use the read methods on the input stream to read data. private String data = "This is a test". Steps > Invoke Connector. specifying comm as the protocol and COM1 or USB as the port. 1.openDataOutputStream(). 1. and on the port connection object. Steps > Invoke Connector. Invoke openDataOutputStream() or openOutputStream().writeChars(data). Send data on the USB or serial port connection.open( info[0]. 1. Invoke openDataOutputStream() or openOutputStream(). Task Open a Bluetooth connection.open( "comm:COM1.openDataOutputStream(). _dout. Use Bluetooth serial port connections You can use the Bluetooth® API (net.bluetooth) to let your BlackBerry® Java® Application access the Bluetooth Serial Port Profile.

java example requires that you create resource files in the BlackBerry® Java® Application project and define the required resource keys. 1.close(). Invoke openInputStream() or openDataInputStream(). DataInputStream _din = _bluetoothConnection.BlackBerry Java Development Environment Development Guide Task Receive data on the Bluetooth connection. 2. Example: HTTPFetch. Use the read methods on the input stream to read the data. Code samples Code sample: Using an HTTP connection to retrieve data The HTTPFetch.close(). See “Localizing BlackBerry Java Applications” on page 223 for more information on creating resource files.close(). _dout = null. Steps 1. Close the Bluetooth connection. } catch(IOException ioe) { } } if (_din != null) { try { _din. Create a non-main event thread to read data from the input stream. _din = null. } catch(IOException ioe) { } } _bluetoothConnection = null. Make sure the BlackBerry® Java® Application implements exception handling. if (_bluetoothConnection != null) { try { _bluetoothConnection. See “Code sample: Listening for data on the serial port and rendering the data when it arrives” on page 124 for more information.readUTF(). 3.java /** * HTTPFetch. Invoke close() on the input and output streams. } catch(IOException ioe) { } } if (_dout != null) { try { _dout.java 120 . 2. The close() method can throw IOExceptions. String contents = _din.openDataInputStream(). and on the Bluetooth serial port connection object.

*. import import import import import import import import net.enterEventDispatcher().resource.api. private static final String SAMPLE_PAGE = “http://localhost/testpage/sample.*.rim. net. /* The volatile keyword indicates that because the data is shared.device.device.rim. private static final String[] HTTP_PROTOCOL = {“http://”. but produces less overhead.*. net. public static void main(String[] args) { HTTPFetch theApp = new HTTPFetch().rim.docs.*.device. All rights reserved. * instead of cached by the VM.api. net.samples. “http:\\”}.docs.httpfetch.api. net. */ private class ConnectionThread extends Thread { private static final int TIMEOUT = 500.io.BUNDLE_ID. 121 .system. theApp. */ private volatile boolean _start = false. // Members.txt”.*. This technique is equivalent to wrapping * the shared data in a synchronized block. private volatile boolean _stop = false. * the second request stalls until the previous request completes. } /** * The ConnectionThread class manages the HTTP connection.*.device. public class HTTPFetch extends UiApplication implements HTTPFetchResource { // Constants.i18n.io. //statics private static ResourceBundle _resources = ResourceBundle.ui.rim.rim. //ms private String _theUrl. com.ui.ui. HTTPFetchResource.rim. */ ConnectionThread _connectionThread = new ConnectionThread().samples.api. javax.getBundle( HTTPFetchResource.*.microedition.device.BUNDLE_NAME).*.rim. private RichTextField _content. * the value of each variable must always be read and written from memory. private MainScreen _mainScreen.container.component.api. java. but if a second fetch request * is made while a previous request is still active. /** * Send and receive data over the network on a * separate thread from the main thread of your application. * Fetch operations are not queued.7: Creating connections * Copyright (C) 2001-2005 Research In Motion Limited. */ package com.

*/ public void stop() { _stop = true. byte[] data = new byte[256].BlackBerry Java Development Environment Development Guide /** * Retrieve the URL. int len = 0. */ synchronized(this) { // Open the connection and extract the data. Invoked when the application exits. _theUrl = url.open(getUrl()). InputStream input = s.) { // Thread control. } /** * Fetch a page. } /** * Close the thread. StreamConnection s = null.openInputStream(). StringBuffer raw = new StringBuffer(). } /* Ensure that fetch requests are not missed * while received data is processed.. */ public void fetch(String url) { _start = true. Invoked when the thread * is started.toString()). 122 . } } // Exit condition. // Extract data in 256 byte chunks. } catch (InterruptedException e) { System.println(e. if ( _stop ) { return. */ public void run() { for(. */ public synchronized String getUrl() { return _theUrl. // but the thread has not been stopped. try { sleep(TIMEOUT). The synchronized keyword makes sure that only one * thread at a time can call this method on a ConnectionThread object. } /** * Open an input stream and extract data. which is invoked in the application constructor when * the user selects the Fetch menu item.err. while( !_start && !_stop) { // No connections are open for fetch requests. try { s = (StreamConnection)Connector. This method is invoked on the connection thread by * fetchPage().

_connectionThread. for (i = HTTP_PROTOCOL. updateContent(e.println(e. int i = 0.add(_content). pushScreen(_mainScreen). } // Retrieve web content. } } // Constructor. } } } } private final class HTTPMainScreen extends MainScreen { // Close the connection thread when the user closes the application.stop(). } // Reset the start state. } catch (IOException e) { System. super.err.close(). _start = false. _mainScreen.toLowerCase().indexOf(HTTP_PROTOCOL[i]) ) { validHeader = true.USE_ALL_WIDTH)).getString(APPLICATION_TITLE). i >= 0. // Start the helper thread.read(data)) ) { raw.toString(). public void close() { _connectionThread. String lcase = url.length .getString(HTTPDEMO_CONTENT_DEFAULT)). _content = new RichTextField( _resources.close(). input.add(new SeparatorField()). _mainScreen.append(new String(data.7: Creating connections while ( -1 != (len = input. private void fetchPage(String url) { // Perform basic validation (set characters to lowercase and add http:// or https:/ /). 0.close(). len)).toString()). boolean validHeader = false. break. updateContent(text). public HTTPFetch() { _mainScreen = new HTTPMainScreen(). _mainScreen.setTitle(new LabelField( _resources.start(). LabelField. fetchPage(SAMPLE_PAGE). --i) { if ( -1 != lcase.ELLIPSIS | LabelField.1. } String text = raw.toString()). 123 . // Display the text on the screen. s.

com. } // Display the content.io.rim.api.api.rim.ui.*.rim.api.rim.device.api.device.device.bluetoothserialportdemo.samples. } } Code sample: Listening for data on the serial port and rendering the data when it arrives Example: BluetoothSerialPortDemo.microedition.device.rim.system. } // Create a new thread for connection operations.BlackBerry Java Development Environment Development Guide } } if ( !validHeader ) { // Prepend the protocol specifier if it is missing.docs. net. net.*. net.device. private void updateContent(final String text) { /* This technique creates several short-lived objects but avoids * the threading issues involved in creating a static Runnable and * setting the text.device.api. */ /* The client side of a simple serial port demonstration application. */ UiApplication. javax.java * Copyright (C) 2004-2005 Research In Motion Limited.util. import import import import import import import import import import java.api.ui.container.java /** * BluetoothSerialPortDemo. _connectionThread.samples.setText(text).getUiApplication(). } }).rim.ui. url = HTTP_PROTOCOL[0] + url. */ package com. 124 . * This application listens for text on the serial port and * renders the data when it arrives.*.io. net.docs.*.device.*.fetch(url).resource. net.*.*.component.rim.*.rim. net.rim.*.api.bluetooth.i18n. net.*.invokeLater(new Runnable() { public void run() { _content.

getText()).enterEventDispatcher().makeMenu(menu. } super.getTextLength() > 0) { menu. } 125 .BUNDLE_NAME). MENUITEM_COPY. JUST_OPEN = 4.getBundle(BluetoothSerialPortDemoResResource. NO_CONTENTS = 6. 10) { public void run() { Clipboard. } }). BluetoothSerialPortDemoResResource.add(new MenuItem(_resources. static { _resources = ResourceBundle.7: Creating connections public class BluetoothSerialPortDemo extends UiApplication implements BluetoothSerialPortDemoResResource { //statics -----------------------------------------------------------------private static ResourceBundle _resources. super. DataOutputStream _dout. REMOVE = 2. 100000. private final class BluetoothDemoScreen extends MainScreen { protected void makeMenu(Menu menu. } } public static void main(String[] args) { new BluetoothSerialPortDemo(). } private private private private EditField _infoField.close().put(_infoField.BUNDLE_ID. DataInputStream _din.getClipboard(). int instance) { if (_infoField. CHANGE = 3. StreamConnection _bluetoothConnection. } public void close() { closePort(). CONTENTS = 5. private private private private private private static static static static static static final final final final final final int int int int int int INSERT = 1. instance).

READONLY). invokeLater(new Runnable() { public void run() { openPort(). } 126 .USE_ALL_WIDTH)). } catch(IOException ioe) { } } if (_din != null) { try { _din. private void closePort() { if (_bluetoothConnection != null) { try { _bluetoothConnection.add(_infoField).close().getString(TITLE). } catch(IOException ioe) { } } if (_dout != null) { try { _dout. } catch(IOException ioe) { } } _bluetoothConnection = null. _din = null. LabelField. mainScreen.BlackBerry Java Development Environment Development Guide //constructor -------------------------------------------------------------public BluetoothSerialPortDemo() { MainScreen mainScreen = new BluetoothDemoScreen(). _infoField = new EditField(Field. } // Open the serial port.setTitle(new LabelField(_resources. mainScreen. _dout = null.close().close(). } // Close the serial port. pushScreen(mainScreen). private void openPort() { if (_bluetoothConnection != null) { closePort(). } }).

”). _dout. String value.exit(1).length == 0 ) { invokeAndWait( new Runnable() { public void run() { Dialog. for (. value = _din. if (type == INSERT) { offset = _din.READ_WRITE ). 127 .” )..exit(1). closePort(). } }).readInt().flush(). count = _din. } }). _din = _bluetoothConnection. count). insert(value. } catch(IOException e) { invokeAndWait( new Runnable() { public void run() { Dialog. _dout.openDataInputStream(). } }).getSerialPortInfo(). remove(offset. } else if (type == REMOVE) { offset = _din. } _bluetoothConnection = (StreamConnection)Connector. _dout = _bluetoothConnection. count.) { type = _din. System.exit(1).openDataOutputStream().toString(). closePort(). } catch( UnsupportedOperationException e ) { invokeAndWait( new Runnable() { public void run() { Dialog.readInt().readUTF().open( info[0]. System.start().alert( “No bluetooth serial ports available for connection. offset. if( info == null || info.readInt(). } try { int type.writeInt(JUST_OPEN). closePort().7: Creating connections new InputThread().alert(“This handheld or simulator does not support bluetooth.readInt(). Connector. System.alert(“Unable to open serial port”). offset). } private class InputThread extends Thread { public void run() { try { BluetoothSerialPortInfo[] info = BluetoothSerialPort.

getEventLock()) { _infoField. } }). final int count) { invokeLater(new Runnable() { public void run() { _infoField.setText(contents).BlackBerry Java Development Environment Development Guide } else if (type == JUST_OPEN) { // Send contents to desktop.setCursorPosition(offset+count). } private void remove(final int offset. } } } catch(IOException ioe) { invokeLater(new Runnable() { public void run() { Dialog. _infoField.readUTF(). } }). _dout.alert(“Problems reading from or writing to serial port.”). _dout. } } else if (type == CONTENTS) { String contents = _din. if (value == null || value.insert(msg). _infoField. System. } }). closePort(). } } 128 . } else { _dout. } } else if (type == NO_CONTENTS) { } else { throw new RuntimeException(). _dout.exit(1).writeInt(CONTENTS).backspace(count).flush().writeUTF(_infoField.setCursorPosition(offset).writeInt(NO_CONTENTS).flush(). } } } private void insert(final String msg. value = _infoField.getText(). synchronized(Application.equals(““)) { _dout.getText()). final int offset) { invokeLater(new Runnable() { public void run() { _infoField.

7: Creating connections 129 .

BlackBerry Java Development Environment Development Guide 130 .

802.8 Working with Wi-Fi connections on a BlackBerry device Work with wireless access families Work with a Wi-Fi connection Work with wireless access families Working with the BlackBerry® device transceiver involves using APIs that make reference to wireless access families. GERAN. See the API reference for the BlackBerry Java Development Environment for more information about wireless access families.areWAFsSupported(int wafs). Wireless access family 3GPP CDMA WLAN Description includes GPRS. EDGE.11b™. Determine the wireless access family transceivers that are turned on. and GAN includes CDMA1x and EVDO includes 802. Determine if a BlackBerry device supports one or more wireless access families.11a™.11g™ Identify the wireless access families that a BlackBerry device supports Task Retrieve the wireless access families that a BlackBerry device supports.11™. 802. 802. > Invoke RadioInfo.getActiveWAFs(). . Invoke RadioInfo. UTRAN.getSupportedWAFs(). UMTS. Steps > > Invoke RadioInfo.

Application. This parameter is applied only to RadioStatusListeners. Turn off the transceiver for a wireless access family.deactivateWAFs(int WAFs).api. RadioStatusListener listener = new RadioStatusListener() { … }.addListener(listener). transceiver for the WLAN wireless access family connects or disconnects 2. From the net.WAF_WLAN and the value returned by RadioInfo. RadioListener listener). This method registers the listener to listen for events from the wireless access families specified in the wafFilter parameter. The WAFs parameter is a bitmask. > Register a unique RadioStatusListener instance for each wireless access family.addRadioListener(int wafFilter.activateWAFs(int WAFs). WLANInfo. Steps > Create an IF statement that tests the value of RadioInfo.addRadioListener(int wafFilter. The WAFs parameter is a bitmask.WAF_WLAN.getActiveWAFs() & RadioInfo.addRadioListener(int wafFilter. Determine the wireless access family that generated a transceiver event. Register a WLANConnectionListener object by invoking the WLANInfo. Receive notifications of transceiver events Task Enable a BlackBerry Application to receive transceiver events from multiple transceivers. RadioListener listener) using the RadioInfo. with a wireless access point. Invoke Application. for example: if ( ( RadioInfo.system package.rim. the application will not be able to determine the wireless access family that generated the transciever event. WLANConnectionListener listener = new WLANConnectionListener() {…}. Invoke Application.BlackBerry Java Development Environment Development Guide Turn on a transceiver for a wireless access family Task Turn on the transceiver for a wireless access family.addListener() method using a WLANConnectionListener object as a parameter.addRadioListener(RadioInfo. Steps > Register a transceiver event listener for specific wireless access families by invoking Application.device.WAF_WLAN ) != 0 ) { … } 132 . listener). Steps > > Invoke Radio. 3. RadioListener listener) using the RadioInfo. when the RadioStatusListener method notifies the application of a transciever event. If a BlackBerry Application registers a RadioStatusListener method for more than one wireless access family. Work with a Wi-Fi connection Query the status of the Wi-Fi transceiver on a BlackBerry device Task Determine if the transceiver for the WLAN wireless access family is on. Receive notifications of Wi-Fi transceiver events > Receive notifications when the 1.WAF_WLAN field and a RadioStatusListener object as parameters.getActiveWAFs(). Invoke Radio.WAF_WLAN parameter. import the WLANListener and WLANConnectionListener interfaces and the WLANInfo class.

Retrieve status information about a You can let a BlackBerry device application retrieve status information such as the data rate of the wireless access point or the active Wi.WLANAPInfo.system package.WLANAPInfo object contains a snapshot of the current wireless network.rim.WLAN_STATE_CONNECTED) {…} The WLANInfo.NETWORK_SERVICE_GAN flag is set in the return value. b or g). 133 . check for the RadioInfo.NETWORK_SERVICE_* flags that the getNetworkService(int)method returns.device. the BlackBerry device is accessing a wireless network through a wireless access point. check to see if the RadioInfo.WLANAPInfo that this method returns. If this flag is set in the service parameter.connection.getAPInfo() method returns null.device. If the BlackBerry device is not connected to an access point.WLANAPInfo info = WLANInfo. Create an IF statement that tests the value of WLANInfo. Invoke the RadioInfo. the WLANInfo. if (WLANInfo.WLAN_STATE_CONNECTED and the value returned by WLANInfo.WAF_3GPP parameter.getNetworkService method using the RadioInfo. WLANInfo.api. > When the listener’s RadioStatusListener. See the API reference for the BlackBerry Java Development Environment for more information about WLANInfo. 1.api.getAPInfo(). this method returns WLANInfo. From the net. or the name of the Wi-Fi profile in use.8: Working with Wi-Fi connections on a BlackBerry device Task Determine if the transceiver for the WLAN wireless access family is connected to a wireless access point. When a 3GPP wireless access family generates a transceiver event. determine if the BlackBerry device is accessing a wireless network through a wireless access point.NETWORK_SERVICE_GAN flag in the service parameter.WLAN_STATE_DISCONNECTED. import the WLANInfo class.getWLANState() method checks if a BlackBerry device has an IP address and can transfer data over a Wi-Fi network. 2.getAPInfo(). 2.getWLANState().rim. The transceiver for the WLAN wireless access family must be connected to a wireless access point.networkServiceChange(int networked. 2. Steps 1. storing a reference to WLANInfo. int service) method is invoked. the SSID of the associated access Fi profile. The WLANInfo. If the transceiver for the WLAN wireless access family is off.11a. In the bitmask of the RadioInfo. Invoke WLANInfo.getWLANState() == WLANInfo. From the net. Accessing a wireless network through a wireless access point Task Determine if the BlackBerry device is accessing a wireless network through a wireless access point. point.system package. import the WLANInfo class. the wireless LAN standards used (802. Steps 1.

String URL = "http://www. Invoke isCoverageSufficient(COVERAGE_CARRIER.WAF_WLAN. To establish a Wi-Fi® connection and use a Wi-Fi API in a BlackBerry device application. Open a Wi-Fi connection The interface=wifi parameter applies only to TCP/UDP connections. 2. Cast the returned object as an HttpsConnection object.RadioInfo.deviceside=true. Determine if the BlackBerry device has > enough wireless coverage to attempt a direct TCP connection through a wireless access point. Open a Wi-Fi HTTPS connection.interface=wifi". and append the deviceside=true parameter and the interface=wifi parameter to the end of the URL string value. and append the interface-wifi parameter to the end of the URL string value. Invoke Connector.interface=wifi". conn = (HttpsConnection)Connector. Task Open a Wi-Fi socket connection. HttpsConnection conn = null. Invoke Connector. and append the interface=wifi parameter to the end of the URL string value. conn = (HttpConnection)Connector. Invoke isCoverageSufficient(COVERAGE_MDS.com/ myContent.open(URL). private static String URL = "socket:// local_machine_IP:4444.deviceside=true. false).WAF_WLAN.open(URL). 134 .deviceside=true.open(). 1. specify https as the protocol.open(URL). RadioInfo. 1. Steps > Invoke Connector. 2. Cast the returned object as an HttpConnection or a StreamConnection object.false). specify socket as the protocol.myServer. String URL = "https://host:443/. specify http as the protocol. StreamConnection conn = null. Receive notifications of changes in the > connectivity state of a Blackberry device.open().interface=wifi". the wireless service provider must support Wi-Fi access. Determine if the BlackBerry device has > enough wireless coverage to attempt a WLAN enterprise connection through a wireless access point.BlackBerry Java Development Environment Development Guide Determine if the BlackBerry device is in a wireless coverage area Task Steps Use the addListener()methods of the CoverageInfo class. Open a Wi-Fi HTTP connection.open(). HttpConnection conn = null. conn = (StreamConnection)Connector.

typically by displaying a UI element. such as a flashing LED. BlackBerry Java® Applications that are affected by the event can provide custom notifications to the BlackBerry device user. BlackBerry devices do not provide system-wide notifications for deferred events. When the event occurs.9 Creating notifications Types of notification events Add a new event source Respond to deferred events Cancel events Customize system notifications for immediate events Code samples Types of notification events The notification API (net. BlackBerry® devices schedule events in a queue according to their priority. In the BlackBerry device profiles list. Notification event type Immediate events Description With immediate events.rim.device. Deferred events . such as a dialog box. BlackBerry® devices notify the BlackBerry device user as soon as the event occurs. or tune. With deferred events. BlackBerry device users control how they receive notification of immediate events by choosing an active profile and setting profile options. vibration.notification) lets you add custom events for your BlackBerry® Java® Application and define the type of notification that BlackBerry device users receive when custom events occur. A BlackBerry Java® Application cannot request a specific type of notification.api. using a system notification.

On the Application tab. for deferred events only. Click Convert “string” to Long. 1. In the Alternate entry point drop-down list. Right-click the highlighted string.CASUAL Register the event source when the BlackBerry device starts To register the event source when the BlackBerry® device starts. public static final long ID_1 = 0xdc5bf2f81374095L. allowing the BlackBerry Java Application to perform any one-time initializations. Open the BlackBerry® Integrated Development Environment. Select the System module option. Steps 1. 7. Define a source object.registerSource(). click the event source project. Task Create an initialization project. In the BlackBerry IDE text pane. Right-click the project. 5. Steps 1. the source object.IMPORTANT • NotificationsConstants. 6. When the BlackBerry device starts. and. Object event = new Object() { public String toString() { return "Notification Demo". type a string. Click OK. specify a unique event ID. in the Project type drop-down list. Define an object that provides the source for the event. click Alternate CLDC Application Entry Point. type autostartup. 4. In this method. Your implementation of toString() returns the string to display in the profiles list. 2. and then click Properties.BlackBerry Java Development Environment Development Guide Add a new event source Task Create a unique long ID. create a separate project that acts as an alternative entry point to the main BlackBerry Java® Application. 8. one of the following priority levels: • NotificationsConstants. 2. 2. 2. 3. In the Arguments passed to field. } } Add your BlackBerry® Java® Application to the BlackBerry device profiles. Define a long ID for each notification event. this project automatically runs as a system module and passes an argument to the BlackBerry Java Application. 1. Select the string.CRITICAL • NotificationsConstants.SENSITIVE • NotificationsConstants. 136 . 4. Invoke NotificationsManager. 5. 6. 3. Select the Auto-run on startup option.DEFAULT_LEVEL • NotificationsConstants. create a project. In the BlackBerry® Integrated Development Environment.

Trigger a deferred event. int. long.triggerImmediateEvent(ID_1.equals(“autostartup”)) { //BlackBerry Java® Application runs as a system module at startup. long. } } See “Code sample: Add a new event source” on page 141 for more information. 0. public static void main (String[] args) { if ( args. this. Invoke negotiateDeferredEvent(). NotificationsManager. Invoke triggerImmediateEvent().9: Creating notifications Task Perform initializations at the alternative entry point.negotiateDeferredEvent(ID_1. If you invoke negotiateDeferredEvent(long. 137 . null). > In your main() method. //Perform any necessary one-time automatic initialization. perform any required initializations. NotificationsManager.MANUAL_TRIGGER. Steps > 1. 0. 2. your BlackBerry® Java® Application must implement the NotificationEngineListener to receive events and respond appropriately. } else { //BlackBerry Java Application is being run by a user.length > 0 && args[0]. Object). null). Object. Triggering events Task Trigger an immediate event. Steps 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. NotificationsConstants. this. -1.

occurs. s. Object context) { same or higher priority. er. long sourceID. BlackBerry device from the holster. Dialog.show().IN_HOLSTER_ENGINE_STATE) { // Perform action if the BlackBerry device is inserted into the holster. public void proceedWithDeferredEvent(long sourceID. _app.. long eventID. > Invoke NotificationsManager. } }). Steps > Implement the NotificationsEngineListener interface. null). superseded by another event at the public void deferredEventWasSuperseded(long sourceID. device user inserts or removes the public void notificationsEngineStateChanged(int stateInt.MANUAL_TRIGGER.OUT_OF_HOLSTER_ENGINE_STATE) { // Perform action if the BlackBerry device is removed from the holster. Object eventReference. Object context) { final long _eventID = eventID. long eventID.OK.invokeLater(new Runnable() { public void run() { NotificationsManager. d).. long eventID.D_OK. Dialog d = new Dialog(Dialog.} Define behavior if an event is > Implement deferredEventWasSuperseded(). NotificationsEngineListener). _eventHashtable. er = eventReference. Object context) { if(stateInt == NotificationsConstants.cancelDeferredEvent(ID_1. } } Define notification when the event > Implement proceedWithDeferredEvent(). _eventID.getPredefinedBitmap(Bitmap. final long _eventID = eventID. } Define behavior if the BlackBerry® > Implement notificationsEngineStateChanged(). Object eventReference. } Register the notifications listener with the NotificationsManager. NotificationsManager. 0).registerNotificationsEngineListener(int. Bitmap. providing as parameters the event source ID of your BlackBerry Java Application and an instance of the class that implements the NotificationsEngineListener interface.BlackBerry Java Development Environment Development Guide Respond to deferred events Task Provide a custom UI notification. } }). new ListenerImpl(this)). You can register only one NotificationsEngineListener for each BlackBerry® Java® Application. private static class ListenerImpl implements NotificationsEngineListener {.invokeLater(new Runnable() { public void run() { String s = "This event has occurred: " + _eventID. Object eventReference.INFORMATION). NotificationsConstants.registerNotificationsEngineListener( ID_1. _app. 138 .put(_eventID. d. } if(stateInt == NotificationsConstants.

9: Creating notifications

Cancel events
Task Cancel an immediate event. Steps > Invoke cancelImmediateEvent(long, long, Object, Object),and then the source and event ID. Invoke cancelDeferredEvent(long, long, Object, int, Object),and then the source and event ID.

NotificationsManager.cancelImmediateEvent(ID_1, 0, this, null);

Cancel a deferred event.

>

NotificationsManager.cancelDeferredEvent(ID_1, 0, this, NotificationsConstants.MANUAL_TRIGGER, null);

Cancel all deferred events.

If you invoke negotiateDeferredEvent() and do not specify a timeout, you must invoke cancelDeferredEvent() to cancel the event, or the event never expires. > Invoke cancelAllDeferredEvents(long, int, Object) to cancel all deferred events that your BlackBerry® Java® Application starts.

NotificationsManager.cancelAllDeferredEvents(ID_1, NotificationsConstants.MANUAL_TRIGGER, null);

Customize system notifications for immediate events
Task Respond to notification events. Steps > Create a class that implements the Consequence and SyncConverter interfaces. The SyncConverter interface defines the functionality necessary to convert data from object to serialized format.

private static class ConsequenceImpl implements Consequence,SyncConverter {...}

Define a unique ID. Define the constants.

> >

Define a unique ID for the consequence Declare the DATA and TYPE constants to identify data for the BlackBerry® Java® Application. When the BlackBerry Java Application invokes convert(), the constants identify the type of incoming data from the SyncConverter.
final int TYPE = 'n' << 24 | 'o' << 16 | 't' << 8 | 'd'; final byte[] DATA = new byte[] {'m', 'y', '-', 'c', 'i', 'g', '-', 'o', 'b', 'j', 'e', 'c', 't'}; final Configuration CONFIG = new Configuration(DATA); final final final final final final short BFlat = 466; // 466.16 short TEMPO = 125; short d16 = 1 * TEMPO; short dpause = 10; // 10 millisecond pause short[] TUNE = new short[] {BFlat, d16, pause, BFlat}; int VOLUME = 80; // Percentage volume.

public static final long ID = 0xbd2350c0dfda2a51L;

private static private static 'o', 'n', 'f', private static

Create a tune that plays when the BlackBerry® device user receives the notification.

>

Create a tune that plays as part of the consequence for event notifications.
static static static static static static

private private private private private private

139

BlackBerry Java Development Environment Development Guide

Task Define a notification.

Steps > 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().

public void stopNotification(long consequenceID, long sourceID, long eventID, Object configuration, Object context) { LED.setState(LED.STATE_OFF); Alert.stopAudio(); Alert.stopBuzzer(); }

Store the event notification user profile settings.

>

Implement newConfiguration().

public Object newConfiguration(long consequenceID, long sourceID, byte profileIndex, int level, Object context) { return CONFIG; }

Enable data backup for the event notification user profile settings.

>

Implement SyncConverter.convert().

public SyncObject convert(DataBuffer data, int version, int UID) { try { int type = data.readInt(); int length = data.readCompressedInt(); if ( type == TYPE ) { byte[] rawdata = new byte[length]; data.readFully(rawdata); return new Configuration(rawdata); } } catch (EOFException e) { System.err.println(e); } return null; }

Enable data restore for the event notification user profile settings.

>

Implement SyncConverter.convert().

public boolean convert(SyncObject object, DataBuffer buffer, int version) { boolean retval = false; if ( object instanceof Configuration ) { Configuration c = (Configuration)object; buffer.writeInt(TYPE); buffer.writeCompressedInt(c._data.length); buffer.write(c._data); retval = true; } return retval; }

140

9: Creating notifications

Task Define the notification configuration.

Steps 1. Create a class that implements SyncObject and Persistable. 2. In the class, make sure the SyncObject.getUID() method returns 0 if data synchronization is not required.
private static final class Configuration implements SyncObject, Persistable { public byte[] _data; public Configuration(byte[] data) { _data = data; } public int getUID() { return 0; } }

Register a custom notification in the NotificationsManager.

>

If you create a custom Consequence implementation, register it with the NotificationsManager by invoking registerNotificationsObjects(long, Consequence).

NotificationsManager.registerConsequence(ConsequenceImpl.ID, new ConsequenceImpl());

See “Code sample: Creating a custom notification” on page 144 for more information.

Code samples
Code sample: Add a new event source
Example: NotificationsDemo.java
/** * NotificationsDemo.java * Copyright (C) 2001-2005 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.notifications; import import import import import import net.rim.device.api.notification.*; 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.*;

public class NotificationsDemo extends UiApplication { public static final long ID_1 = 0xdc5bf2f81374095L; private long _eventIdGenerator; private static Object er; public static final Object event = new Object() { public String toString() {

141

BlackBerry Java Development Environment Development Guide

return “Sample Notification Event #1”; } }; public static void main(String[] args) { if ( args.length > 0 && args[0].equals( “autostartup” ) ) { NotificationsManager.registerSource(ID_1, event, NotificationsConstants.CASUAL); NotificationsManager.registerConsequence(ConsequenceDemo.ID, new ConsequenceDemo()); } else { NotificationsDemo app = new NotificationsDemo(); app.enterEventDispatcher(); } } 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.triggerImmediateEvent(ID_1, 0, this, null); } public String toString() { return “Trigger event”; } }; private MenuItem deferItem = new MenuItem(null, 0, 100, 10) { public void run() { long timeout = -1; // Ignored unless trigger is OUT_OF_HOLSTER_TRIGGER. int trigger = NotificationsConstants.MANUAL_TRIGGER; Object er = new Object(); NotificationsManager.negotiateDeferredEvent(ID_1, ++_eventIdGenerator, er, timeout, trigger, null); } public String toString() { return “Start deferred event”; } }; private MenuItem cancelItem = new MenuItem(null, 0, 100, 10) { public void run() { int trigger = NotificationsConstants.MANUAL_TRIGGER; NotificationsManager.cancelDeferredEvent(ID_1, _eventIdGenerator, er, trigger, null); } public String toString() { return “Cancel deferred event”; } }; private final class NotificationsMainScreen extends MainScreen
142

9: Creating notifications

{ protected void makeMenu( Menu menu, int instance ) { menu.add(triggerItem); menu.add(deferItem); menu.add(cancelItem); super.makeMenu(menu, instance); } } private static class NotificationsEngineListenerImpl implements NotificationsEngineListener { private UiApplication _app; public NotificationsEngineListenerImpl(UiApplication app) { _app = app; } 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.MANUAL_TRIGGER, null); } }); } public void notificationsEngineStateChanged(int stateInt, long sourceID, long eventID, Object eventReference, Object context) { if(stateInt == NotificationsConstants.OUT_OF_HOLSTER_ENGINE_STATE) { // Perform some action if handheld is removed from holster. } if(stateInt == NotificationsConstants.IN_HOLSTER_ENGINE_STATE) { // Perform some action if handheld is inserted into holster. } } public void proceedWithDeferredEvent(long sourceID, long eventID, Object eventReference, Object context) { final long _eventID = eventID; _app.invokeLater(new Runnable() { public void run() { String s = “This event has occurred: “ + _eventID; Dialog d = new Dialog(Dialog.D_OK, s, Dialog.OK, Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), 0); d.show(); } }); } } }

143

Object context) { LED. import import import import import net. SyncConverter { public static final long ID = 0xbd2350c0dfda2a51L. LED. long sourceID. public void startNotification(long consequenceID.docs.*. ‘-’. net.java /** * ConsequenceDemo.device. } public SyncObject convert(DataBuffer data.BRIGHTNESS_50).api. // 10 millisecond pause.rim.stopBuzzer(). int UID) { try { 144 . long eventID.java * Copyright (C) 2001-2005 Research In Motion Limited.io. ‘g’.synchronization. VOLUME). Alert.16.setState(LED. ‘c’.STATE_BLINKING).rim. int VOLUME = 80. LED. ‘f’.startBuzzer(TUNE. java.util. long sourceID. byte profileIndex. short[] TUNE = new short[] {BFlat. // Percentage volume.rim.api.device. // The actual value is 466. Object context) { return CONFIG. ‘n’. public class ConsequenceDemo implements Consequence. short TEMPO = 125.rim. private static final Configuration CONFIG = new Configuration(DATA). BFlat}. ‘e’.notification. private static final int TYPE = ‘n’ << 24 | ‘o’ << 16 | ‘t’ << 8 | ‘d’.*. ‘c’. Alert. private static final byte[] DATA = new byte[] { ‘m’. } public void stopNotification(long consequenceID. VOLUME). ‘t’ }. int version. short d16 = 1 * TEMPO.startAudio(TUNE.*. private private private private private private static static static static static static final final final final final final short BFlat = 466.rim. 250. long eventID.system.notifications.device.samples.STATE_OFF). All rights reserved. ‘o’. Object configuration. d16. Alert.device. ‘-’.setState(LED. int level.api. ‘o’.setConfiguration(500.*. net. ‘i’. ‘j’.BlackBerry Java Development Environment Development Guide Code sample: Creating a custom notification Example: ConsequenceDemo.*. Alert. long sourceID.stopAudio(). */ package com. ‘y’.api. net. pause. Object configuration. Object context) { LED. short pause = 10. ‘b’. } public Object newConfiguration(long consequenceID.

println(e). if ( type == TYPE ) { byte[] rawdata = new byte[length]. buffer.writeInt(TYPE).writeCompressedInt(c. } /* Inner class to store configuration profile. } } catch (EOFException e) { System. public Configuration(byte[] data) { _data = data. DataBuffer buffer. } return retval. } } } 145 . retval = true. Persistable { public byte[] _data.9: Creating notifications int type = data. } public int getUID() { return 0. } return null. */ private static final class Configuration implements SyncObject.err.readCompressedInt().write(c. if ( object instanceof Configuration ) { Configuration c = (Configuration)object.readFully(rawdata)._data._data).length). buffer. buffer. int version) { boolean retval = false. data.readInt(). int length = data. } public boolean convert(SyncObject object. return new Configuration(rawdata).

BlackBerry Java Development Environment Development Guide 146 .

maps.invokeApplication(APP_TYPE_CALENDAR.PhoneArguments). Invoke. browser. See “Open the address book from your BlackBerry Java Application” on page 172 for more information. new MessageArguments( MessageArguments.APP_TYPE_MESSAGES: a constant parameter • MessageArguments: a new MessageArguments object that uses the ARG_NEW_SMS parameter Start the message application and create > a new blank message.api.APP_TYPE_MAPS. When the third-party BlackBerry Java Application invokes the BlackBerry device application. Task Steps Invoke the invokeApplication() method with the following parameters: • Invoke.invokeApplication(APP_TYPE_PHONE. See the API Reference for more information about using the net. > > > Invoke Invoke. Related topics • See “Start the media player from the BlackBerry Browser” on page 48 for more information.Invoke class to invoke BlackBerry device applications. Invoke.APP_TYPE_MESSAGES. See “Start the task application from your BlackBerry Java Application” on page 178 for more information. Invoke invokeApplication() using a new MapsArguments object. new MapsArguments() ). CalendarArguments) Invoke Invoke. Start the maps application and display the default map view.invokeApplication(Invoke. the third-party BlackBerry Java Application can make the BlackBerry device application perform an action or display information.10 Integrating with BlackBerry applications Invoke BlackBerry applications Invoke BlackBerry applications You can create BlackBerry® Java® Applications that invoke BlackBerry device applications such as the email. See “Create new messages” on page 157 for more information. Start the phone application.rim. calendar.ARG_NEW_SMS)).blackberry.invokeApplication( Invoke.invoke. • • • • • • See “Start the media player with no content” on page 49 for more information. . See “Use the BlackBerry Maps application” on page 224 for more information. and camera applications to perform an action or display information. phone. Start the calendar. See “Start the media player with content” on page 49 for more information.

BlackBerry Java Development Environment Development Guide 148 .

currentApplicationDescriptor(). ApplicationManager manager = ApplicationManager.11 Managing applications Application manager Retrieve information about BlackBerry Java Applications Register BlackBerry Java Applications when the BlackBerry device starts Communicate with other BlackBerry Java Applications Determine the services that are available to BlackBerry Java Applications Listen for changes to IT policies Application control Managing code modules The runtime store Share runtime objects Code sample Application manager The BlackBerry® JVM on BlackBerry devices includes an application manager that functions as the central dispatcher of operating system events for other BlackBerry Java® Applications. Retrieve a description of the current BlackBerry Java Application. .getName().getVisibleApplications().getApplicationManager(). running. The net.device. Steps > Invoke ApplicationManager. such as retrieving the IDs for foreground BlackBerry Java Applications post global events to the system run a BlackBerry Java Application immediately or at a specific time Retrieve information about BlackBerry Java Applications Task Retrieve information about the processes that are running. the BlackBerry Java Applications that are String appname1 = descriptors[0].getVisibleApplications().system.getName(). Retrieve descriptions of the objects for > Invoke ApplicationDescriptor. ApplicationDescriptor descriptors[] = manager.rim. > Invoke ApplicationDescriptor.currentApplicationDescriptor(). ApplicationDescriptor descriptor = ApplicationDescriptor.api.ApplicationManager class lets BlackBerry Java Applications interact with the application manager to perform the following actions: • • • interact with processes.

8. In the BlackBerry® Integrated Development Environment. In the Arguments passed to field.} } Communicate with other BlackBerry Java Applications > ApplicationManager. allowing the BlackBerry Java Application to perform any one-time initialization.length > 0 && args[0].postGlobalEvent() To post a system-level event to other BlackBerry® Java® Applications. 5. Perform initializations at the alternative > In your main() method. the network gateway. and then click Properties.api. type autostartup. 3. public static void main (String[] args) {if ( args.BlackBerry Java Development Environment Development Guide Register BlackBerry Java Applications when the BlackBerry device starts To register the event source when the BlackBerry® device starts. 7. Click OK. > To let your BlackBerry Java® Application interact with the BlackBerry Infrastructure. click Alternate CLDC Application Entry Point. Task Retrieve information about the processes that are running. click the alternate entry point project. Select the System module option. 150 .device. use the service book API (net. 4. create a separate project that acts as an alternative entry point to the main BlackBerry Java® Application. perform the required initialization. Right-click the project. //Perform any necessary one-time automatic initialization. invoke one of the methods. Select the Auto-run on startup option. 9. each of which defines a service on a BlackBerry® device. 2. create a project. this project automatically runs as a system module and passes an argument to the BlackBerry Java Application. and the configuration information such as browser settings. In the Alternate entry point drop-down list. Steps 1. Service records define the communication protocol (WAP or IPPP). 6. For example: entry point. When the BlackBerry device starts. Click the Application tab. Determine the services that are available to BlackBerry Java Applications The service book consists of service records. In the Project type drop-down list. You cannot pass arguments to MIDlet BlackBerry Java Applications when the BlackBerry device starts.rim.servicebook).equals("autostartup")) { //Application runs as a system module at startup. } else { //Application is being run by a user.

See “Code sample: Listening for changes to IT policies” on page 154 for more information.println( "The user saved more restrictive settings" ). For example. 3. if( ApplicationPermissionsManager.addPermission( ApplicationPermissions. or more permissive settings" ). 2. 151 . Create an instance of the ApplicationPermissions class. Note: The BlackBerry® Application Control IT policy works only when the BlackBerry device and a BlackBerry Enterprise Server are connected.PERMISSION_EVENT_INJECTOR ). Set the build request to ask for event injection privileges. This IT policy does not apply to BlackBerry devices that use only the BlackBerry Internet Service. system administrators can use the BlackBerry Application Control IT policy to make sure that a game that exists on the BlackBerry device cannot access the phone API. Steps > > Implement the GlobalEventListener interface. Allow a BlackBerry Java Application to request access to resources 1.eventOccurred().system package.rim. use the CodeModuleManager class in the net. Identify changes in IT policies.invokePermissionsRequest( permissions ) ) { System. Application control The BlackBerry® Application Control IT policy rules provide administrators with the ability to establish the capabilities of a BlackBerry Java® Application when it runs on a specific BlackBerry device.out. Determine the access control settings that the BlackBerry® device user set.out.api.getInstance(). Implement GlobalEventListener.println( "The user saved equal. } else { System.device. } Managing code modules To retrieve information about and manage code modules on the BlackBerry device. ApplicationPermissions permissions = new ApplicationPermissions(). permissions.11: Managing applications Listen for changes to IT policies Task Enable a BlackBerry Java Application to use IT policies.

getModuleCodeSize( handle ). int version = CodeModuleManager.length ). > Invoke saveNewModule(int). 152 . int handle = CodeModuleManager. String name = CodeModuleManager. int). String description = CodeModuleManager. If the module saves successfully. Save a module to the BlackBerry® device database.writeNewModule( handle.getModuleHandles().saveNewModule(handle). Invoke createNewModule(int. and provide the name of the code module as a parameter. > Invoke writeNewModule() and provide a byte array of data as a parameter to this method. int result = CodeModuleManager.getModuleHandle("test_module"). Steps > > Invoke createNewModule() and provide the size of the module in bytes as a parameter. Boolean success = CodeModuleManager. int size = CodeModuleManager. Retrieve specific information about a module. String name = CodeModuleManager. > Create code modules Task Create a module without data. int handles[] = CodeModuleManager.getModuleName( handle ). data. byte[]. Create a module with data. as long as you know the offset at which to add data.createNewModule( 3000 ). Invoke the methods of the CodeModuleManager class. You can write data into a code module in increments.BlackBerry Java Development Environment Development Guide Retrieve module information Task Retrieve a handle for a module. data. String vendor = CodeModuleManager. Retrieve an array of handles for existing modules on a BlackBerry device Invoke getModuleHandles().getModuleVendor( handle ).getModuleVersion( handle ). int timestamp = CodeModuleManager. the method returns one of the result codes defined in the CodeModuleManager class. and provide the module handle as a parameter to these methods.getModuleName( handles[0]). byte[]. Steps > > Invoke getModuleHandle(). static int createNewModule(int.getModuleTimestamp( handle ). 0. int). Write data into a module. providing the following parameters: • the length in bytes of the entire module • the byte array to add to the module • the length parameter to specify the number of bytes from the byte array to add to the start of the module. int handle = CodeModuleManager.getModuleDescription( handle ).

getModuleHandle("test_module").put(long. } 153 . By default. String) and provide as parameters a unique long ID and the runtime object to store. Invoke RuntimeStore. // Create an object and a unique number to identify the object. 2. RuntimeStore store = RuntimeStore. Contact RIM for information on how to control access to your data. true ). RuntimeStore store = RuntimeStore. The runtime store is not persistent.getRuntimeStore(). if( handle != 0 ) { Boolean success = CodeModuleManager. Share runtime objects Task Retrieve the runtime store. try { store.deleteModule( handle.getRuntimeStore().put( ID.an object with the same ID exists. } catch(IllegalArgumentException e) { // Handle exception .catch block to manage the IllegalArgumentException that put() throws if a runtime object with the same ID exists. Invoke RuntimeStore. Create a try . A BlackBerry device restart clears the data in the runtime store. msg ). } If the module is in use. only BlackBerry Java Applications that Research In Moton (RIM) digitally signs can access data in the runtime store. Add a runtime object. 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. long ID = 0x60ac754bc0867248L. int handle = CodeModuleManager. Steps > Invoke deleteModuleEx(int.11: Managing applications Task Delete a module from the BlackBerry® device database.getRuntimeStore(). deletes it when the BlackBerry device restarts. Steps > 1. The runtime store BlackBerry® devices use a runtime store as a central location in which BlackBerry Java® Applications can share runtime objects. String msg = "Some shared text".

catch block to manage the ControlledAccessException that get() throws if the BlackBerry® Java® Application does not have read access to the specified runtime object. } catch(ControlledAccessException e) { // Handle exception .replace( 0x60ac754bc0867248L.waitFor() to wait for registration of a runtime object to complete.getRuntimeStore(). null // otherwise. } 2.getRuntimeStore(). Create a try .waitFor(0x60ac754bc0867248L). try { // get() returns the object with the specified ID if it exists. waitFor() blocks for a maximum of MAX_WAIT_MILLIS. } not exist. Invoke RuntimeStore. 2. newmsg). Object obj = store. Create code for handling exceptions.BlackBerry Java Development Environment Development Guide Task Replace a runtime object.java /** * ITPolicyDemo.get(0x60ac754bc0867248L). If the runtime object with the specified ID does not exist.insufficient permissions. Create a try .catch block to manage the ControlledAccessException that replace() throws if the runtime object with the specified ID does not exist. } Retrieve an unregistered runtime object. } catch(ControlledAccessException e) { // Handle exception . try { Object obj = store. Retrieve a registered runtime object. 1.insufficient permissions. Code sample Code sample: Listening for changes to IT policies Example: ITPolicyDemo. 1.java * Copyright (C) 2002-2005 Research In Motion Limited.getRuntimeStore(). Invoke replace(). Steps 1. RuntimeStore store = RuntimeStore. 2. RuntimeStore store = RuntimeStore.time out.get() and provide as a parameter the runtime object ID. String newmsg = "Some new text". RuntimeStore store = RuntimeStore. Invoke RuntimeStore. } catch(ControlledAccessException e) { // Handle exception. } catch(RuntimeException e) { // Handle exception . try { Object obj = store. */ 154 .

11: Managing applications package com. int data1.out.addGlobalEventListener(this).exit(0).*.api.docs. boolean appEnabled = ITPolicy. Object obj1) { if (guid == ITPolicy.system.device. System.itpolicy.getBoolean(“DemoAppEnabled”. boolean appEnabled = ITPolicy.rim. import net. int retries = ITPolicy.getBoolean(“DemoAppEnabled”. } public void eventOccurred(long guid.enterEventDispatcher().*. import net. app.GUID_IT_POLICY_CHANGED ) { String security = ITPolicy. Object obj0.println(“App Enabled: “ + appEnabled). public class ITPolicyDemo extends Application implements GlobalEventListener { public static void main(String[] args) { ITPolicyDemo app = new ITPolicyDemo().getInteger(“DemoAppRetries”.getString(“DemoSecurityLevel”).device.rim.itpolicy. true).rim. } ITPolicyDemo() { this. System. } } } 155 . 10).samples. true).api. int data0.

BlackBerry Java Development Environment Development Guide 156 .

invokeApplication(Invoke. 1. Invoke. m.open( "sms://" ). m. > Invoke invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW parameter. Steps > Invoke invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_SMS parameter.APP_TYPE_MESSAGES.APP_TYPE_MESSAGES. new MessageArguments( m ) ). Create and populate a new TextMessage object. > Invoke invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_MMS parameter. Invoke invokeApplication() with the following parameters: • APP_TYPE_MESSAGES: a constant parameter • MessageArguments: a new MessageArguments object that uses the new TextMessage object.messaging package (JSR 120).TEXT_MESSAGE ).ARG_NEW)). 2. new MessageArguments( MessageArguments.newMessage( MessageConnection. Create a new blank email message. Use the API items in the javax.setAddress( "sms://5558888" ).ARG_NEW_SMS)). Invoke. MessageConnection mc = (MessageConnection)Connector. TextMessage m = (TextMessage)mc.ARG_NEW_MMS)). .setPayloadText( "An SMS Message for you" ).invokeApplication(Invoke.invokeApplication(Invoke.invokeApplication( Invoke.wireless.APP_TYPE_MESSAGES.12 Using the messages application Create new messages Work with a message Work with folders Working with attachments Create new messages Task Create a new blank text message. Invoke. Create a new text message with multimedia. new MessageArguments( MessageArguments. Create a new populated text message. new MessageArguments( MessageArguments.APP_TYPE_MESSAGES. Invoke.

Message m = new net.invokeApplication(Invoke.setSubject("Email for you"). > Invoke invokeApplication() using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses the ARG_NEW_PIN parameter.addRecipients(net..mail.setSubject("PIN message for you").rim. 1. Invoke invokeApplication() with the following parameters: • APP_TYPE_MESSAGES: a constant parameter • MessageArguments:a new MessageArguments object that uses the new PIN message. m.APP_TYPE_MESSAGES.blackberry.setContent("A message for you.Message(). m. net.Message(). addresses). Invoke invokeApplication()with the following parameters: • APP_TYPE_MESSAGES: a constant parameter • MessageArguments: a new MessageArguments object that uses the new email Message object. new MessageArguments(m)). PINAddress pa = new PINAddress("ABCDEF99". net. Create a new populated email message. addresses ).TO.com". Invoke. "Ming Li"). "Mark Chapters").invokeApplication(Invoke. Create a new populated PIN message. m.mail.invokeApplication(Invoke.blackberry.api.api. 1.api.rim. 158 .Message. Address a = new Address("mLi@rim.mail.ARG_NEW_PIN)).Message m = new net. m..APP_TYPE_MESSAGES. new MessageArguments( MessageArguments..setContent("A message for you. Invoke. m.rim.api.BlackBerry Java Development Environment Development Guide Task Steps Create and populate a new email message object. Address[] addresses = {a}.blackberry.TO .RecipientType.mail.mail. 2.APP_TYPE_MESSAGES.rim.rim."). Create a new blank PIN message. Invoke.blackberry.api.addRecipients( net.RecipientType. new MessageArguments(m)).blackberry.. Create and populate a new PIN message. 2.api. m.Message. Address[] addresses = {pa}.rim.mail.blackberry.").

2.addStoreListener(this)..addFolderListener(this).getUnreadMessageCount(). } Add a listener to a folder. public class MailTest implements FolderListener. Add a listener to the message store.12: Using the messages application Work with a message Task Receive a message notification.Store. } Retrieve the total count of unread messages in all folders in the store.getStore(). StoreListener { .waitForDefaultSession().rim. 159 . } store.mail. Add a StoreListener instance to it.list(Folder. 3. Retrieve the Store object. } void messagesRemoved(FolderEvent e) { // Perform processing on removed messages. 1. 1. } catch (NoSuchServiceException e) { System.. 3. > Invoke net. void messagesAdded(FolderEvent e) { // Perform processing on added messages.blackberry. > Implement StoreListener. } 2. try { Store store = Session. 2. Folder[] folders = store.INBOX).messagesAdded() and FolderListener.toString()).println(e. Create a try-catch block to manage a NoSuchServiceException.getUnreadMessageCount(). Steps 1. void batchOperation(StoreEvent e) { // Perform action when messages added or removed in batch operation. Implement FolderListener. Retrieve the Folder object for which you want to receive new message notifications.batchOperation().out. int numUnread = store. inbox. Create code to manage a ControlledAccessException. Implement the FolderListener and StoreListener interfaces.api.messagesRemoved(). Folder inbox = folders[0]. Add a listener to the message store for batch updates. Add the FolderListener instance to the folder.

true).more(tb.moreRequestSent(). the first section of a message (typically about 2 KB) is sent to the BlackBerry® device. 4. To request more of a message.moreRequestSent()) {trans. Steps By default. invoke tb. if (( tb. 5. Transport trans = Session.hasMore() ) && (! tb.getTransport() and store the returned object in a variable of type Transport. To determine if the BlackBerry device user made a request for more data.BlackBerry Java Development Environment Development Guide Task Get more of a message. 3. Create an instance of a subclass of the BodyPart abstract class. 2. TextBodyPart tb = new TextBodyPart(new MultiPart()). invoke tb. boolean reqAll).} 160 . The second parameter of more() is a Boolean value that specifies whether to retrieve only the next section of the body part (false) or all remaining sections of the body part (true).more(BodyPart bp. invoke Session. invoke trans. 1. To determine if more data for a body part is available on the server.getTransport().hasMore(). To obtain a Transport object.

Steps 1. to display to the BlackBerry® device user.println(e. Create code to catch an AddressException. Retrieve the message store and the folder that contains the message. Iterate through the array and retrieve information.out. } 161 .. // Retrieve the first message.getFrom(). Object o = msg.com".12: Using the messages application Open a message 1.} //. 3. Address[] recipients = msg. Message msg = new Message(sentfolder). Store store = Session..getRecipients(Message.waitForDefaultSession. Store store = Session. Message[] msgs = folder. Add each address to the array. Send a message Task Create a message. Create a Message object. // Verify that the message is not multipart.list(Folder. Invoke getBodyText() on a message to retrieve the plain text contents as a String. 2. which is thrown if an address is invalid. 4. Retrieve the message objects from the folder. If the message does not contain plain text. Create an array of Address objects. Specify the recipients. String subject = msg.getStore().getSubject().wahl@blackberry. } catch(AddressException e) { System. invoke methods on the Message object to retrieve the appropriate fields and body contents to display to the BlackBerry device user. Folder sentfolder = folders[0].TO) Date sent = msg. Folder[] folders = store. the method returns null. When a BlackBerry device user selects a message from the list. if ( o instanceof String ) { String body = (String)o.getFolder("SampleFolder"). "Aisha Wahl"). Address from = msg.getDefaultInstance(). 1. such as the sender and subject. 2.getStore(). Folder folder = Store. Message msg = msgs[0].getContent().SENT). Address toList[] = new Address[1].getSentDate(). 3. Specify a folder in which to save a copy of the sent message.toString()). 2.getMessages(). try { toList[0]= new Address("aisha.RecipientType.

getTransport(). Address from = new Address("scott. "Scott McPherson"). If the message has multiple types of recipients.out. 2.setContent("This is a test message.waitForDefaultSession(). 2.com".getMessage()). } catch(MessagingException e) { System. msg. Transport trans = Session. } Reply to a message Task Reply to an existing message. Invoke Session. Steps 1.BlackBerry Java Development Environment Development Guide Task Add the recipients.RecipientType. Invoke trans.send(msg).setSubject("Test Message"). Folder[] folders = store. Message[] messages = inbox. Add a subject line.getStore(). CC.addRecipients(Message.reply(Boolean) and specify true to reply to all message recipients or false to reply to only the sender.list(INBOX). the BlackBerry® Java® Application retrieves content from text that a BlackBerry device user types in a field. invoke addRecipients() once for each recipient type. or BCC) and the array of addresses to add as parameters to the method. } catch(MessagingException e) { System. Store store = Session. 1.getMessages(). Invoke Session. } Send the message. Transport trans = Session. the sender. msg.reply(true). Specify the message contents.addRecipients() and provide the type of recipient (TO. if( messages.send(Message). Typically. > > Invoke setSubject(String).println(e."). Steps 1. try { trans. msg. Invoke Message. Folder inbox = folders[0]. The Transport object represents the messaging transport protocol.setFrom(from). try { msg.TO. } Message reply = msg.getMessage()).out.mcpherson@blackberry. Invoke setContent(String).getTransport() and store the returned object in a variable of type Transport. trans. 162 .println(e. The Transport object represents the messaging transport protocol. > Invoke Message.getTransport() and store the returned object in a variable of type Transport. toList). Specify the name and email address of > Invoke setFrom(Address).length > 0 ) { Message msg = messages[0].getTransport().send(reply).

The Transport object represents the messaging transport protocol.invokeApplication(Invoke.12: Using the messages application Forward a message Task Create a message object.getTransport().send(fwdmsg).println(e.getMessage()). > Invoke Store. try { fwdmsg. 2. Invoke. Create an array of addresses. Message fwdmsg = msg.out. new MessageArguments( folders[0])).APP_TYPE_MESSAGES. store = Session. Add the recipients. "Katie Laird"). Steps 1.RecipientType. Invoke addRecipients(int. } catch(MessagingException e) { System. } Send the message.list().waitForDefaultSession(). toList[0]= new Address("aisha. try { trans. fwdmsg. } Work with folders 1.list(). Folder[] folders = store. 2.getStore(). Address[]). 1.forward(). Store store = null. Invoke store. Invoke trans. Address toList[] = new Address[1].list().getStore(). Store store = Session. Invoke invokeApplication()using the APP_TYPE_MESSAGES constant parameter and a new MessageArguments object that uses a folder from the list of folders as a parameter.getMessage()). The subject line of a forwarded message is set automatically to FW:original_subject.getTransport() and store the returned object in a variable of type Transport. 2. Transport trans = Session.out.list() to retrieve a list of folders.TO. } catch(MessagingException e) { System. Folder[] folders = store.println(e. Specify that the message content appears before the original message. 163 . toList). Complete any of the following actions: Task Open a folder view. Steps > Invoke forward() on an existing Message object. > Invoke setContent(String).send(Message). 2. Invoke Session. 1."). Invoke getStore() on the default session.setContent("This is a forwarded message. List the folders in a mailbox store.addRecipients(Message.waitForDefaultSession().com".wahl@blackberry.

> Invoke appendMessage(Message) on a Folder object. type. folder.getFolder(id).findFolder("Inbox"). Folder[] folders = store. File a message. Create code to manage a FolderNotFoundException exception if the folder does not exist.list(INBOX).getId(). Folder inbox = folders[0]. Message msg = new Message(). 1. Retrieve a folder by its name. 2.appendMessage(msg). Folder[] folders = store. 1. Folder f2 = store.getFolder("Mailbox . Folder folder = store. Invoke getFolder() with the ID as a parameter. Retrieve an array of folders through a search. 2. > Invoke findFolder(String). Invoke getFolder(String) and provide as a parameter the absolute path to the folder.getFolder("Inbox"). 164 . Folder[] folders = store.list().. Retrieve a folder by its ID. //.Aisha Wahl/Inbox/Projects"). long id = folders[0]. Folder folder = store. Invoke getID() to retrieve the folder ID..BlackBerry Java Development Environment Development Guide Task Steps Retrieve an array of folders by > Invoke list(int) and provide as a parameter the folder type.

Screen view = new Screen(). this action invokes the run()method. See the BlackBerry Enterprise Server Maintenance and Troubleshooting Guide for more information about the BlackBerry Enterprise Server Attachment Service. Define attachment processing. use the mail API.toLowerCase().setTitle(new LabelField("Attachment Viewer")). public boolean supports(String contentType) { return (contentType.getInstance(). Create an attachment handler The BlackBerry® Enterprise Server Attachment Service receives all attachments first. CustomAttachmentHandler ah = new CustomAttachmentHandler(). SupportedAttachmentPart p) { // Perform processing on data. String s = new String((byte[])p.getContent()))).addAttachmentHandler(ah). public void run(Message m.add(new RichTextField(new String((byte[])p. Steps > > Implement the AttachmentHandler interface. } Register an attachment. view. When registering a custom attachment handler. } Define the associated menu item string to display in the messages list when the BlackBerry® device user selects an attachment. m. public String menuString() { return "Custom Attachment Viewer". > Implement menuString(). Third-party attachment handlers cannot override the default BlackBerry device behavior. Task Define a custom attachment handler. AttachmentHandlerManager m = AttachmentHandlerManager. > 165 .indexOf("contenttype") != -1 ? true : false). A separate BodyPart on a Multipart message represents a message attachment.getContent(). } > Implement run(). the attachment name must be prefixed with "xrimdevice" for the attachment to be sent and stored on the BlackBerry® device. Retrieve attachments Task Steps Invoke SupportedAttachmentPart. view. Register the accepted MIME types when the BlackBerry® device receives an attachment.addAttachmentHandler(). When a BlackBerry® device user selects a menu item from the messages list.getContent()). Retrieve the contents of an attachment. > Invoke AttachmentHandlerManager.12: Using the messages application Working with attachments To open incoming message attachments and create outgoing attachments on the BlackBerry® device. Implement supports(String).

Invoke Session.addBodyPart(attach). byte[] data = new byte[256]. Invoke trans. 2.send(msg). > > Invoke addBodyPart(SupportedAttachmentPart) on that object. try { trans. An UnsupportedAttachmentPart represents an attachment that does not have a viewer on the BlackBerry device. } 166 . Send the message. // The attachment. "application/x-example". msg. } catch(MessagingException e) { System. // Add the attachment to the multipart. multipart. MultiPart multipart = new MultiPart(). Steps > Invoke the methods of the SupportedAttachmentPart class. // Default type of multipart/mixed. Invoke setContent(Multipart) on the Message object and provide as a parameter the Multipart object. "filename". > Create a SupportedAttachmentPart object. designating the Multipart object as its parent.getTransport(). data). Set the content of the attachment.out. SupportedAttachmentPart attach = new SupportedAttachmentPart( multipart.getTransport() and store the returned object in a variable of type Transport.println(e. The SupportedAttachmentPart class represents an attachment with a corresponding viewer on the BlackBerry® device. 1. Steps > Create a new Multipart object.send(Message).setContent(multipart).getMessage()). Send a message with an attachment Task Create a multipart message. The Transport object represents the messaging transport protocol.BlackBerry Java Development Environment Development Guide Task Retrieve information about the attachment. Transport trans = Session. Add each SupportedAttachmentPart object to the multipart object. Create each component of the attachment.

getInstance(). 2.items(). Invoke Invoke.13 Using PIM applications Using the calendar Using the address book Using tasks Code samples Using the calendar Start the calendar from your BlackBerry Java Application Task Open the calendar. CalendarArguments). PIM.nextElement().EVENT_LIST. View or change an event. Steps > 1. new CalendarArguments( CalendarArguments.READ_WRITE ). EventList el = (EventList)PIM. Retrieve an Event from the list of events.openPIMList( PIM. CalendarArguments) using the CalendarArguments object created using the ARG_VIEW_DEFAULT property and the retrieved Event. Enumeration events = el. e = (Event)events.invokeApplication( Invoke.APP_TYPE_CALENDAR. Event e = null. Invoke Invoke. e ) ). Manage exceptions > Check for a ControlledAccessException if your BlackBerry® Java® Application invokes a BlackBerry application that you do not have permission to use or access. .invokeApplication(APP_TYPE_CALENDAR. Invoke.invokeApplication(APP_TYPE_CALENDAR.ARG_VIEW_DEFAULT.

providing as parameters the type of list to open (PIM.createEvent(): 168 .READ_WRITE). Invoke Invoke. } catch (PimException e) { // Handle exception. e ) ).openPIMList( PIM.openPIMList( PIM. try { eventList = (EventList)PIM. EventList el = (EventList)PIM. 4.EVENT_LIST) and the mode in which to open the list: • READ_WRITE • READ_ONLY • WRITE_ONLY EventList eventList = null. e = el.EVENT_LIST. Steps 1.addDate( Event. 0. 2. new CalendarArguments( CalendarArguments.END. Event e = null. e. 0. For each event.currentTimeMillis() + 8640000. start and end times.ARG_NEW.START.APP_TYPE_CALENDAR. long start = System.READ_WRITE ). e.addDate( Event. Use the calendar Task Open an event list.addString( Event. 3.LOCATION. start ). } Create an appointment. e.BlackBerry Java Development Environment Development Guide Task Open a new populated event.SUMMARY. Invoke. PIM. "The Park" ).getInstance().invokeApplication(APP_TYPE_CALENDAR. Create one or more Event objects to store information for specific appointments. you can store data such as the summary. > Invoke createEvent() on an event list. Use an instance of the EventList class to access the calendar. Add information to the Event object. start + 72000000 ). "Go For A Walk" ). Event event = eventList. location. and reminder notification. 5. e. 0. Steps > Create an EventList object by invoking openPIMList().getInstance().EVENT_LIST. 0. CalendarArguments) using the CalendarArguments object created using the ARG_NEW property and the Event. Create a new Event using an EventList object.createEvent().invokeApplication( Invoke.addString( Event. PIM.

ATTR_NONE.START.ALARM)) { if (event.READ_WRITE).currentTimeMillis() + 8640000). "Meet with customer"). Event. Event.EVENT_LIST. Event event = eventList.setInt(RepeatRule. invoke isSupportedField(int).isSupportedField(Event.addDate(Event. To retrieve an array of supported fields. Steps > To verify that an item supports a field. Event. Event. To replace an existing value with a new one. To change an existing value.SUMMARY.FREQUENCY. 0.START)) { event.addString(Event. invoke setRepeat(RepeatRule) on an event. int) or setDate(int. if (event.ATTR_NONE. event. 3. The RepeatRule class defines fields for the properties and values that you can set.13: Using PIM applications Task Add appointment information. int.addDate(Event. To define a recurring pattern. } Date start = new Date(System.LOCATION. if (event. To determine if a value is already set for the field. 14). 1. use the corresponding set method.setInt(Event.removeValue(Event. such as COUNT.isSupportedField(Event. "Board Room"). RepeatRule recurring = new RepeatRule(). such as setString().LOCATION)) { event. start + 72000000).isSupportedField(Event. Change appointment information. long) on a new RepeatRule object. invoke countValues().LOCATION.ATTR_NONE. } 169 .openPIMList( PIM.SUMMARY)) { event. event. } } Create a recurring appointment. int. Event. To assign a recurrence pattern to an appointment. 2. 2. and INTERVAL.setRepeat(recurring). "Conference Center"). recurring.createEvent().LOCATION) > 0) { event. 4.END. 3.ATTR_NONE.0). 1. PIM.getFields().ALARM.isSupportedField(Event. recurring.ALARM. 396000). invoke RepeatRule. invoke setInt(int.addString(Event. } if (event.isSupportedField(Event. invoke the appropriate set method.ATTR_NONE.END)) { event. } if (event.getInstance(). } if (event.setInt(RepeatRule. start). Event.countValues(Event. if (event.ALARM) > 0) { event. EventList eventList = (EventList)PIM.setString(Event.MONTHLY). FREQUENCY. 0.countValues(Event. Create a RepeatRule object. RepeatRule.DAY_IN_MONTH. such as setString().ATTR_NONE.

1.toSerialFormat(event.items(). EventList eventList = (EventList)PIM. j < event. PIM. } 170 .commit().isModified()) { event. To retrieve an array of IDs of fields that have data for a particular task. 3. index < fieldIds. Enumeration e = eventList.getString(id. PIM. while (e. 3. for(int index = 0.openPIMList( PIM. To retrieve the field values. if(e. Before you save the appointment. use the importEvent() method.getFields(). To write an item in serial format. dataFormats[0]).READ_ONLY).BlackBerry Java Development Environment Development Guide Task Save an appointment. invoke PIM. This parameter cannot be null.items().READ_ONLY ). and then specify the list type (PIM. "UTF8". PIM. ByteArrayOutputStream bytestream = new ByteArrayOutputStream(). The enc parameter specifies the character encoding to use when writing to the output stream. 1.getInstance(). invoke PIMList. To retrieve an enumeration of appointments.” “ISO-8859-1.println(event. To import or export PIM item data.out. you do not have to invoke commit(). Invoke commit().EVENT_LIST. 1.getString().” and “UTF-16BE”.nextElement(). 2.hasMoreElements()) { Event event = (Event)e.supportedSerialFormats(). int[] fieldIds = event. if(event.openPIMList( PIM. such as iCal®.length. invoke PIMItem. } Retrieve appointment information. Enumeration e = eventList. invoke isModified().getInstance().getFieldLable(id) + "=" + value). int id.hasMoreElements()) { Event event = (Event)e. EventList eventList = (EventList)PIM.getFields(). use an output stream writer to export tasks from the BlackBerry® device to a supported serial format.EVENT_List). } } } } Export an appointment. To retrieve a string array of supported serial formats. ++index) { id = fieldIds[index]. Supported character encodings include “UTF8. Steps To save an appointment. to identify appointment fields that have changed since the appointment was last saved. System.getPIMList().nextElement().countValues(id). invoke toSerialFormat(). 2.getFieldDataType(id) == STRING) { for(int j=0. 2.getInstance(). j). invoke PIMItem. ++j) { String value = event. while (e. byteStream.EVENT_LIST.items().

lang.getInstance(). "UTF8"). PIM.getInstance(). PIMItem[] pi = PIM. "UTF8".EVENT_LIST. Close an event list. To add a new appointment. os. 1.toSerialFormat(event. Event event2 = eventList.close().openPIMList( PIM.io.importEvent(). EventList eventList = (EventList)PIM. invoke EventList. 171 . ByteArrayOutputStream os = new ByteArrayOutputStream(). // Write appointment to iCal. // Convert an existing appointment into a iCal and then import the iCal as a new // appointment.fromSerialFormat(is. Invoke close(). try { eventList.InputStream is. // Import appointment from iCal. PIM.toByteArray()). ByteArrayInputStream is = new ByteArrayInputStream(outputStream. } See “Code sample: Creating new recurring appointments” on page 182 for more information.importEvent((Event)pi[0]). 2.eventSerialFormats(). } catch (PimException e) { // Handle exception.READ_WRITE). invoke from SerialFormat(java. Create a try-catch block to manage a PimException. java. Steps 1.13: Using PIM applications Task Import an appointment. String[] dataFormats = PIM.String enc).getInstance(). dataFormats[0]). To return an array of PIMItem objects. 2.

Open a contact using PIM data. try { contactList = (ContactList)PIM. invoke Invoke. Invoke. Create an instance of an AddressBookArguments object. ContactList contactList = null. > 1. Manage exceptions.USER2 • BlackBerryContact. READ_ONLY. } catch (PimException e) { return. Contact contact).CONTACT_LIST) and the access mode with which to open the list (READ_WRITE.openPIMList( PIM.invokeApplication(APP_TYPE_ADDRESSBOOK.CONTACT_LIST. } 172 .USER1 • BlackBerryContact. Invoke PIM. Use contacts Task Provide access to the PIN BlackBerry® device contacts field.openPIMList() and provide as parameters the type of list to open (PIM. Steps > From a BlackBerry® Java® Application. Use the following constants: • BlackBerryContact. PIM. > Check for a ControlledAccessException if your BlackBerry® Java® Application invokes a BlackBerry application that you do not have permission to use or access. 2. or WRITE_ONLY).getInstance(). AddressBookArguments) using the AddressBookArguments object for the contact.invokeApplication(APP_TYPE_ADDRESSBOOK.USER3 • BlackBerryContact. Steps > > Use the BlackBerryContact.BlackBerry Java Development Environment Development Guide Using the address book Open the address book from your BlackBerry Java Application Task Open the address book. 2. Define labels for the USER1 through USER4 BlackBerry® device contacts fields. Changing a label affects all contacts on the BlackBerry device. Invoke Invoke.invokeApplication(APP_TYPE_ADDRESSBOOK. 1. specifying as a parameter a Contact object. abArg). Create a contacts list.USER4 Invoke BlackBerryPIMList.READ_WRITE). Provide access to the USER1 through USER4 BlackBerry® device contacts fields.setFieldLabel().AddressBookArgum ents).PIN constant. Open a contacts list. AddressBookArguments abArg = AddressBookArguments(String arg.

Contact contact = contactList. > Invoke createContact() on a contact list. you must commit it. Steps To add a contact to the database. 173 . See “Save a contact” on page 173 for more information about committing contact data.13: Using PIM applications Task Create a contact.createContact().

to verify that the item supports the field.WRITE_ONLY). invoke isSupportedAttribute(int. To let fields store multiple values.TEL. the TEL field supports the ATTR_HOME. 4. Before you set or retrieve a field. "555-5555").} catch (IllegalArgumentException iae) {// Handle exception.isSupportedField(Contact. Invoke one of the following methods: • • • • • • addString() addStringArray() addDate() addInt() addBoolean() addBinary() 2.isSupportedAttribute(Contact. Contact.} catch (PIMException e) {} Contact contact = contactList.ATTR_HOME.TEL.NAME)) {contact.isSupportedField(Contact.addString(Contact.address[Contact. int). use field attributes. try {ContactList contactList = (ContactList)PIM.ADDR_LOCALITY] = "Los Angeles".stringArraySize(Contact.ADDR_POSTALCODE] = "632300".wahl@blackberry.} 174 . // Add home telephone number.NAME_PREFIX] = "Mr. Contact.String[] name = new String[contactList.EMAIL)) {contact.isSupportedField(Contact. // Create string array for name. "aisha. name). address). and fax numbers.} // Add work internet messaging address.addString(Contact. mobile.} // Add work telephone number.CONTACT_LIST. 5.NAME)].maxValues(int field). } // Create string array for address. if (contactList.ATTR_NONE. Contact.". Contact.NAME_GIVEN] = "Scott".address[Contact. and ATTR_FAX attributes to store numbers for work. ATTR_MOBILE.ADDR. To verify that a field supports a particular attribute. Contact.} // Add address.NAME_FAMILY] = "McPherson". PIM. invoke PIMList.contact.TEL.ADDR_STREET] = "323 Main Street".ATTR_NONE. invoke ContactList.address[Contact. Contact.BlackBerry Java Development Environment Development Guide Task Add contact information.if (contactList.TEL) &&contactList. "555-1234"). home.name[Contact. if(contactList. ATTR_WORK. Steps 1. To determine how many values a field supports.ATTR_WORK.} catch (IllegalArgumentException iae) {// handle exception} // Add name.addStringArray(Contact. String[] address = new String[7].ADDR_COUNTRY] = "United States".createContact().isSupportedField(Contact.address[Contact.ATTR_HOME.isSupportedField(int).addStringArray(Contact.NAME. if (contactList.openPIMList(PIM.getInstance(). // 7 address elements try {address[Contact. For example. 3. // 5 name elements try {name[Contact.name[Contact.EMAIL.ADDR_REGION] = "California".ATTR_HOME)) {contact.TEL)) {contact.addString(Contact.com").

isModified()) { contact. retrieve the array and then change one or more indexes in the array before adding the array back to the Contact object. } // Change the prefix to Dr.countValues(Contact.NAME_SUFFIX] = "Jr. Perform one of the following actions: • To change the fields that support a single value.} 3. invoke the appropriate set method to replace an existing value with a new value. such as addString(). if(contact. Create code to manage a FieldFullException. 1. and add the suffix. For example: if (contact. • To change the contacts fields that support multiple values.NAME. Invoke commit(). newname[Contact. } 175 . contact.". if (contact. Save a contact.commit().ATTR_NONE.wahl@blackberry.NAME. newname). 0. before adding another value. Contact.addString(Contact.countValues(Contact. invoke isModified().".com"). 2.NAME_PREFIX] = "Dr. Jr.ATTR_NONE.EMAIL) < contactList. To determine if any contact fields have changed since the contact was last saved. To change the name and address fields. 0).setStringArray(Contact.getStringArray(Contact.NAME) > 0) { String[] newname = contact.13: Using PIM applications Task Change contact information.EMAIL)) { contact. "aisha. Contact. which occurs if you invoke an add method. verify that the number of values does not exceed the maximum number of values. Steps 1. 2.EMAIL.maxValues(Contact. newname[Contact. for a field that already has a value.

for(int index = 0. BlackBerryContactList list = (BlackBerryContactList)PIM. invoke PIMItem. } 176 . Steps 1. 3.out.BlackBerry Java Development Environment Development Guide Task Retrieve contact information.CONTACT_ LIST. int id. ++j) { String value = c.openPIMList(PIM.getString(id. Enumeration enum = contactList.items().items() to retrieve an enumeration of items in a contacts list.EMAIL.nextElement(). ++index) { id = fieldIds[index].READ_WRITE). PIM.println(c.choose(). String email = contact. System.getInstance()..countValues(id).items().getFieldDataType(id) == Contact. > Invoke the BlackBerryContactList.getInstance(). Invoke PIMList. j < c.getFields(). PIMItem item = list.openPIMList( PIM. PIM. } } } } Select a contact from the address book. Perform one of the following actions: • To retrieve an array of IDs for fields that have data for a particular contact.choose() to return a Contact or BlackBerryGroupContact PIMItem.. • To retrieve the field values.hasMoreElements()) { Contact c = (Contact)enum. 2. 0). your BlackBerry® Java® Application must sort items as necessary.getPIMList().CONTACT_LIST.getString(). while (enum.println("Name is: " + email). When you invoke PIMList.STRING) { for(int j=0.getString(Contact. int[] fieldIds = c. invoke PIMItem. ContactList contactList = (ContactList)PIM.READ_WRITE). j).getPIMList(). if(c.length. if (item instanceof Contact) { Contact contact = (Contact)item. System.getFieldLabel(id) + "=" + value). } else if (item instanceof BlackBerryContactGroup) { .getFields() .out. index < fieldIds.

contactList. Delete a contact. use an output stream writer to export tasks from the BlackBerry® device to a supported serial format.Contact_LIST).getInstance().removeContact(contact). The enc parameter specifies the character encoding to use when writing to the output stream. use the enc parameter.getInstance().commit().CONTACT_LIST. 2. 1. "UTF8". To return an array of PIM items. // Import contact from vCard.importContact((Contact)pi[0]). try { contactList. byteStream. 177 . To create a new contact using the PIM item.READ_ONLY).getInstance()." and "UTF-16BE. while (e.nextElement(). ByteArrayOutputStream byteStream = new ByteArrayOutputStream(). ContactList contactList = (ContactList)PIM. } Import a contact. 3. "UTF8"). Supported character encodings include "UTF8. invoke fromSerialFormat().CONTACT_LIST).importContact().close(). > > Invoke removeContact() on a contact list. To import or export PIM item data. invoke toSerialFormat(). 2. PIM. 3.CONTACT_LIST.13: Using PIM applications Task Export a contact. such as vCard®. dataFormats[0]).getInstance(). ContactList contactList = (ContactList)PIM.getInstance(). String[] dataFormats = PIM. PIMItem[] pi = PIM. } catch(PIMException e) { Dialog. To specify the character encoding to use when writing to the output stream. invoke PIM.supportedSerialFormats( PIM. Invoke close(). To retrieve a string array of supported formats.toSerialFormat(c. PIM. To write an item to a supported serial format.openPIMList( PIM. Steps 1. PIM. contact2. ByteArrayInputStream istream = new ByteArrayInputStream(outputStream. Enumeration e = contactList.openPIMList(PIM.supportedSerialFormats() and specify the list type (PIM.toByteArray()).hasMoreElements()) { Contact c = (Contact)e.alert(e." This parameter cannot be null. } See “Code sample: Displaying a screen that lets BlackBerry device users add new contacts” on page 184 for more information.fromSerialFormat(istream.toString()). Close a contacts list." "ISO-8859-1.READ_WRITE). Contact contact2 = contactList.items(). invoke ContactList.

new TaskArguments( TaskArguments.invokeApplication(Invoke. 1.invoke.TODO_LIST. new TaskArguments(TaskArguments. new TaskArguments( TaskArguments.addString(ToDo.READ_WRITE). TaskArguments).APP_TYPE_TASKS. Steps The TaskArguments (net. 1. Invoke createToDo() to create a new ToDo object and add information to the new ToDo object.items(). PIM. 2.invokeApplication(APP_TYPE_TASKS. Create a new populated task.createToDo().openPIMList(PIM.rim.TaskArguments) cannot be updated without changes to the Task application. > Invoke invokeApplication() using the APP_TYPE_TASKS constant parameter. 3.APP_TYPE_TASKS. "Walk the Dog"). Create a new blank task. Task Open the task application. 0.getInstance(). todo)). Invoke invokeApplication() using the APP_TYPE_TASKS constant parameter. todo. 2. 3.nextElement().SUMMARY.APP_TYPE_TASKS.invokeApplication(Invoke. Enumeration todos = tdl. Invoke invokeApplication() using the APP_TYPE_TASKS constant parameter. ToDoList tdl = (ToDoList)PIM. 178 .BlackBerry Java Development Environment Development Guide Using tasks Start the task application from your BlackBerry Java Application Check for a ControlledAccessException if your BlackBerry® Java® Application invokes a BlackBerry application that you do not have permission to use or access. > View or change a task. Invoke.ARG_NEW) ). todo)). and a new TaskArguments object created using the ARG_NEW parameter and the new ToDo object.READ_WRITE). ToDoList tdl = (ToDoList)PIM.getInstance().TODO_LIST. and a new TaskArguments object created using the ARG_NEW parameter. and a new TaskArguments object created using the ARG_VIEW parameter and the ToDo object. Invoke Invoke. Create an instance of a ToDoList and store it in an Enumeration. Create a ToDo object using an element from the Enumeration: ToDo todo = (ToDo)todos. Invoke.blackberry.openPIMList(PIM.api. ToDo todo = tdl.invokeApplication(Invoke. Invoke.ARG_VIEW.ARG_NEW. PIM. Create an instance of a ToDoList.

getFieldDataType(int). 2).addInt(ToDo. To set the field data. > Use the PIM extended field ToDo. ToDo. try { todoList = (ToDoList)PIM.ATTR_NONE.isSupportedField(ToDo.openPIMList() and provide as parameters the type of list to open (PIM. 2. READ_ONLY.PRIORITY)) { task. Steps > Invoke PIM. } catch (PimException e) { //an error occurred return. or WRITE_ONLY).createToDo(). Add task information. } if (todoList.addInt(Todo. 2).ATTR_NONE. "Create project plan"). To retrieve the field data type. invoke PIMList. } if (todoList.PRIORITY.ATTR_NONE.SUMMARY)) { task. 3. ToDo.EXTENDED_FIELD_MIN_VALUE + 9: • STATUS_NOT_STARTED: 1 • STATUS_IN_PROGRESS: 2 • STATUS_COMPLETED: 3 • STATUS_WAITING: 4 task.NOTE.addDate(ToDo. Before you set or retrieve a field.NOTE)) { task. } if (todoList. ToDo.addString(ToDo. > 1.isSupportedField(ToDo.13: Using PIM applications Use tasks Task Open a task list. } Set the status of a task.getInstance(). invoke one of the following methods: • addString() • addDate() • addInt() • addBoolean() • addBinary() if (todoList. "Required for meeting").DUE)) { Date date = new Date(). 179 .TODO_LIST. ToDo task = todoList.DUE. verify that the item supports the field by invoking isSupportedField(int). ToDoList todoList = null. Invoke createToDo() on a task list.SUMMARY.EXTENDED_FIELD_MIN_VALUE + 9.TODO_LIST) and the access mode with which to open the list (READ_WRITE.isSupportedField(ToDo. } Create a task.ATTR_NONE.isSupportedField(ToDo. ToDo.ATTR_NONE. ToDo. (date + 17280000)). task.addString(ToDo. PIM.openPIMList(PIM.READ_WRITE).

0. To retrieve an array of IDs for fields that have data for a particular ToDo item. ++j) { String value = task.length.out. } } } } 180 . To determine if a value is already set for the field.getFields(). Invoke commit(). invoke PIMItem.getString(id. Create code to manage a FieldFullException which a method such as addString() throws when a value already exists. int id.isModified()) { task. "Review notes").getInstance(). to determine whether any task fields have changed since the task was last saved. } Save a task. 1. Steps 1. if(task. To retrieve the field values. System. invoke countValues().println(task. ++index) { id = fieldIds[index]. 3. for(int index = 0. 3.getPIMList(). ToDoList todoList = (ToDoList)PIM.nextElement().getFieldDataType(id) == STRING) { for(int j=0.items() on the task list. invoke the appropriate set method. To replace an existing value with a new value. invoke PIMItem.ATTR_NONE. To change an existing value.getFields(). int[] fieldIds = task. j).getString(). Enumeration enum = todoList.TODO_LIST. } Retrieve task information. if (task. while (enum. invoke PIMList.openToDoList( PIM. 1.SUMMARY. use the corresponding set() method.BlackBerry Java Development Environment Development Guide Task Change task information. 2. if(task.hasMoreElements()) { ToDo task = (ToDo)enum.SUMMARY) > 0) { task.countValues(id).items().READ_ONLY).countValues(ToDo. Before you commit your changes. ToDo. PIM.commit(). 4. j < task. such as setString().getFieldLable(id) + "=" + value). invoke isModified() 2. 2. index < fieldIds.setString(ToDo. To retrieve an enumeration.

getInstance(). To create a new task using the PIM items. 3. ByteArrayOutputStream os = new ByteArrayOutputStream(). String[] dataFormats = PIM. > 1. The importToDo() method saves the task. invoke toSerialFormat(). try { todoList.TODO_LIST. Invoke removeToDo() on a task list. while (e. byteStream. To retrieve a string array of supported serial formats. Invoke todoList. PIM." "ISO-8859-1.getInstance(). "UTF8".getInstance().openPIMList( PIM. invoke ToDoList. invoke PIM.supportedSerialFormats(PIM. 2.READ_WRITE)." "ISO-8859-1.toDoSerialFormats(). // Write task to serial format. The enc parameter specifies the character encoding to use when writing to the output stream. you do not have to invoke commit().getInstance(). To return an array of PIMItem objects." and "UTF-16BE. Delete a task.openPIMList( PIM.close(). os.TODO_List). String[] dataFormats = PIM.TODO_LIST). Enumeration e = todoList. ByteArrayOutputStream byteStream = new ByteArrayOutputStream(). } catch (PimException e) { // Handle exception. } Import a task.nextElement(). The enc parameter specifies the character encoding to use when writing to the output stream. 1. } 181 .READ_ONLY).getInstance(). Supported character encodings include "UTF8." This parameter cannot be null. 2. ToDo task2 = todoList.supportedSerialFormats().13: Using PIM applications Task Export a task. 2. use an output stream writer to export tasks from the BlackBerry® device to a supported serial format. Steps 1. Supported character encodings include "UTF8.TODO_LIST. ByteArrayInputStream is = new ByteArrayInputStream(outputStream." This parameter cannot be null.getInstance(). dataFormats[0]).toSerialFormat(task.removeToDo(task). "UTF8". To import or export PIM item data.close(). invoke fromSerialFormat(). PIM. todoList.items(). Close a task list.toByteArray()). PIM. PIM. Create code that manages exceptions." and "UTF-16BE. PIMItem[] pi = PIM. dataFormats[0]).importToDo((ToDo)pi[0]). ToDoList todoList = (ToDoList)PIM. "UTF8").toSerialFormat(task.hasMoreElements()) { ToDo task = (ToDo)e. and then specify the list type (PIM.fromSerialFormat(is.importToDo(). ToDoList todoList = (ToDoList)PIM. To write an item to a serial format. // Import task from serial format.

See “Code sample: Displaying a screen that lets BlackBerry device users add new contacts” on page 184 for more information.rim.i18n.ui.rim.system. _endTime.device.api. pushScreen(_eventScreen). _location.*. */ package com.*.device.pim.*. combine this sample with ContactsDemo.device. public static void main(String[] args) { new EventDemo(). public final class EventDemo extends UiApplication { private EventScreen _eventScreen.microedition. import javax. import net.api.rim.rim.docs. private SaveMenuItem _saveMenuItem. import net.rim.rim. 0.api. } 182 . import net.enterEventDispatcher(). private DateField _startTime.rim.device.*. import java.eventdemo.util.BlackBerry Java Development Environment Development Guide See “Code sample: Using tasks” on page 186 for more information. private Event event.samples.io. } private EventDemo() { _eventScreen = new EventScreen().*.*.component.*. import net.device.ui. import net.java * Copyright (C) 2002-2005 Research In Motion Limited. } public final static class EventScreen extends MainScreen { private EditField _subject.api.*.device.api. private class SaveMenuItem extends MenuItem { public SaveMenuItem() { super(null. Example: EventDemo.java /** * EventDemo.api. private ObjectChoiceField _repeat.*. import net. Code samples Code sample: Creating new recurring appointments To let the BlackBerry® device user invite attendees to the meeting.ui.util.container. import java.java. 100000. 5).

“Monthly”.getDate()). String[] choices = {“None”.setDate(null).addDate(Event.getSelectedIndex() != 0) { event. _repeat = new ObjectChoiceField(“Recurrence: “.setText(““). setTitle(new LabelField(“Event Demo”. ““).ATTR_NONE. “Weekly”.WRITE_ONLY). _location = new EditField(“Location: “.START.END. event. event. _location. _endTime.currentTimeMillis() + 7200000. } } public EventScreen() { _saveMenuItem = new SaveMenuItem(). LabelField. System. choices. event = eventList.ATTR_NONE. _subject.setText(““). System. _subject = new EditField(“Subject: “.ELLIPSIS | LabelField.setSelectedIndex(0). add(_location).getDate()). PIMItem. } protected boolean onSave() { try { EventList eventList = (EventList)PIM. openPIMList(PIM. DateField. ““).ATTR_NONE. } 183 .addString(Event. _startTime. add(_endTime). return true.USE_ALL_WIDTH) ).getText()). PIMItem. } public void run() { onSave(). add(_repeat). _endTime = new DateField(“End: “.EVENT_LIST. } catch (PIMException e) { System. event. 0).setRepeat(setRule()). add(new SeparatorField()). //reset fields on screen _subject. PIMItem.DATE_TIME). _repeat.createEvent(). PIMItem.setDate(null). _endTime.commit(). PIM. add(_subject).getText()). event.getInstance(). _location.currentTimeMillis() + 3600000. DateField.addDate(Event.LOCATION. add(new SeparatorField()).SUMMARY.ATTR_NONE. “Daily”. _startTime = new DateField(“Start: “.addString(Event. add(_startTime).13: Using PIM applications public String toString() { return “Save”.DATE_TIME). } // Save the appointment to the Calendar. event. _startTime.println(e).err. “Yearly”}. if(_repeat.

BlackBerry Java Development Environment Development Guide

return false; } private RepeatRule setRule() { RepeatRule rule = new RepeatRule(); int index = _repeat.getSelectedIndex(); if (index == 0) { rule.setInt(RepeatRule.FREQUENCY, } if (index == 1) { rule.setInt(RepeatRule.FREQUENCY, } if (index == 2) { rule.setInt(RepeatRule.FREQUENCY, } if (index == 3) { rule.setInt(RepeatRule.FREQUENCY, } return rule; }

RepeatRule.DAILY); RepeatRule.WEEKLY); RepeatRule.MONTHLY); RepeatRule.YEARLY);

protected void makeMenu(Menu menu, int instance) menu.add(_saveMenuItem); menu.addSeparator(); super.makeMenu(menu, instance); } } }

{

Code sample: Displaying a screen that lets BlackBerry device users add new contacts
The following sample demonstrates how to display a screen that lets BlackBerry® device users add new contacts to the address book.
Example: ContactsDemo.java
/** * ContactsDemo.java * Copyright (C) 2002-2005 Research In Motion Limited. */ package com.rim.samples.docs.contactsdemo; import import import import import import import import import java.io.*; java.util.*; javax.microedition.pim.*; 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.*;

184

13: Using PIM applications

import net.rim.blackberry.api.pdap.*; public final class ContactsDemo extends UiApplication { 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. public static final class ContactScreen extends MainScreen { private EditField _first, _last, _email, _phone, _pin; private SaveMenuItem _saveMenuItem; private class SaveMenuItem extends MenuItem { private SaveMenuItem() { super(null, 0, 100000, 5); } public String toString() { return “Save”; } public void run() { onSave(); } } public ContactScreen() { _saveMenuItem = new SaveMenuItem(); setTitle(new LabelField(“Contacts Demo”, LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH)); _first = new EditField(“First Name: “, ““); add(_first); _last = new EditField(“Last Name: “, ““); add(_last); _email = new EditField(“Email Address: “, ““, BasicEditField.DEFAULT_MAXCHARS, BasicEditField.FILTER_EMAIL); add(_email); _phone = new EditField(“Work Phone: “, ““, BasicEditField.DEFAULT_MAXCHARS, BasicEditField.FILTER_PHONE); add(_phone); _pin = new EditField(“PIN:”, ““, 8, BasicEditField.FILTER_HEXADECIMAL); add(_pin); } protected boolean onSave() { String firstName = _first.getText(); String lastName = _last.getText(); String email = _email.getText(); String phone = _phone.getText(); String pin = _pin.getText(); // Verify that a first or last name and email has been entered. if ((firstName.equals(““) && lastName.equals(““)) || email.equals(““)) {
185

BlackBerry Java Development Environment Development Guide

Dialog.inform(“You must enter a name and an email address!”); return false; } else { 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.EMAIL, Contact.ATTR_HOME, email); contact.addString(Contact.TEL, Contact.ATTR_WORK, phone); if (contactList.isSupportedField(BlackBerryContact.PIN)) { contact.addString(BlackBerryContact.PIN, Contact.ATTR_NONE, pin); } // Save data to address book. contact.commit(); // Reset UI fields. _first.setText(““); _last.setText(““); _email.setText(““); _phone.setText(““); _pin.setText(““); return true; } catch (PIMException e) { return false; } } } protected void makeMenu(Menu menu, int instance) { menu.add(_saveMenuItem); super.makeMenu(menu, instance); } } }

Code sample: Using tasks
Example: TaskDemo.java
/** * TaskDemo.java * Copyright (C) 2002-2005 Research In Motion Limited. */ package com.rim.samples.docs.taskdemo;

186

13: Using PIM applications

import import import import import import import import import

java.io.*; java.util.*; javax.microedition.pim.*; 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.*;

public final class TaskDemo extends UiApplication { private TaskScreen _taskScreen; public static void main(String[] args) { new TaskDemo().enterEventDispatcher(); } private TaskDemo() { _taskScreen = new TaskScreen(); pushScreen(_taskScreen); } public final static class TaskScreen extends MainScreen { // Members. private EditField _summary, _note; private DateField _due; private ObjectChoiceField _priority, _status; private SaveMenuItem _saveMenuItem; private class SaveMenuItem extends MenuItem { private SaveMenuItem() { super(null, 0, 100000, 5); } public String toString() { return “Save”; } public void run() { onSave(); } } public TaskScreen() { _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. String[] choices = {“High”, “Normal”, “Low”}; _priority = new ObjectChoiceField(“Priority: “, choices, 1); add(_priority); String[] status = { “Not Started”, “In Progress”, “Completed”, “Waiting on someone else”, “Deferred” };
187

BlackBerry Java Development Environment Development Guide

_status = new ObjectChoiceField(“Status: “, status, 0); add(_status); _due = new DateField(“Due: “, System.currentTimeMillis() + 3600000, DateField.DATE_TIME); add(_due); _note = new EditField(“Extra Notes: “, ““); add(_note); } protected boolean onSave() { try { ToDoList todoList = (ToDoList)PIM.getInstance(). openPIMList(PIM.TODO_LIST, PIM.WRITE_ONLY); ToDo task = todoList.createToDo(); task.addDate(ToDo.DUE, ToDo.ATTR_NONE, _due.getDate()); task.addString(ToDo.SUMMARY, ToDo.ATTR_NONE, _summary.getText()); task.addString(ToDo.NOTE, ToDo.ATTR_NONE, _note.getText()); task.addInt(ToDo.PRIORITY, ToDo.ATTR_NONE, _priority.getSelectedIndex()); // ToDo.EXTENDED_FIELD_MIN_VALUE + 9 represents status. // Add 1 to selected index so that values are correct. // See the RIM Implementation Notes in the API docmentation for ToDo. task.addInt(ToDo.EXTENDED_FIELD_MIN_VALUE + 9, ToDo.ATTR_NONE, _status.getSelectedIndex() + 1); // Save task to handheld tasks. task.commit(); _summary.setText(““); _note.setText(““); _due.setDate(null); _priority.setSelectedIndex(1); // Reset to “Normal” priority. _status.setSelectedIndex(0); // Reset to “Not Started” status. return true; } catch (PIMException e) { return false; } } protected void makeMenu(Menu menu, int instance) { menu.add(_saveMenuItem); super.makeMenu(menu, instance); } } }

188

14
Using the phone application
Start the phone application from your BlackBerry Java Application Use phone call functionality Listen for phone events Access and use call logs Code sample

Start the phone application from your BlackBerry Java Application
To open the phone application from your BlackBerry® Java® 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.
private MenuItem phoneItem = new MenuItem(_resources.getString(MENUITEM_PHONE), 110, 12) { public void run() { synchronized(store) { String phoneNumber = phonefield.getText(); if ( phoneNumber.length == 0 ) { Dialog.alert(_resources.getString(ALERT_NO_PHONENUMBER)); } else { PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL, phoneNumber); Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, call); } } } };

Use phone call functionality
Task Retrieve a phone call. Retrieve the phone number of a BlackBerry device. Retrieve a phone call by call ID. Steps > > > Invoke Phone.getActiveCall(). Invoke Phone.getDevicePhoneNumber(boolean format). Invoke Phone.getCall(int).
PhoneCall call = Phone.getActiveCall(); String phNumber = Phone.getDevicePhoneNumber(true);

BlackBerry Java Development Environment Development Guide

Task Retrieve phone call information.

Steps > 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.isOutGoing() && elapsedTime > threshold) { // Use getCallId() to retrieve the caller ID as as an integer. String phoneNumber = call.getDisplayPhoneNumber(); Status.show("Your call to " + phoneNumber + " has lasted more than " + (String)threshold + "."); }

Add DTMF tones to the send queue
Task Add a single DTMF tone to the send queue. Add multiple DTMF tones to the send queue. Retrieve the send queue for the current call. Steps > > > Invoke sendDTMFTone(). Invoke sendDTMFTones(). Invoke getDTMFTones().

BlackBerry DTMF tones
BlackBerry® devices play DTMF tones as soon as no other tones are pending, overriding conversations. DTMF tones consist of a low and a high frequency, which are played at the same time.
Key 1 2 3 4 5 6 7 8 9 0 * # Low Tone (Hz) 697 697 697 770 770 770 852 852 852 941 941 941 High Tone (Hz) 1209 1336 1477 1209 1336 1477 1209 1336 1477 1209 1336 1477

190

14: Using the phone application

Listen for phone events
Task Listen for phone events. Register the phone listener. Remove a phone listener. Steps > >
>

Implement the PhoneListener interface. Invoke Phone.addPhoneListener().
Invoke removePhoneListener().

To act on a particular event, implement one of the following methods.
Event A call is added to a conference call. A BlackBerry® device user answers a call (user driven). A conference call is established. The network indicates a connected event (network driven). A direct-connect call is connected. A direct-connect call is disconnected. A call is disconnected. A BlackBerry device user ends the call. A call fails. A call goes on hold. A new call arrives. The BlackBerry device initiates an outgoing call. A call is removed from a conference call. A held call resumes. A call is waiting. A conference call is ended (all members are disconnected). Method
callAdded(int) callAnswered(int) callConferenceCallEstablished(int) callConnected(int) callDirectConnectConnected(int) callDirectConnectDisconnected(int) callDisconnected(int) callEndedByUser(int) callFailed(int, int) callHeld(int) callIncoming(int) callInitiated(int) callRemoved(int) callResumed(int) callWaiting(int) conferenceCallDisconnected(int)

Access and use call logs
Task Retrieve a phone log. Steps The PhoneLogs class represents the phone call history and provides methods for opening, adding, deleting, or swapping call logs. > Invoke PhoneLogs.getInstance().
PhoneLogs _logs = PhoneLogs.getInstance();

Retrieve the number of normal or missed There are two phone log folders: FOLDER_NORMAL_CALLS and FOLDER_MISSED_CALLS. calls. > Invoke numberOfCalls(int).
int numberOfCalls = _logs.numberOfCalls(FOLDER_NORMAL_CALLS);

Retrieve a call log.

You can instantiate two types of call logs: PhoneCallLog objects, which have only one participant, and ConferencePhoneCallLog objects, which have two or more participants. > Invoke PhoneLogs.callAt(int index, long folderID).
PhoneCallLog phoneLog = (PhoneCallLog)_logs.callAt(0);

191

invoke PhoneLogs.addCall(CallLog call). mobile.phonelogs.rim. 192 . 0. All rights reserved. and provide the date.swapCall(conferenceCall. > Invoke PhoneCallLogID. or fax.int index.getType(). 1.getParticipantAt().rim. duration.phone. Date date = new Date("1000"). home. The PhoneCallLogID constructor removes dashes and other non-numeric characters from phone numbers. work.getParticipant(int) or ConferencePhoneCallLog. PhoneCallLogID participant = ConferencePhoneCallLog.deleteCall(). The PhoneCallLogID class identifies the type of phone call for a log. • To replace the call log with a new call log. and notes for the call as parameters to the constructor. invoke PhoneLogs.addCall(conferenceCall). participants. > Invoke PhoneCallLog.getParticipant(). For example.docs. caller2.api.". duration. Steps The PhoneCallLogID class identifies participants in a phone call log by phone number. caller1. > Invoke PhoneLogs.BlackBerry Java Development Environment Development Guide Task Retrieve a call participant by phone number. _logs. as recorded in the address book. Create an instance of a PhoneCallLog or ConferencePhoneCallLog object. FOLDER_NORMAL_CALLS). import net. Retrieve the phone number type.java * Copyright (C) 2001-2005 Research In Motion Limited. // duration of call PhoneCallLogID caller1 = new PhoneCallLogID("555-1234"). Create a call log or conference call log. notes).deleteCall(0). 2. Code sample Code sample: Calculating the time spent on the phone by a participant Example: PhoneLogsDemo.blackberry.java /** * PhoneLogsDemo.phonelogs. */ package com. // notes ConferencePhoneCallLog conferenceCall = new ConferencePhoneCallLog(date. Delete a call log. PhoneLogs.getParticipant(). // date of call int duration = 60. Update the call log: • To update the call log. PhoneCallLogID participant = phoneCallLog.samples.swapCall(CallLog call.getType(). _logs. String phoneType = PhoneCallLogID.FOLDER_NORMAL_CALLS.*.long folderID) _logs. // second participant String notes = "New call. // first participant PhoneCallLogID caller2 = new PhoneCallLogID("555-1235").

folder)._logs. } } 193 . PhoneLogs. } private PhoneLogsDemo() { _logs = PhoneLogs. } // Returns the number of seconds spent on the phone with a participant.getParticipant() == participant) timeSpokenTo += phoneCallLog. PhoneCallLog phoneCallLog. } } } return timeSpokenTo. } else { conferencePhoneCallLog = (ConferencePhoneCallLog) o.system.api.getParticipantAt(j) == participant) { timeSpokenTo += conferencePhoneCallLog. if ( phoneCallLog.numberOfCalls(folder). int timeSpokenTo = 0. public int findTimeSpokenTo(PhoneCallLogID participant.*. j < participants.Application.device. for (int i = 0. for (int j = 0. public class PhoneLogsDemo extends Application { private PhoneLogs _logs. long folder) { int numberOfCalls = this. j++) if (conferencePhoneCallLog.numberOfParticipants(). j = participants. import net. private int _timeSpokenTo.enterEventDispatcher().FOLDER_NORMAL_CALLS). static public void main(String[] args) { PhoneLogsDemo app = new PhoneLogsDemo(). ConferencePhoneCallLog conferencePhoneCallLog. _timeSpokenTo = findTimeSpokenTo(participant. int participants = conferencePhoneCallLog. i++) { Object o = _logs. app.getInstance().lang. i < numberOfCalls.getDuration().rim.getDuration(). if (o instanceof PhoneCallLog) { phoneCallLog = (PhoneCallLog) o. PhoneCallLogID participant = new PhoneCallLogID(“5551234”).callAt(i.14: Using the phone application import java.

BlackBerry Java Development Environment Development Guide 194 .

rim.blackberry. Steps 1.blackberry.getDefaultSession(). Task Retrieve a BlackBerry® Browser session. Store the returned rendering session handle in a RenderingSession object. use the net.. Steps Retrieving the default session overrides any open sessions on the BlackBerry device.api.java sample creates a menu item that displays a web page in the BlackBerry Browser. > > Retrieve the default BrowserSession object by invoking the static method Browser. Invoke RenderingSession.getNewInstance(). Invoke Browser.displayPage(String url). private MenuItem browserItem = new MenuItem(_resources. visit. Display content in a BlackBerry Browser field To display web content in a BlackBerry® Browser field.15 Using the BlackBerry Browser Display content in the BlackBerry Browser Display content in a BlackBerry Browser field Code sample Display content in the BlackBerry Browser To display web content in the BlackBerry® Browser. if (websiteUrl. } } } }.displayPage(websiteUrl). Task Access a rendering session.rim. The following excerpt from the Restaurants. RenderingSession _renderingSession = RenderingSession. > Retrieve a non-default BlackBerry® Browser session.getString(ALERT_NO_WEBSITE)). .alert(_resources. Invoke BrowserSession. specifying the URL that contains the web content.getText().getDefaultSession().getNewInstance().api. 12) { public void run() { synchronized(store) {String websiteUrl = websitefield.length == 0) { Dialog.browser package. Request a web page. } else { BrowserSession visit = Browser. use the net.getSession().browser package. 2.getString(MENUITEM_BROWSER). 110.

field.com").getRenderingOptions().deleteAll() method. To add field data to the BlackBerry Java® Application screen. To render the new BlackBerry browser content. _mainScreen. 196 .browser.microedition. WML files and images might load before you invoke this method. class CreationThread extends Thread { BrowserFieldHandlerApplication _callBackApplication.rim. } public void run() { _renderingApplication = new BasicRenderingApplication(_callBackApplication).field.BlackBerry Java Development Environment Development Guide Task Define callback functionality for a rendering session.finishLoading(). 2.browser. invoke MainScreen. Store the returned object in a BrowserContent object. Display a BlackBerry® Browser field.getDisplayableContent(). BrowserField field = _renderingApplication.api. invoke the MainScreen. this. invoke BrowserContent. net. > Invoke BrowserContent. } } Set rendering options.device. Your BlackBerry® Java® Application uses the default rendering options if you do not override BrowserContent.. storing the returned object in a Field object. Create a non-main event thread to run BrowserContent.RenderingApplication.add(field). Steps > 1. > Override BrowserContent. BrowserContent browserContent = _renderingSession.HTML files display a blank field until you invoke BrowserContent. > Create a non-main thread that contains the instructions for retrieving and displaying the BlackBerry® Browser field. Implement the RenderingApplication interface.rim.io.displayBrowserField(field).deleteAll(). BasicRenderingApplication _renderingApplication.finishLoading()so that the UI does not lock. Retrieve a BlackBerry® Browser field.Event). _mainScreen.api.getRenderingOptions().getBrowserField("www. Create a separate thread for rendering. public CreationThread(BrowserFieldHandlerApplication callBackApplication) { _callBackApplication = callBackApplication. 4. net. Invoke RenderingSession.add().device. 2.getBrowserContent(HttpConnection connection.HttpConnecti on. Event e).getDisplayableContent(). You render web content in the BrowserContent object.blackberry. Field field = browserContent. _callBackApplication.getBrowserContent(javax. 3. 1. Retrieve a field in which the URL content is rendered to your BlackBerry® Java® Application for display.finishLoading(). To clear the current screen.

urlRequestedEvent. switch (e.15: Using the BlackBerry Browser Task Manage events. specifying the actions that occur when a specific rendering event occurs.getSource().getURL().setTitle(newTitle). break. break. String newTitle = browserField.eventOccurred().event. HttpConnection conn = null. Steps > Implement of RenderingApplication. case RedirectEvent. referrer = null. } case Event. The following example specifies actions that occur in the event of a URL request. so we update the title field.} case Event. BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event. case Event. PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(urlRequestedEvent.EVENT_URL_REQUESTED : { UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event. thread.EVENT_SET_HEADER : // no cache support case Event. change in browser content.getUID(). or a redirect to a different web page. if (browserContentChangedEvent.TYPE_JAVASCRIPT : break. String absoluteUrl = urlRequestedEvent. } 197 .start().getHeaders().}} break. public Object eventOccurred(Event event) { int eventId = event.getPostData().EVENT_SET_HTTP_COOKIE : // no cookie support default : } return null.getSource() instanceof BrowserContent) { BrowserContent browserField = (BrowserContent) browserContentChangedEvent. urlRequestedEvent. do not send a Referer for META Refresh.getType()) { case RedirectEvent.getURL().getTitle(). String referrer = e. this).EVENT_BROWSER_CONTENT_CHANGED: { // The browser field title might have changed.EVENT_REDIRECT : { RedirectEvent e = (RedirectEvent) event.TYPE_META : // For MSIE and Mozilla. if (newTitle != null) { _mainScreen. switch (eventId) { case Event.getSourceURL().

http.device.api.api.device. net. private MainScreen _mainScreen. net.device.rim. net.rim.rim.api.ui.rim. null.ui.api. javax. import import import import import import import import java.rim.MainScreen. } public void processConnection(HttpConnection connection.device. pushScreen(_mainScreen). private HttpConnection _currentConnection.api. */ package com. _renderingSession = RenderingSession.close().google.IOException. this).device.*.component.container.io. net.Status.HttpHeaders.ui.io.api.rim.*. Event e) { // cancel previous request if (_currentConnection != null) { try { _currentConnection. null.device.field. net. null.BlackBerry Java Development Environment Development Guide Code sample Code sample: Using the BlackBerry Browser Example: BrowserFieldSampleApplication. } catch (IOException e1) { } } _currentConnection = connection.docs.enterEventDispatcher().browser. PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(“http:// www. private RenderingSession _renderingSession. app.browser. 198 . final public class BrowserFieldSampleApplication extends UiApplication implements RenderingApplication { private static final String REFERER = “referer”.getNewInstance(). net.java /** * DefaultRenderingApplication.java * Copyright (C) 2004-2005 Research In Motion Limited.io.samples.Application. thread. public static void main(String[] args) { BrowserFieldSampleApplication app = new BrowserFieldSampleApplication().HttpConnection.system.com”.microedition.rim. } private BrowserFieldSampleApplication() { _mainScreen = new MainScreen().start().

break.add(field).deleteAll(). event.getTitle(). thread.setTitle(newTitle).getSource() instanceof BrowserContent) { BrowserContent browserField = (BrowserContent) browserContentChangedEvent. HttpConnection conn = null. } } catch (RenderingException re) { } finally { SecondaryResourceFetchThread.getBrowserContent(connection.EVENT_URL_REQUESTED : { UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event.getURL().getUID().doneAddingImages().getHeaders().api. } case Event.E vent) */ public Object eventOccurred(Event event) { int eventId = event. urlRequestedEvent. String newTitle = browserField. } } break.browser.browser. } } browserContent. if (browserContentChangedEvent.getSource().finishLoading(). this).getDisplayableContent().getEventLock()) { _mainScreen.device.device.EVENT_BROWSER_CONTENT_CHANGED: { // browser field title might have changed update title BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event. _mainScreen. this.getPostData().15: Using the BlackBerry Browser BrowserContent browserContent = null. if (newTitle != null) { _mainScreen.RenderingApplication#eventOccurred(net.rim. } } /** * @see net. e). switch (eventId) { case Event. } case Event.getURL(). String absoluteUrl = urlRequestedEvent.EVENT_REDIRECT : { 199 . urlRequestedEvent. if (browserContent != null) { Field field = browserContent. PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(urlRequestedEvent.rim.api. if (field != null) { synchronized (Application. try { browserContent = _renderingSession.start().

PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(e. break.. requestHeaders. } /** * @see net.getScreenHeight(). break.rim. 200 .device.api.BrowserContent) */ public int getAvailableHeight(BrowserContent browserField) { // field has full screen return Graphics.setProperty(REFERER. String referrer = e.EVENT_SET_HEADER : // no cache support case Event. } HttpHeaders requestHeaders = new HttpHeaders().invokeAndWait(new Runnable() { public void run() { Status.RenderingApplication#getAvailableHeight(net.getRequestProperty(REFERER).BlackBerry Java Development Environment Development Guide RedirectEvent e = (RedirectEvent) event. requestHeaders. event.getSourceURL().api.EVENT_CLOSE : // TODO: close the appication break.EVENT_SET_HTTP_COOKIE : // no cookie support case Event. case RedirectEvent.EVENT_HISTORY : // no history support case Event.start(). referrer = null.show(“You are being redirected to a different page. break.getSource().null.TYPE_JAVASCRIPT : break.TYPE_META : // MSIE and Mozilla don’t send a Referer for META Refresh.device. case RedirectEvent.browser. thread.TYPE_SINGLE_FRAME_REDIRECT : // show redirect message Application. Mozilla. } case Event. Object eventSource = e. case Event.EVENT_STOP : // no stop loading support default : } return null.EVENT_EXECUTING_SCRIPT : // no progress bar is supported case Event.EVENT_FULL_WINDOW : // no full window support case Event.getLocation().TYPE_300_REDIRECT : // MSIE. case RedirectEvent. } break. and Opera all send the original // request’s Referer as the Referer for the new // request.rim.. } }).getApplication().brow ser. referrer). this). switch (e.”). if (eventSource instanceof HttpConnection) { referrer = ((HttpConnection)eventSource).getType()) { case RedirectEvent.

rim.RenderingApplication#getResource(net.rim.api.RenderingApplication#getHistoryPosition(net.api. if (url == null) { return null.device.rim.browser.api.BrowserContent) */ public HttpConnection getResource( RequestedResource resource.api.BrowserContent) */ public int getAvailableWidth(BrowserContent browserField) { // field has full screen return Graphics.15: Using the BlackBerry Browser } /** * @see net.BrowserContent) */ public int getHistoryPosition(BrowserContent browserField) { // no history support return 0. return the connection.rim.api. BrowserContent referrer) { if (resource == null) { return null.device. * net.getScreenWidth().brow ser.RenderingApplication#getHTTPCookie(java. } /** * @see net.browser. } /** * @see net.rim.browser.device.rim.api.getUrl().device. } // Verify that this is a cache-only request.isCacheOnly()) { // no cache support return null. } // If the referrer is null.device.brows er.device.browser.browser.api.device.device.rim. } /** * @see net.browser.Req uestedResource. if (referrer == null) { 201 .String) */ public String getHTTPCookie(String url) { // no cookie support return null. if (resource.lang.api.rim.RenderingApplication#getAvailableWidth(net. } String url = resource.

byte[] postData. _postData = postData. private String _url.getUrl(). _application = application. } public void run() { HttpConnection connection = Utilities.device.processConnection(connection. return connection. } } 202 .enqueue(resource. _application. _requestHeaders = requestHeaders. _requestHeaders.BlackBerry Java Development Environment Development Guide HttpConnection connection = Utilities.browser.RenderingApplication#invokeRunnable(java.lang. SecondaryResourceFetchThread. BrowserFieldSampleApplication application) { _url = url.makeConnection(resource. } /** * @see net. } } class PrimaryResourceFetchThread extends Thread { private BrowserFieldSampleApplication _application.rim. referrer). PrimaryResourceFetchThread(String url. } else { // If the referrer is not null. _postData).run(). private HttpHeaders _requestHeaders. private byte[] _postData. private Event _event. resource. Event event. null). HttpHeaders requestHeaders. _event = event. set up the connection on a separate thread.api.getRequestHeaders(). } return null.makeConnection(_url. _event).Runnable) */ public void invokeRunnable(Runnable runnable) { (new Thread(runnable)).

. The Internet Browser configuration does not support push applications. Two types of push applications exist: Application Browser push applications Description Browser push applications send content to a web browser on the BlackBerry® device. • • • The BlackBerry Browser configuration supports BlackBerry MDS™ Services push applications.16 Creating push BlackBerry Java Applications Types of push BlackBerry Java Applications Types of push requests Write a client push BlackBerry Java Application Write a server-side push application Create a RIM push request Create a PAP push request Code samples Types of push BlackBerry Java Applications Push applications send web content or data to specific BlackBerry® device users. Client/server push applications A server-side application pushes data to a custom BlackBerry® Java® Application on the BlackBerry device. This approach provides more control than browser push applications over the type of content that you can send and how the BlackBerry device processes and displays the content. See the BlackBerry Browser Developer Guide for more information about writing browser push applications. Users do not need to request or download the data because the push application delivers the information as soon as it becomes available. The WAP Browser configuration supports WAP push applications. Client/server push applications consist of a custom client BlackBerry Java Application for the BlackBerry device and a server-side application that pushes content to the client BlackBerry Java Application.

Undelivered RIM pushes might be lost if the server reboots.0 specification. 204 .org. including both RIM and PAP push requests. For more information about PAP. Note: Part of the WAP 2. Note: The BlackBerry® Mobile Data System™ queues only 1000 push requests. visit http:// www. PAP pushes are stored in a database.openmobilealliance.BlackBerry Java Development Environment Development Guide Types of push requests Applications can send two types of push requests: Request RIM push Supported tasks • • • • • PAP • • • • • • • 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 sending a server-side push submission specifying a reliability mode for the push submission specifying a deliver-before times tamp for the push submission requesting a result notification of the push submission specifying a deliver-after times tamp for the push submission cancelling a push request submission querying the status of a push request submission Push storage RIM pushes are stored in RAM.

Open an input stream.getRecordByUidAndCid( serviceUID.getNetworkService() & RadioInfo. Create code to check if the IPPP service book can be routed. If you use application level push reliability. // open an input stream for the connection InputStream input = stream.NETWORK_SERVICE_DATA ) != 0. If an IOException occurs. set the deviceside=boolean parameter to false.isServiceRoutable( serviceUID. use the pushInputStream. Open a server-side stream connection once and keep the server-side stream connection open.accept() method to accept and acknowledge the incoming data. 205 . 4.getState() != RadioInfo.getInstance(). 7. a wireless coverage area.open(String). To specify the connection type that the BlackBerry® Java® Application uses for incoming and outgoing connections.open returns as a StreamConnectionNotifier. // open a server-side stream connection StreamConnection stream = _notify. 5. followed by the optional deviceside=boolean parameter with one of the following values: • If the BlackBerry Java Application listens for push information from BlackBerry® MDS™ Services. add a colon. reopen the connection. Determine if a BlackBerry® device is in 1. • If the BlackBerry Java Application listens for push information from WAP push requests. -1 ) ) { // Serial bypass is active return true. StreamConnectionNotifier _notify = (StreamConnectionNotifier)Connector. specifying http:// as the protocol and choosing a high port number from 1 to 65. 1. Read the incoming data.16: Creating push BlackBerry Java Applications Write a client push BlackBerry Java Application Task Create a listening thread. "IPPP" ) == null ) { // There is no service book return false. Create code to check that the wireless transceiver is on and that data coverage is on. do not use the deviceside=boolean parameter. at the end of the connection string.open("http://:6234"). Cast the object that Connector.acceptAndOpen(). 3.535 to avoid conflicts with other applications.getSB(). } return RadioInfo. You cannot use the following port numbers: • 80 • 443 • 7874 • 8080 Connnector. 2. Steps > Send and receive data on a separate thread so that you do not block the main event. if( ServiceBook.openInputStream(). 6. 2.open(http://6234). } if( ServiceRouting. Invoke Connector.STATE_OFF && ( RadioInfo.

Invoke openConnection() on the push URL.openConnection() returns as an HttpURLConnection. conn. See “Code sample: Listening for data from a web server” on page 211 for more information. See “Create a PAP push request” on page 210 for more information about PAP push requests. 3. // Post to the BlackBerry Enterprise Server. Cast the object that url. 2. Establish a connection using the fully qualified computer name or IP address. 206 . 1. conn. and 8080 to deliver push data. Construct the push URL. 1. > Connect to the BlackBerry® MDS™ Connection Service. Set properties for the HTTP POST request. 7874. perform one of the following actions: • Create a RIM push request using the following format: /push?DESTINATION=destination&PORT=port&REQUESTURI=uri <headers> <content> • Create a PAP push request using the following format: /pap See “Create a RIM push request” on page 209 for more information about RIM push requests. _notify. 443. The following sections use standard Java® to demonstrate a server-side push application. Steps If you create an client/server push application. in the application. To send data.setRequestMethod("POST"). Steps > Invoke close() on the stream connection notifier.setDoInput(true).close().openConnection(). To create a push request. An HttpURLConnection represents a connection to a remote object. set the parameter in setDoInput(Boolean) to true to indicate that the application intends to read data from the URL connection. HttpURLConnection conn =(HttpURLConnection)url. conn. you must make sure that the server-side application uses a port number other than 80. Task Specify a port. Connect to the BlackBerry® Enterprise Server. To receive confirmation.BlackBerry Java Development Environment Development Guide Task Close the stream connection notifier. include the X-Rim-Push-Dest-Port header with the port value. Create a POST request.setDoOutput(true). > > To specify a different port. set the parameter in setDoOutput(Boolean) to true to indicate that the application intends to send data to the URL connection. 2. Write a server-side push application You can use any programming language that can establish an HTTP connection to create a push application.

open a data input stream. 2. 1. To access an input stream. Determine the size of the content. dins. Close the server connection. invoke disconnect() conn. invoke getInputStream(). } ins. Write data to the output stream. Steps 1. out. and then retrieve the content. System. OutputStream out = conn.getInputStream().println(new String(someArray)). int contentLength = conn. 207 .getOutputStream().close(). invoke getOutputStream(). out. Read the server response. DataInputStream dins = new DataInputStream(ins). To access an output stream.readFully(someArray).16: Creating push BlackBerry Java Applications Task Write data to the server connection.close(). InputStream ins = conn.disconnect(). Close the output stream. If the size of the content is non zero. > To indicate that the application will make no further requests to the server. 3. 2.out. if (contentLength > 0) { byte[] someArray = new byte [contentLength].write(data).getContentLength().

net" /> The following example shows a PAP push cancellation request: Content-Type: application/xml <?xml version="1. For example: <statusquery-message push-id="123@wapforum.wahl%40blackberry. If the application requires this functionality.dtd" [<?wap-pap-ver supported-versions="2.org"> 2.com%3A7874/ TYPE=USER@rim. To specify the address to which you want to submit the push message.wapforum.wahl%40blackberry.0. in the PAP push query request.org"> 2.BlackBerry Java Development Environment Development Guide Work with a server-side push request Send a request to cancel a PAP push submission.1.0"?> <!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.net" /> The following example shows a RIM network status query request: Content-Type: application/xml <?xml version="1. send a PAP push query request using the statusquery-message push-id header.0//EN" "http://www. specify multiple recipient addresses in the push submission. <address address-value="WAPPUSH=aisha.org/DTD/pap_2. Query the status of a PAP push request.wapforum.0. For example: <address address-value="WAPPUSH=aisha.com%3A7874/TYPE=USER@rim.*"?>]> <pap> <statusquery-message push-id="123@wapforum. use the address address-value header.0//EN" "http://www.0.com%3A7874/TYPE=USER@rim.wahl%40blackberry. 1. To specify the push message on which you want to obtain status information.net"/> </statusquery-message> </pap> 208 .org "> <address address-value="aisha.wahl%40blackberry. For example: <cancel-message push-id="123@wapforum. 1. you cannot determine the status of delivery to a particular recipient or cancel delivery to one or more recipients.dtd"> <pap> <cancel-message push-id=“a_push_id"> <address address-value= “WAPPUSH=aisha.org/DTD/pap_2.net”/> </cancel-message> </pap> Note: When pushing to a Group address.com%3A7874/ TYPE=USER@rim.0"?> <!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2. Use the cancel-message push-id header. This is a required tag. To specify the address to which the application submitted the push message. use the address-value header.

which specifies an HTTP response code.com. Use the X-RIM-Push-NotifyURL header.preferred (APPLICATION-PREFERRED) • transport-level (TRANSPORT) Use the X-RIM-Push-Deliver-Before-timestamp header. To push data to a single BlackBerry device user using RIM push. Represent the date and time in UTC format.com&DESTINATION=user2@rim. Use the X-RIM-Push-Reliability-Mode header with one of the following modes: • application-level (APPLICATION) • application. Steps 1. 209 . For example: Note: Push identifiers must not end in @ppg. In the following example. the $ character is URL encoded. The notification also contains an X-RIM-Push-Destination header that specifies the recipient address to which the result pertains. send an HTTP POST request using the following URL format. For example: BlackBerry® device. which specifies the message ID. The following example shows a URL used to push to a group named IT using RIM push: http://mds_server:8080/push?DESTINATION=%24IT&PORT=7874&REQUESTURI=/ Specify a unique message ID to cancel or check the status of a message. Typically.com&PORT=7874&REQUESTURI=/ Push content to a group using RIM push. prefix the group name with the $ character. the Mobile Data Service™ generates a unique message ID. The result notification contains the X-RIM-Push-ID header. Content that the application does not deliver before this date is not delivered. specify a URL in combination with a value.rim. specify the date and time in UTC which the content is delivered to the format. > Specify the delivery reliability mode > of the content. The application Mon. 28 Aug 2006 16:06:00 GMT Specify the date and time after > In the X-RIM-Push-Deliver-After-timestamp header. For example: http://mdsServer:web server listen port/ push?DESTINATION=destination&PORT=port&REQUESTURI=uri headers content where: • destination is the destination PIN or email address • port is the destination port number • uri is the URI sent to the BlackBerry device • headers consists of HTTP headers • content is a byte stream 2. Specify a URL to send a result notification. and the X-RIM-Push-Status header. > Use the X-RIM-Push-ID header.16: Creating push BlackBerry Java Applications Create a RIM push request Task Push content to one or multiple BlackBerry® device users using a RIM push request. 28 Aug 2006 16:06:00 GMT does not deliver the content before this date. To push content to multiple recipients using RIM push. include multiple DESTINATION parameters in the query string.com. > Mon. Specify the date and time by which to deliver the content to the BlackBerry device. such as 123@blackberry. If this header is omitted. http://mds_server:8080/push?DESTINATION= user1@rim. > In the recipient addresses portion of the push submission.

add multiple address tags to the post request. send an HTTP POST request using the following format: http://mdsServer:web server listen port/pap . Task Steps To push data to a single BlackBerry device user using PAP. To push content to multiple recipients using PAP.wahl%40blackberry. For example: <address address-value="WAPPUSH=user1%40rim%2ecom%5B%3A7874/ TYPE=USER@rim. BlackBerry® device users using PAP. Push content to one or multiple 1. prefix the group name with the $ character.org/DTD/pap_2.The URL to send the PAP push to. PAP world!</body></html> --asdlfkjiurwghasf-- 2. > In the recipient addresses part of the push submission. 210 .net"/> <quality-of-service delivery-method="unconfirmed"/> </push-message> </pap> --asdlfkjiurwghasf Content-Type: text/html <html><body>Hello.BlackBerry Java Development Environment Development Guide Create a PAP push request See “Appendix: XML control entity attributes” on page 265 for more information about XML control entity attributes.net"></address> Push content to a group using PAP. which consists of the following items: • XML document specifying the control entity • push content The following example shows a PAP push request: Content-Type: multipart/related. In the following example. type="application/xml".wapforum. The request is a MIME multipart message.com%3A7874/ TYPE=USER@rim.net/ReceiveNotify"> <address address-value="WAPPUSH=aisha. boundary=asdlfkjiurwghasf X-Wap-Application-Id: / --asdlfkjiurwghasf Content-Type: application/xml <?xml version="1.net"></address> <address address-value="WAPPUSH=user2%40rim%2ecom%5D%3A7874/ TYPE=USER@rim.net"/> See “Code sample: Pushing data to a BlackBerry Java Application that listens on a BlackBerry device” on page 214 for more information.dtd"> <pap> <push-message push-id="a_push_id" ppg-notify-requested-to="http:// foo. The following example shows an address element used to push to a group named IT using PAP: <address address-value="WAPPUSH=%24IT/TYPE=USER@rim.0"?> <!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2. the $ character is URL encoded.0.0//EN" "http:// www.rim.

api.docs.io.docs.device.httppush.samples.api.api. net.rim. private MainScreen _mainScreen. private static final String URL = “http://:100”. //statics -----------------------------------------------------------------private static ResourceBundle _resources = ResourceBundle. * This application will listen for image data on the specified port and * render the data when it arrives.i18n.api. private RichTextField _imageField.api.rim.rim.io.rim.samples. */ private class ListeningThread extends Thread { private boolean _stop = false.device. private RichTextField _infoField.java /** * The client side of a simple HTTP Push system.api.device. import import import import import import import import import import java.BUNDLE_NAME).device. 211 . */ package com.rim. } /** * Create a separate listening thread so that you do not * block the application’s main event thread.rim.resource.*. HTTPPushDemoResResource.microedition. All rights reserved.getBundle(HTTPPushDemoResResource. // Fields.device.BUNDLE_ID.component.*.16: Creating push BlackBerry Java Applications Code samples Code sample: Listening for data from a web server Example: HTTPPushDemo.device. net. private ListeningThread _listeningThread. net. * Copyright (C) 2001-2005 Research In Motion Limited. javax.api.ui. public static void main(String[] args) { HTTPPushDemo theApp = new HTTPPushDemo(). public class HTTPPushDemo extends UiApplication implements HTTPPushDemoResResource { // Constants.*.*. net. net.util.http.*.*.rim.ui.device.system. private StreamConnectionNotifier _notify. theApp.ui.container.rim.*.*.*.enterEventDispatcher().io.rim. //PORT 100 private static final int CHUNK_SIZE = 256. net. com. net.*.

acceptAndOpen().deviceside=false”).toString()). byte[] data = new byte[CHUNK_SIZE]. while (!_stop) { try { //synchronize here so that we don’t end up creating a //connection that is never closed synchronized(this) { // Open the connection once (or re-open after an IOException). // we open the url with a parameter that indicates that we should always // use MDS when attempting to connect. try { input = stream. } catch (NullPointerException e) { // The notify object likely failed to open.openInputStream().close(). while ( -1 != (chunk = input. where a push is lost if // it comes in before the connection is open again. input).open(URL + “. //Extract the data from the input stream DataBuffer db = new DataBuffer(). } while (!_stop) { //NOTE: the following will block until data is received stream = _notify. chunk). // so we don’t end up in a race condition.write(data. } updateMessage(data). try { _notify. 0. //This method is called to accept the push pushInputStream. MDSPushInputStream pushInputStream=null. int chunk = 0. InputStream input = null. // Close the connection so thread returns. } } public void run() { StreamConnection stream = null.accept(). due to an IOException. } catch (IOException e) { System. 212 .println(e.err. pushInputStream= new MDSPushInputStream((HttpServerConnection)stream. _notify = (StreamConnectionNotifier)Connector.BlackBerry Java Development Environment Development Guide public synchronized void stop() { _stop = true.read(data)) ) { db.

close().close(). } catch (InterruptedException e) { System. } catch (IOException ioe) { // likely the stream was closed System.16: Creating push BlackBerry Java Applications input.println(e.println(e1. } catch ( IOException e ) { } } } } } } private final class HTTPMainScreen extends MainScreen { public void close() { // Stop the listening thread.close().close().toString()).toString()). _notify = null. try { _listeningThread.err.err. _listeningThread. if ( input != null ) { try { input. } catch (IOException e1) { // a problem occurred with the input stream // however. } } 213 . _notify = null. } catch (IOException e2) { } } } } _notify.close().getArray(). the original StreamConnectionNotifier is still valid System.err. if ( _notify != null ) { try { _notify. } super.stop(). } catch (IOException e2) { } } if ( stream != null ) { try { stream.println(ioe. data = db.close().close().toString()).join(). stream.

} private void updateMessage(final byte[] data) { Application.inform(e.err. define a mapping between the internet messaging address and the BlackBerry Device Simulator PIN (2100000A). } _infoField. } } Code sample: Pushing data to a BlackBerry Java Application that listens on a BlackBerry device The HTTPPush. System.toString()). try { _imageField. pushScreen(_mainScreen). LabelField.length). } } }). if ( 0 != Dialog. 214 . _infoField = new RichTextField().toString()).setText(_resources.USE_ALL_WIDTH)).BlackBerry Java Development Environment Development Guide // Constructor.setTitle(new LabelField(_resources.getString(HTTPPUSHDEMO_TITLE).getString(HTTPPUSHDEMO_QUERYFORRENDER). _infoField.println(e.getString (HTTPPUSHDEMO_DIALOG_CANCEL)}. } catch (Exception e) { Dialog.add(_infoField). 0) ) { return.setText(new String(data)). _mainScreen.getString(HTTPPUSHDEMO_DIALOG_OK). _imageField = new RichTextField().invokeLater(new Runnable() { public void run() { //query the user to load the received message String[] choices = {_resources. choices.getString(HTTPPUSHDEMO_LISTENTHREADSTARTED)). sends a string of text to a listening client application on the BlackBerry® device using either a RIM push or a PAP push. _mainScreen.add(_imageField).start(). To test push applications with the BlackBerry Device Simulator.java sample application. _mainScreen. _mainScreen.setText(_resources. The application pushes data based on an internet messaging address. _listeningThread. which uses standard Java®.getString(HTTPPUSHDEMO_IMAGEINFO) + data. _resources. _listeningThread = new ListeningThread().getApplication().ask(_resources. public HTTPPushDemo() { _mainScreen = new HTTPMainScreen().add(new SeparatorField()).

&amp.getHeight()). import import import import import import java.swing.JFrame { //constants ----------------------------------------------------------------private static final String RESOURCE_PATH = “com/rim/samples/docs/httppush/resources”.net. //statics ------------------------------------------------------------------private static ResourceBundle _resources = java. 215 . java.16: Creating push BlackBerry Java Applications The following code sample compiles using J2SE 1. For reliable push.4.application. The associated client demo * is HTTPPushServer. notifyURL=”http://localhost:7778”. */ public class HTTPPushServer extends javax. private static final int MDS_PORT = 8080. private static final String DEVICE_PORT = “100”.PORT=&lt.<b>100</b></code * * <p> The general form of the URL for posting (pushing) data to the device is: * http://&lt. //sizing code for the main frame setSize(_panel.getBundle(RESOURCE_PATH).util. * <p>This program will send text to a listening device.host&gt.getWidth(). pack ().post uri&gt./push?DESTINATION=&lt. All rights reserved.&REQUESTURI=&lt.util. java.swing. javax.java /* * HttpPushServer.ports=7874.:&lt. //constructors -------------------------------------------------------------/** Creates a new HTTPPushServer instance*/ public HTTPPushServer() { initComponents ().*. append the port that you are pushing to in * rimpublic.io.docs. private private private private private static String String Random Thread final String IMAGE_TYPE = “.rim.awt. java.java * Copyright (C) 2001-2004 Research In Motion Limited.httppush.device pin&gt.application.port&gt. notificationThread.reliable. Example: HTTPPushServer. javax.border. private static final String DEVICE_PIN = “2100000A”. */ package com. _panel.property file (push.*.device_port&gt.Color.2. requestTemplate.*.swing. Start up both the device simulator and MDS before executing * this program.*. /** * <p>The HTTPPushServer class provides a simple PUSH server sample.*.ports): * <code>push.png”.reliable.ResourceBundle. random= new Random().samples.

try { if ((DevicePin == null) || (DevicePin.JTextArea(). } return _pushURL.JButton().add(_papButton). _textField = new javax. } _pushURL = new URL(“http”. _notification=new javax. * WARNING: Do NOT modify this code. setTitle(java.JTextField(DEVICE_PIN). _buttonGroup= new javax.swing. _textArea= new javax. _buttonGroup.JRadioButton(“pap”). 216 .JPanel().BlackBerry Java Development Environment Development Guide setLocation(100.ButtonGroup().swing. setResizable(false).length() == 0)) { DevicePin = DEVICE_PIN. notificationThread= new NotificationThread(). } private URL getPushURL(String DevicePin) { /** * The format of the URL is: * http://<host>:<port>/push?DESTINATION=<device pin>&PORT=<device_port>&REQUESTURI=<post uri> */ URL _pushURL = null.swing.JTextArea(). _rimButton= new javax.WindowEvent evt) { exitForm(evt).awt.ResourceBundle.JRadioButton(“rim”).setPreferredSize(getSize()).util.getString(“HTTPPushServer.swing. getContentPane(). } catch (MalformedURLException e) { System. } /** * This method is called from within the constructor to * initialize the form. _buttonGroup. _papButton= new javax.setLayout(null). “localhost”.getBundle(“com/rim/samples/docs/httppush/ resources”).swing.event. _panel.println(e.title”)).100).setLayout(null).swing. addWindowListener(new java. _pinField = new javax. } }). The content of this method is * always regenerated by the FormEditor.add(_rimButton). _sendButton = new javax.WindowAdapter() { public void windowClosing(java.toString()).awt.err. */ private void initComponents() {//GEN-BEGIN:initComponents _panel = new javax.JTextArea().swing. _label = new javax.swing. “/push?DESTINATION=”+ DevicePin +”&PORT=”+DEVICE_PORT+”&REQUESTURI=localhost”).swing. MDS_PORT.JTextField().swing. _panel.event.

50.event. _label.setBounds(10. 170. }//GEN-END:initComponents private void sendButtonMouseClicked(java. 40)._pinField.ResourceBundle.awt. _scrollPane._textField. _label. 300.setLabel(java.getString(“HTTPPushServer. 450). 30).getString(“HTTPPushServer.util.get (“Button. 50. _sendButton.add(_panel). _scrollPane.setBounds(10._label. } }).MouseAdapter() { public void mouseClicked(java.add(_rimButton).setVerticalScrollBarPolicy( JScrollPane.setBorder(new LineBorder(Color.setLineWrap(true).awt. 50.setBounds(10. _panel.util. _panel.setToolTipText(java.MouseEvent evt) {//GEN-FIRST:event_sendButtonMouseClicked String text =_textArea.250. _panel. _label.util. _papButton.util.getString(“HTTPPushServer. _textArea.setBounds(240.Color) javax. _panel. _panel. 150. 10.awt. _pinField. _pinField.getDefaults (). 210).getBundle(“com/rim/samples/docs/httppush/ resources”).toolTipText”)). 170. _panel. _rimButton.ResourceBundle.getString(“HTTPPushServer.setWrapStyleWord(true).background”)).event.VERTICAL_SCROLLBAR_ALWAYS).swing.setLocation(10. 0.event. _textArea. _panel.setSize(_sendButton. 270.16: Creating push BlackBerry Java Applications _textArea.getText().getBundle(“com/rim/samples/docs/ httppush/resources”).setBounds(170. 150). _sendButton.add(_label).add(_scrollPane). 30).add(_pinField).MouseEvent evt) { sendButtonMouseClicked(evt).label”)).setText(java. _sendButton. _label.setBounds(10.addMouseListener(new java.text”)). 217 .add(_textArea).getPreferredSize()). _label.ResourceBundle. 100).setToolTipText(java. 30).270.awt.ResourceBundle. _label.UIManager.toolTipText”)). getContentPane().swing.setEditable(false).JScrollPane(_notification).add(_sendButton). 270.getBundle(“com/rim/samples/docs/ httppush/resources”).BLACK)). JScrollPane _scrollPane = new javax.setBackground((java.setBounds(0.add(_papButton). _sendButton. _panel._sendButton. 170.getBundle(“com/rim/samples/docs/ httppush/resources”).

println( _resources.setRequestMethod(“POST”). } conn.disconnect().//Post the data to the proxy conn. System. int contentLength =conn.getString(“HTTPPushServer. notifyURL).getInputStream(). * param data the data to post * */ private void postData(String data) { String pushId=”pushID:”+random.out.println(_resources.BlackBerry Java Development Environment Development Guide if(_rimButton. out.&REQUESTURI=&lt.err.getString(“HTTPPushServer.toString()). HttpURLConnection conn =(HttpURLConnection)url.setRequestProperty(“X-RIM-Push-Reliability-Mode”. out.getOutputStream().readFully(someArray).status./push?DESTINATION=&ltdevice pin&gt.out.sendingToString”) + url.out.host&gt. and takes the form: * http://&lt.openConnection().”APPLICATION”).contentLengthDescription”)+ contentLength).getBytes()). System. } catch (IOException e) { System.println(e).isSelected()) papPush(text). try { URL url = getPushURL(_pinField.port&gt. conn. InputStream ins =conn. setupNotifyThread(). conn.post uri&gt.:&lt.isSelected()) postData(text).setRequestProperty(“X-RIM-PUSH-ID”. pushId).println(new String(someArray)).close(). DataInputStream dins = new DataInputStream(ins). dins. else if(_papButton.//For sending the data conn.//For receiving the confirmation conn. //Write the data OutputStream out = conn.&PORT=&lt. } } 218 .nextInt(). if (contentLength > 0) { byte[] someArray = new byte [contentLength].device_port&gt.setDoOutput(true).. //open the connection using the static member.setDoInput(true).getContentLength().write(data. }//GEN-LAST:event_sendButtonMouseClicked /** * <p>posts the specified data to the device * <p>The URL is hardcoded for the purposes of this demo. conn.status.setRequestProperty(“X-RIM-Push-NotifyURL”.getText()). System..

mdsConn. mdsHost. “multipart/related.out.toString() + “. “/pap”). URL mdsUrl = new URL(“http”. copyStreams(ins. = output. = output. ByteArrayOutputStream bouts = new ByteArrayOutputStream().”100”). = output. readPapTemplate(). } } private void papPush(String data) { String pushId=”pushID:”+random.setRequestProperty(“X-Wap-Application-Id”. } catch (Exception exception) { exception. mdsConn.openConnection().printStackTrace().getText()).setDoOutput(true). this.nextInt(). ““ + notifyURL). String errorCode = null. “/”). } } private void setupNotifyThread() { if( !notificationThread. notificationThread.setRequestProperty(“Content-Type”. mdsConn.txt”. pushId = “ + pushId). boundary=” + boundary). String boundary = ““.replaceAll(“\\$\\(pushid\\)”.println(“ sending PAP request to “ + mdsUrl. mdsConn. type=\”application/xml\”.setRequestMethod(“POST”). 219 . mdsConn.replaceAll(“\\$\\(notifyURL\\)”. mdsConn. mdsConn. boundary).toByteArray()).setRequestProperty(“X-Rim-Push-Dest-Port”. boundary = “asdlfkjiurwghasf”. System.replaceAll(“\\$\\(pin\\)”.isAlive() ) { notificationThread = new NotificationThread(). pushId). String output output output output = requestTemplate. setupNotifyThread().start().requestTemplate = new String(bouts.setAllowUserInteraction(false). try { String mdsHost = “localhost”.replaceAll(“\\$\\(boundary\\)”.setDoInput(true). ““ + _pinField.16: Creating push BlackBerry Java Applications private void readPapTemplate() { try { String papFilename = “com/rim/samples/docs/httppush/pap_push. bouts). HttpURLConnection mdsConn = (HttpURLConnection)mdsUrl. MDS_PORT. InputStream ins = new BufferedInputStream(new FileInputStream(papFilename)).

if (bytesRead <= 0) break. output = output. 0.awt. “EOL”).println(buffer).replaceAll(“\\$\\(deliveryMethod\\)”.replaceAll(“\r\n”.getResponseCode(). outs). if (httpCode != HttpURLConnection. “\r\n”). ByteArrayOutputStream response = new ByteArrayOutputStream(). output = output. copyStreams(new ByteArrayInputStream(output.exit (0).replaceAll(“\\$\\(headers\\)”. }//GEN-LAST:event_exitForm 220 . response).BlackBerry Java Development Environment Development Guide String deliveryMethod = “confirmed”. byte [] buffer = new byte[1024]. outs. “EOL”). OutputStream outs = mdsConn.event.out. } System.WindowEvent evt) {//GEN-FIRST:event_exitForm System. output = output.replaceAll(“EOL”. } } public void copyStreams(InputStream ins. data).getOutputStream(). “Content-Type: text/plain”). int httpCode = mdsConn. } } /** Exit the Application */ private void exitForm(java.println(“ encountered error on submission: “ + exception.HTTP_ACCEPTED) { throw new Exception(“MDS returned HTTP status: “ + httpCode).toString()). } } catch (Exception exception) { if (errorCode == null) { errorCode = exception. OutputStream outs) throws IOException { int maxRead = 1024. copyStreams(mdsConn. mdsConn.getBytes()).out.out.replaceAll(“\\$\\(content\\)”.) { bytesRead = ins.connect().read(buffer). for(.println(output). output = output.getInputStream()..getName(). System. System. bytesRead).replaceAll(“\n”. output = output. deliveryMethod).getClass(). output = output. int bytesRead.write(buffer.

close().swing. private javax.append((char)byteRead). PrintWriter output = new PrintWriter(clientSocket.swing. } } catch (Exception exception) { exception.read().swing.JRadioButton _papButton..JTextField _textField. private javax.append(str.do not modify//GEN-BEGIN:variables private javax. // End of variables declaration//GEN-END:variables public class NotificationThread extends Thread { public void run() { try { System. try { Socket clientSocket = serverSocket.JButton _sendButton.getOutputStream()).JScrollPane _scrollPane.close().JRadioButton _rimButton. InputStream input = clientSocket. private javax.setText(“Received notification:”). StringBuffer str= new StringBuffer().read(). Restarting. private javax.toString()). } _notification. while ((byteRead != -1) && (input.setSoTimeout(120000). _notification.”).swing. private javax. private javax.. while (true) { ServerSocket serverSocket = new ServerSocket(7778).”).show ().ButtonGroup _buttonGroup.printStackTrace(). int byteRead = input. } 221 . private javax. } serverSocket.out.JTextArea _textArea.swing. output. byteRead = input. private javax.JTextArea _notification.swing.JPanel _panel.swing. clientSocket.println(“Notification connection timeout. private javax. serverSocket.JTextArea _label.close().accept(). } catch (SocketTimeoutException ste) { System. } // Variables declaration .swing.available() > 0)) { str.println(“Waiting for notification on port “ + 7778 + “.JTextField _pinField.out.swing...swing.getInputStream(). private javax.swing.16: Creating push BlackBerry Java Applications /** * @param args the command line arguments */ public static void main (String args[]) { new HTTPPushServer().

BlackBerry Java Development Environment Development Guide } } } 222 .

The BlackBerry Integrated Development Environemnt organizes resources in a hierarchy based on inheritance. a string from the next closest locale is used. You can load the appropriate . The BlackBerry Java Application can switch languages. A ResourceBundleFamily object contains a collection of ResourceBundles. without requiring new resource bundles. depending on the locale of the BlackBerry device user. outside your source code. The net. Storing resources for a locale You can use the BlackBerry® Integrated Development Environemnt to compile each resource bundle into a separately compiled . Storing text strings in separate resource files has two benefits: • • Text translation is efficient because all of the text strings for a given locale are stored in a single file.cod files onto BlackBerry devices with the .api.rim.17 Localizing BlackBerry Java Applications Storing text strings in resource files Storing resources for a locale Files required for localization Add localization support Retrieve strings from a resource file Code samples Storing text strings in resource files Design BlackBerry® Java® Applications so that they are localized (adapt to specific languages and regions) without coding changes. A ResourceBundle object stores the resources for a locale. .cod files for the BlackBerry Java® Application.device. based on the locale of the BlackBerry device user. which groups the resources for a BlackBerry Java Application. If you do not define a string in a locale. Note: MIDP applications do not support localization. BlackBerry Java Applications can dynamically retrieve the appropriate text to display to the BlackBerry device user.i18n package includes the Localization API. store text strings in separate resource files. In your source code. The BlackBerry Java Development Environment includes a mechanism for creating string resources. Instead of including textual elements in your source code. use unique identifiers that map to the appropriate resource files.cod file.

Close the file. 2. 5. 3. Two-letter language and country codes are specified in ISO-639 and ISO-3166. In the BlackBerry IDE. for example ApplicationName. browse to the location of the resource header file and select *. correctly. followed by an AppName_en_GB. The path should appear in the Location field. In the Files tab. confirm that the resource header file displays the package name correctly. Click OK.rrh) file.java Add localization support Task Add resource header files. 10. Steps 1. if you create AppName. 8.rrc Example AppName. In the Add resource header (.rrh.rrc country). optionally. Highlight the resource header file and select Open.rrh file name.rrh. Right-click the project and select Add File to Project Name. init. 224 . respectively. 9. Click OK. 4. 6. In the File name field. Initialization file This file initializes the resource bundle mechanism. Resource content file (root This file maps resource keys to string values for the root (global) locale. In the text editor. Files have the same name as the resource header file. select File -> New. Resource content file (specific locales) AppName. type a name. ensure that the package name has been populated. It has the locale) same name as the resource header file. From the Files of Type drop-down list. it creates a resource interface with Resource appended to the .java source files of the application and then click OK. This file is required only when you compile resources as a separate project. Browse to the location of the . When the BlackBerry® Integrated Development Environment builds a project. The file name should follow the proper format of the resource header file specified above. select Other from the list of available file formats.rrh This file maps resource keys to string values for specific locales (language and AppName_en. 12. For example. an underscore (_) and AppName_fr.rrh. the interface is named AppNameResource. where Project Name is the name of the project.BlackBerry Java Development Environment Development Guide Files required for localization File required for localization Resource header file Description This file defines descriptive keys for each localized string.rrc country code. 7. and then.rrc underscore (_) and the language code. 11.

On the Resources tab. If you do not provide a resource for the BlackBerry Java Application title. such as APPLICATION_TITLE. select a description ID. visit http://www. In the File name field. Add resource keys: • To add one value per key: On the Root tab. In the Files tab.17: Localizing BlackBerry Java Applications Task Add resource content files. select the tab for a locale. browse to the location of the resource content file and select *. right-click a resource and click Convert to Multiple Values. type a name of the root resource content file. select the resource to use for the BlackBerry Java Application title. 3.java. This name should correspond to the application name with the extension . From the Files of Type drop-down list. type resource keys and values for each string or string array in your BlackBerry® MDS Java®Application.java source files of the application and then click OK. and CountryInfo_fr.rrc (i. 6. select the Title Resource Available option. 9.rrc). 1. select the resource header file name to use for this BlackBerry Java Application. Add one or more values to the array. Right-click the project and select Add File to Project Name. CountryInfo_en. 8.rrc(English) or _fr_rrc(french). 3. 4.unicode. 225 . If you do not define a value for a resource in a particular locale. type the text string for the locale. 4. In the resource editor. 1. 2. From the Resource Bundle drop-down list. 5. select Yes. ApplicationName. 5. Click OK. where Project Name is the name of the project. 7.java file exists. the BlackBerry Java Application uses the value you type in the Title field on the Application tab of the Project Properties window as the BlackBerry Java Application title. In the BlackBerry® IDE. Steps Create resource content files in the folder where the . In the Value cell for the resource. 3. Display a localized BlackBerry® Java® Application title on the Home screen. Add resources. From the Description Id drop-down list. For example. such as fr for the French language.rrc (French). To specify a different text string in other locales.e.rrc (root locale). select File -> New. in the folder that contains CountryInfo. 4.org. For more information about unicode characters. add a resource for the BlackBerry Java Application title. 2. 7. For example. In the BlackBerry IDE. right-click the BlackBerry Java Application project. 6. • To add multiple values per key: In the resource editor. create CountryInfo. such as APPLICATION_TITLE. Highlight the resource content file and select Open. double-click a resource header file. You can type unicode characters directly into the Value cell. In the BlackBerry® IDE.rrc. From the Title Id drop-down list. 1. The path should appear in the Location field. and then click Properties. If prompted to save changes. _en. select Other from the list of available file formats. 2. Type a value for this resource in each locale that you support.rrc (English). the value for the root locale is used. Browse to the location of the .

BlackBerry Java Development Environment Development Guide See “Code sample: Storing text strings in separate resources for locales” on page 228 for more information.BUNDLE_ID. See “Code sample: Retrieving strings from a resource file” on page 230 for more information. To retrieve the appropriate bundle family.getString(FIELD_TITLE))). Retrieve strings from a resource file Task Retrieve the resource bundle. String choices[] = _resources.ELLIPSIS | LabelField. MENUITEM_VIEW. 3. LabelField title = new LabelField(_resources. resources. Import the interfaces that the BlackBerry IDE creates. 2. for a BlackBerry Java® Application. > Use the MenuItem constructor that accepts a resource bundle and a resource instead of a String for the name of the menu item. Steps When the BlackBerry® Integrated Development Environment builds your project. replace the text string with the appropriate resource. Invoke getString() or getStringArray() to retrieve the string for the appropriate language. choiceField = new ObjectChoiceField(_resources. 1.resource.pushScreen(_infoScreen). private MenuItem _viewItem = new MenuItem(_resources. 10) { public void run() { select = choiceField.BUNDLE_NAME). LabelField.USE_ALL_WIDTH). } } Replace text strings with the appropriate 1.docs. invoke getBundle().getBundle(CountryInfoResource. _infoScreen = new InfoScreen().getStringArray(FIELD_COUNTRIES). private static ResourceBundle _resources = ResourceBundle.rrh resource file. CountryInfoResource. import com. such as strings. 2. it creates an interface for each .CountryInfoResource. Create menu items using resources. For each field that appears on the main screen. UiApplication. 110.rim.getString(FIELD_CHOICE).getUiApplication(). 226 . Create a ResourceBundle object to contain the localized resources.getSelectedIndex(). choices). add(new RichTextField(_resources.samples.getString(APPLICATION_TITLE).

create a single library project for all resource header (.rrh) files and set the project type to Library. 4. The output file names for all resource locale projects must be the same as for the root locale. the language code. In each resource project. type a name for the compiled file. Open the BlackBerry® Integrated Development Environment. package com. 8. com_company_app__en_GB. right-click each . import net. 7. Create a project for each resource bundle (locale).17: Localizing BlackBerry Java Applications Manage resource files for BlackBerry Java Application suites If you are creating a suite of BlackBerry® Java® Applications. 2. Create an initialization file.resource. Add the resource content (. Add the resource header files to each resource project. Give the projects for each locale the same name as the project for the root locale.api. Specify output file names.i18n.device. so that you only need to create an empty initialization class with an empty main(). 1. organize resources into separate projects for each locale. 6. if the root locale project is named com_company_app. > The BlackBerry® IDE provides a built-in initialization mechanism. Select Dependency only. including the root locale. 2. If you support a large number of locales. 5.rrc) files to the projects for the appropriate locales. optionally.rrh file. 2. Do not build.samples. 3. 1. Create one resource header file for each BlackBerry® Java® Application. an underscore (_) followed by the country code. Steps 1. and then click Properties. and com_company_app__fr. Add the resource header (. and then click Properties. For each resource locale in this project. 227 . in the Output file name field. For example. On the Build tab. define a dependency between the projects. without a file name extension. followed by a double underscore and the appropriate language and country codes.*.rim. Task Create resource projects. public class init { public static void main (String[] args) { } } Add files to appropriate resource projects. 3.rrh) files to the project for each BlackBerry Java Application.rim. followed by a double underscore (__).device. Create one resource content file for each supported locale. and. Create one resource content file for each BlackBerry Java Application. Right-click the project. the projects for each locale would be named com_company_app__en.

*.java /** * CountryInfo.BUNDLE_ID.api.i18n.*.getString(FIELD_TITLE))).rim. setTitle(title).rim. import import import import import import net.api.*. private ObjectChoiceField choiceField.ui.samples.device.USE_ALL_WIDTH).enterEventDispatcher(). net.countryinfo.rim. net.ELLIPSIS | LabelField.samples.docs. } } final class HelloWorldScreen extends MainScreen implements CountryInfoResource { private InfoScreen _infoScreen.BlackBerry Java Development Environment Development Guide Code samples Code sample: Storing text strings in separate resources for locales Example: CountryInfo.getString(APPLICATION_TITLE).getStringArray(FIELD_COUNTRIES). All rights reserved.api.rim.container.device. theApp.ui. net.*.getBundle( CountryInfoResource. com.device.device. you retrieve the string from the resource to display the appropriate text for the user locale. LabelField title = new LabelField(_resources. CountryInfoResource. LabelField.device. private int select. In your source code. public HelloWorldScreen() { super().rim.ui.*. */ public class CountryInfo extends UiApplication { public static void main(String[] args) { CountryInfo theApp = new CountryInfo().api. } public CountryInfo() { pushScreen(new HelloWorldScreen()). private static ResourceBundle _resources = ResourceBundle. choices). choiceField = new ObjectChoiceField( _resources.api. } public boolean onClose() { 228 .rim.*. */ package com.resource. add(choiceField).BUNDLE_NAME). String choices[] = _resources.docs.java * Copyright (C) 2001-2005 Research In Motion Limited.component. add(new RichTextField(_resources.rim. /* This sample demonstrates how to store text strings in separate resource files for specific locales rather than providing text strings directly in the code.system. net.getString(FIELD_CHOICE).

110. add(citiesField). } private MenuItem _viewItem = new MenuItem(_resources.getString(FIELD_US_CITIES)).getSelectedIndex().setText(_resources. popField. citiesField.add(_closeItem). add(new SeparatorField()).setText(_resources. int instance ) { menu.getString(FIELD_CHINA_POP)). null.setText(_resources. } else if (select == 2) { lf. LabelField lf = new LabelField(). citiesField.setText(_resources.READONLY). } }.getString(FIELD_US)).alert(_resources. } private class InfoScreen extends MainScreen { public InfoScreen() { super(). MENUITEM_VIEW. langField.READONLY).setText(_resources.getString(FIELD_CHINA_LANG)). BasicEditField langField = new BasicEditField( _resources.setText(_resources. langField. } } 229 . protected void makeMenu( Menu menu. popField.getString(FIELD_GERMANY)).getString(FIELD_US_POP)). UiApplication. _infoScreen = new InfoScreen(). BasicEditField popField = new BasicEditField( _resources. 50.getString(FIELD_CITIES).setText(_resources. 20.setText( _resources. 10) { public void run() { select = choiceField.getString(CLOSE)). add(langField). add(lf).setText(_resources. return true.READONLY).getString(FIELD_LANG).getString(FIELD_CHINA)).getString(FIELD_CHINA_CITIES)). menu.getString(FIELD_GERMANY_LANG)).17: Localizing BlackBerry Java Applications Dialog. System.pushScreen(_infoScreen).getString(FIELD_POP). private MenuItem _closeItem = new MenuItem(_resources. Field. } }.setText(_resources. } else if (select == 1) { lf.setText(_resources. null. popField. 10) { public void run() { onClose(). 200000.getString(FIELD_US_LANG)). BasicEditField citiesField = new BasicEditField( _resources. MENUITEM_CLOSE.getUiApplication(). Field.getString(FIELD_GERMANY_POP)).setText(_resources.add(_viewItem). 20. citiesField. add(popField). Field. null. langField.exit(0). if (select == 0) { lf.getString(FIELD_GERMANY_CITIES)).

api.enterEventDispatcher().USE_ALL_WIDTH).BUNDLE_ID.resource.api.getBundle( CountryInfoResource.ELLIPSIS | LabelField. */ package com.*. In your source code. } public CountryInfo() { pushScreen(new HelloWorldScreen()). you retrieve the string from the resource to display the appropriate text for the user locale.container.rim. net. LabelField. public HelloWorldScreen() { super(). add(new RichTextField(_resources.system. private static ResourceBundle _resources = ResourceBundle.BUNDLE_NAME).docs. LabelField title = new LabelField(_resources.countryinfo.*. private ObjectChoiceField choiceField.component. import import import import import import net.device.samples.ui.rim.getString(APPLICATION_TITLE). All rights reserved. CountryInfoResource.*. */ public class CountryInfo extends UiApplication { public static void main(String[] args) { CountryInfo theApp = new CountryInfo().rim. setTitle(title).samples.getStringArray(FIELD_COUNTRIES).getString(FIELD_CHOICE). net.device.api.device.i18n. 230 .api.ui.api.docs. net. /* This sample demonstrates how to store text strings in separate resource files for specific locales rather than providing text strings directly in the code. com.*.rim. private int select.rim.getString(FIELD_TITLE))).device.*.*.BlackBerry Java Development Environment Development Guide } } Code sample: Retrieving strings from a resource file Example: CountryInfo.rim.java (with localization support) /** * CountryInfo.rim.ui. theApp. add(choiceField).device. } } final class HelloWorldScreen extends MainScreen implements CountryInfoResource { private InfoScreen _infoScreen. choiceField = new ObjectChoiceField( _resources. net.java * Copyright (C) 2001-2005 Research In Motion Limited. String choices[] = _resources. choices).

alert(_resources. int instance ) { menu. private MenuItem _closeItem = new MenuItem(_resources. BasicEditField citiesField = new BasicEditField( _resources. return true.setText( 231 . 50.getUiApplication(). add(langField). 10) { public void run() { onClose().getString(FIELD_CHINA_LANG)).setText(_resources. System. LabelField lf = new LabelField(). 20. UiApplication. null.getSelectedIndex().setText(_resources.setText(_resources. } else if (select == 1) { lf.getString(FIELD_GERMANY)).setText(_resources.getString(FIELD_US_LANG)).getString(FIELD_GERMANY_POP)). add(lf).setText(_resources. 20.READONLY). Field. 10) { public void run() { select = choiceField.pushScreen(_infoScreen). } else if (select == 2) { lf.add(_closeItem).getString(FIELD_US_POP)). langField. BasicEditField popField = new BasicEditField( _resources.setText(_resources. MENUITEM_CLOSE. _infoScreen = new InfoScreen().getString(FIELD_CHINA)).getString(FIELD_US)).17: Localizing BlackBerry Java Applications } public boolean onClose() { Dialog. Field.getString(CLOSE)).READONLY). null. if (select == 0) { lf. citiesField. popField.setText(_resources. } private class InfoScreen extends MainScreen { public InfoScreen() { super(). menu. MENUITEM_VIEW.setText(_resources.READONLY). langField.setText(_resources. add(citiesField). } }. Field. } private MenuItem _viewItem = new MenuItem(_resources.getString(FIELD_US_CITIES)).setText(_resources. 200000. popField. add(new SeparatorField()).getString(FIELD_LANG). } }. BasicEditField langField = new BasicEditField( _resources. 110.setText(_resources.add(_viewItem). null. citiesField.getString(FIELD_POP).getString(FIELD_CHINA_CITIES)).getString(FIELD_GERMANY_LANG)). citiesField. protected void makeMenu( Menu menu. popField.getString(FIELD_CHINA_POP)). langField.getString(FIELD_CITIES). add(popField).exit(0).

} } } } 232 .BlackBerry Java Development Environment Development Guide _resources.getString(FIELD_GERMANY_CITIES)).

In the BlackBerry Desktop Manager window. Run the BlackBerry® Java® Application. 3. Task Set the connection. 2. click USB. 3. After the BlackBerry® Device Simulator starts. In the Connection drop-down list. 4. Click OK. 5. select USB cable connected. In the Ports tab. Detect the BlackBerry Device Simulator. you should test it on the BlackBerry device. start the BlackBerry Desktop Manager. Use the BlackBerry Device Simulator to test synchronizing data with the BlackBerry Desktop Software To complete the following instructions. on the Options menu. 4. 1. on the Options menu. Build and run the BlackBerry Java Application in the BlackBerry IDE. You can download additional BlackBerry Device Simulators as they are available on the BlackBerry Developer Zone. click Preferences. From the main menu. Open the BlackBerry Integrated Development Environment. Click Detect to detect the BlackBerry Device Simulator. 1.18 Testing BlackBerry Java Applications Testing BlackBerry Java Applications using the BlackBerry IDE Testing BlackBerry Java Applications using BlackBerry devices Debugging BlackBerry Java Applications Testing BlackBerry Java Applications using the BlackBerry IDE After you develop and compile your BlackBerry® Java® Application. Click OK. Close the BlackBerry® Desktop Manager. 2. click Connection Settings. The most common first step is to set up the BlackBerry Integrated Development Environment to use a BlackBerry Device Simulator for testing. 2. so they provide an environment for testing how BlackBerry Java Applications will function on a live BlackBerry device. . Each version of the BlackBerry Java Development Environment comes with the BlackBerry Device Simulators that are available when Research In Motion released that version of the BlackBerry JDE. 3. The BlackBerry Device Simulators run the same Java code as the live BlackBerry devices. the BlackBerry® Desktop Manager must exist on your computer. In the Desktop Manager window. See the BlackBerry Integrated Development Environment Online Help for information on starting the BlackBerry Device Simulator when you run a BlackBerry Java® Application in the BlackBerry Integrated Development Environment. click Connection Settings. Steps 1.

To connect a BlackBerry device that uses a USB port.println(foo). type a positive integer. Execute code and print values to > the Output window when code exectution reaches a Breakpoint. Use breakpoints In the breakpoints pane. > > In the Resume if true field. When BlackBerry® Java® Application execution reaches the breakpoint. This can be useful if you are trying to identify a network issue. type System. you can open and test its functionality and performance. 234 . Stop the BlackBerry® Java® Application after a a specific number of iterations through a breakpoint. type an expression. Open the BlackBerry Integrated Development Environment. See the BlackBerry Java Development Environment Fundamentals Guide for more information about code signing keys. you might require code signing keys. type an expression. a Bluetooth wireless technology issue. BlackBerry Java Application execution resumes if the expression evaluates to true. Connect the BlackBerry IDE to a BlackBerry device 1. where PIN is the PIN of the BlackBerry device that is connected to the computer. attach your BlackBerry device to the BlackBerry Integrated Development Environment debugger to step through your BlackBerry Java Application code. In the Iteration field. you can perform any of the following actions: Task Steps In the Execute when hit field. Debugging BlackBerry Java Applications When you connect a BlackBerry® device to a computer to perform testing and optimization of code. Open the source code at a set breakpoint. For debugging purposes. or other items that are difficult to simulate accurately . execution stops when the number of iterations through a breakpoint equals the number you tyepd.out. click Debug > Attach to > Handheld > USB<PIN>. If your BlackBerry Java Application uses signed APIs. When the BlackBerry Java Application loads. 2. load your BlackBerry Java Application on a live BlackBerry device. run BlackBerry Java® Applications on the BlackBerry device and use the BlackBerry Integrated Development Environment debug tools. Connect a BlackBerry® device to the computer.BlackBerry Java Development Environment Development Guide Testing BlackBerry Java Applications using BlackBerry devices After testing your BlackBerry® Java® Application on the BlackBerry Device Simulator. When you start debugging. For example. 3.

See the BlackBerry Device Simulator User Guidefor more information. 10. click Quit. 2. on the File menu. Open the source file. On the Debug menu. Debug a BlackBerry Java Application in the BlackBerry IDE 1. To resume debugging your BlackBerry Java Application. and then gradually set breakpoints at shorter intervals to identify the problem. and . 3.cod. in the BlackBerry Device Simulator. In the breakpoints pane.18: Testing BlackBerry Java Applications Task Steps In the Condition field.csl. on the Debug menu. Remove all breakpoints. use the BlackBerry email server simulator. Without access to a BlackBerry Enterprise Server. Open the BlackBerry Integrated Development Environement. . 6. To debug BlackBerry Java Applications that send and receive messages between a BlackBerry Device Simulator and a computer email application. 9. use debugging tools to view various BlackBerry Java Application processes and statistics. Remove a breakpoint. HTTP/TCP connections to third-party applications. To stop debugging your BlackBerry Java Application. In the Edit window. click Continue. 1. Add your BlackBerry Java Application to the workspace. On the Debug menu.cso. 4.debug. Copy the BlackBerry Java Application . 5. 1. and push functionality. 2. . Stop the BlackBerry® Java® > Application when a condition is true. In the BlackBerry Device Simulator window. Start any simulators that your BlackBerry Java Application requires. you need the BlackBerry MDS™ Simulator to simulate browser traffic. To identify the problem. after the BlackBerr®y Java® Application pauses at a breakpoint. test the relevant sections of code. click Breakpoint > Delete Breakpoint at Cursor. 8. . On the Debug menu.3\simulator 2. 235 . On the View menu. The Hits field calculates the number of times the BlackBerry Java Application stops at a breakpoint when the Condition is true or the Condition field is emtpy. One debugging method is to start by setting only a few breakpoints at critical sections of your code. click Delete All. 3. such as x==100. Add and set up a workspace for your BlackBerry Java Application. click Break Now.jar files into the BlackBerry® Device Simulator root directory: C:\Program Files\Research In Motion\BlackBerry JDE 4. click Go. The BlackBerry IDE builds all active projects in the workspace and loads the BlackBerry Java Applications in the BlackBerry Device Simulator. click the line of code that contains the breakpoint to remove. type a Boolean expression. click Breakpoints. 7.

Locate an error in the source code 1. Note: To connect the BlackBerry Integrated Development Environment to a BlackBerry device using a USB port. Integrated Development Environment. contain . Steps > To resume running the BlackBerry® Java® Application. set a breakpoint on a line of code. In the Output window. Steps > > Press F4. on the Debug menu. on the Debug menu. 2. click Stop Debugging. If you agree.debug files on your computer To debug BlackBerry® Java® Applications using a BlackBerry device. 2. 3. 236 . Debug a BlackBerry Java Application on a BlackBerry device To perform testing and optimization for BlackBerry® Java® Applications on a BlackBerry device that is connected to your computer. BlackBerry Device Simulator packages. Perform one of the following actions: Task View the next error. install the BlackBerry Desktop Software Version 3. click Break Now.debug files for specific BlackBerry devices. Read the warning message. In the BlackBerry Device Simulator. Interrupt a debugging session without stopping a BlackBerry® Java® Application.5.1 or later.debug files in the BlackBerry Integrated Development Environment must match the software version number of the BlackBerry device. which you can download from the BlackBerry Developer Zone. Install .BlackBerry Java Development Environment Development Guide Manage a debugging session Task Continue a debugging session. on the File menu. > In the main window. Press SHIFT+F4 Run a BlackBerry Java Application to the insertion point 1. click Yes. End a debugging session in the BlackBerry® 1. In the main window. Return to the previous error. the . double-click the error message. on the Debug menu. click Continue. click the line of code at which you want to stop the BlackBerry® Java® Application. In the Edit window. click Run to Cursor. In the Debug menu. click Quit. 2. use the BlackBerry Integrated Development Environment debugging tools. End a debugging session in the BlackBerry® > Device Simulator. Tip: To stop execution at a specific location.

Connect the BlackBerry device to the computer. on the Debug menu.debug files. where PIN is the PIN of the BlackBerry device. You must also specify the -usb option.debug files are located in the Debug directory of the BlackBerry Device Simulator package installation directory. Exit the BlackBerry Desktop Software. In the Handheld debug file location field. Click the Other tab. if a password for the BlackBerry device is set. 1. Note: BlackBerry device users should use the BlackBerry Desktop Software to load BlackBerry Java Applications onto their BlackBerry devices. 5. The . 6. 3. Connect the BlackBerry IDE to a BlackBerry device > In the BlackBerry® IDE. 237 . Connect a BlackBerry device to the computer. Click the Debug tab. on the Edit menu. At a command prompt. 2. Download the BlackBerry Device Simulator package for your BlackBerry device software version number from the BlackBerry Developer Zone at: http://blackberry. In the BlackBerry IDE.com/developers/downloads/simulators 2. This paramter specifies one or more . Load BlackBerry Java Applications onto a BlackBerry device For development and testing purposes.0\bin 4. You can now run your BlackBerry Java® Applications on the BlackBerry device and use the BlackBerry Integrated Development Environment debugging tools to test and optimize your BlackBerry Java Application. type the location of the downloaded . use JavaLoader. 4. This paramter specifies the password for the BlackBerry device. click Attach to > Handheld > USB (PIN).18: Testing BlackBerry Java Applications 1. 3.cod files to load onto the BlackBerry device.3. See “Connect the BlackBerry Integrated Development Environment debugger to a BlackBerry device” on page 239 for more information about connecting a BlackBerry device to a computer. Type the following command: JavaLoader [-usb] [-pport] [-bbps] [-wpassword] load file Parameter port password file Description A BlackBerry device PIN if the BlackBerry device connects to a USB port. switch to the following directory: c:\Program Files\Research In Motion\BlackBerry JDE 4. click Preferences.exe to load BlackBerry® Java® Applications onto a BlackBerry device.

BlackBerry Java Development Environment Development Guide

Step through lines of code in a BlackBerry Java Application
In the main window, on the Debug menu, perform any of the following commands:
Task Step over a method call. Steps The BlackBerry® Integrated Development Environment debugger moves to the next line of code. If the source line is a method call, the BlackBerry Java® Application runs the entire method without stepping through the individual method instructions. The BlackBerry® IDE debugger moves to the next line of code. If the source line is a method call, the BlackBerry Java® Application stops just before running the first statement of the method. The BlackBerry® IDE debugger moves to the next line of code. If the source line is part of a method, the BlackBerry Java® Application runs the remaining lines of the method and returns control to the caller of the method.

Step through method instructions.

Step out of method instructions.

For example, to step into function “f” in the following line of code f(g(x)), perform the following actions: 1. Click Step Into to run the BlackBerry Java Application into “g” 2. Click Step Out to return the BlackBerry Java Application to the line of code. 3. Click Step Into again to run the BlackBerry Java Application into function “f"

View statistics to locate memory leaks
To locate memory leaks, use the Memory Statistics tool with the Objects tool. Begin by using the Memory Statistics tool to retrieve information on the memory usage of your BlackBerry® Java® Application. The Memory Statistics tool identifies the number of objects in memory, while the Objects tool displays detailed information for each object. The Memory Statistics tool displays the statistics on the number of objects and bytes in use for object handles, RAM, and flash memory.

Locate a memory leak
1. Set two or more breakpoints in your code. 2. Open the BlackBerry® Integrated Development Environment. 3. On the Debug menu, click Go. The BlackBerry Java® Application runs to the first breakpoint. 4. In the main window, on the View menu, click Memory Statistics. 5. In the memory statistics pane, click Refresh. 6. Click Snapshot. 7. On the Debug menu, click Continue. The BlackBerry Java Application runs to the second breakpoint. 8. In the memory statistics pane, click the Refresh tab. 9. Click Compare to Snapshot. 10. Repeat steps 1 through 8, setting breakpoints closer together until they converge on the memory leak.

238

18: Testing BlackBerry Java Applications

Display objects in memory to locate object leaks
Object leaks can cause the BlackBerry® JVM to run out of flash memory, which forces a BlackBerry device to reset.

Display format
The Name column displays each process in the following format: process_name(process_id): status where status is one of the following: Add, Delete, Referenced by code, Referenced by static, Grouped, Persistent, or RAM.
Status Add or Delete Referenced by code or Referenced by static Description This status appears when you perform a Compare to Snapshot to indicate new or removed objects since the last snapshot. This status appears when a code (a local variable) or static data member references the variable.

Use the Objects tool to locate a memory leak
1. In the BlackBerry® Integrated Development Environment, on the Debug menu, click Go. 2. On the Debug menu, click Break Now. 3. On the View menu, click Objects. 4. In the objects pane, click GC. 5. In the objects pane, click Snapshot. 6. On the Debug menu, click Continue. 7. Perform operations in the BlackBerry Java® Application that do not increase the number of reachable objects. For example, create a new contact and then delete it. 8. On the Debug menu, click Break Now. 9. In the objects pane, click GC. 10. Click Compare to Snapshot. The objects pane displays the number of objects deleted and added since the previous snapshot. If the number of objects added is not the same as the number of objects deleted, you might have an object leak. To narrow new objects, use the Type, Process, and Location filters located at the top of the objects pane. 11. To save the contents of the objects pane to a comma separated values (.csv) file, click Save.

Show references to or from an object
> In the objects pane, right-click an object, and then click Show References to or Show References From. The object view narrows to show only the objects that have references to or from this object. Use the Forward and Back buttons to move back and forth through the reference chain.

239

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 code or static. Click Forward and Back to move back and forth through the reference chain.

View local variables
1. On the View menu, click Locals. 2. Perform one of the following tasks:
Task View local variables and their current values in the context of the current thread. View local variable names and expressions at and around the executing line. View an expanded view of the current object (this). Evaluate expressions. Steps > > > > Click the Locals tab. Click the Auto tab. Click the This tab. Click the Watch tab.

View variable or expression information
Task View a value for a variable. Steps 1. Point the insertion point at a variable. Press the CTRL key and click an expression. 2. Press the CTRL key and click a variable. View a value for an expression. 1.

View static data
The static data pane displays the static data members of the current class. The following options are available when you right-click the static data pane: • • • • Change the display of the Value field. Set a watch on a variable. View the source code of a variable's defining class. When the BlackBerry® Java® Application modifies an item, stop the BlackBerry Java Application.

240

18: Testing BlackBerry Java Applications

Evaluate (watch) Java expressions
The Watch pane enables you to specify variables and expressions to watch continuously while debugging your BlackBerry® Java® Application. 1. Right-click the Watch pane. 2. Perform one of the following tasks:
Task Set a new watch. Remove a watch. Remove all watches. Steps > > > Click Add Watch. Click Delete. Click Delete All.

See "View threads" on page 241 for more information about viewing the format of threads appearing in the watch pane. See "View the data members of a process" on page 242 for more information about viewing the format of processes appearing in the watch pane.

View threads
The threads pane displays all threads running on the BlackBerry® device. The most recent thread appears yellow. To view the source code in the text edit pane, double-click a thread. The BlackBerry Integrated Development Environment marks the line in the source code that starts the thread with an arrow.

Thread format
The Thread column displays each thread in the following format:
name(pid): status

where: • • • name is the name of the process that starts the thread pid is the ID of the process that starts the thread status is one of the following:
Status running sleeping waiting for notify acquiring lock Description thread is running thread is calling Thread.sleep() thread is calling Object.wait() thread is executing a “synchronized” statement and is being forced to wait

241

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.

Expand objects
In the threads pane, the following fields indicate the status of an object: • • • thread that currently owns the object (Thread owning lock: @nnnnnnnn) thread that calls Object.wait() (Thread waiting for notify: @nnnnnnnn) thread that attempts to enter a synchronized block for the object (Thread acquiring lock: @nnnnnnnn)
Note: Threads, and objects whose threads are deadlocked, also display in the following panes: objects, local variables, watch, static data, processes and locks. To update the context of the selected thread in all the debugging panes, right-click in the threads pane, and then click Make current.

View the data members of a process
The processes pane lists all the processes that are currently running in the BlackBerry® Integrated Development Environment. You can expand each process to view its data members. The Process column displays each process in the format: process_name(process_id). > To view data members, in the Process column, expand a process.

View the call stack
The call stack pane displays the calling methods at the current point of execution.

View the source code of a calling method
1. Right-click a method. 2. Click Show Definition. The source file appears in the Edit window at the line of code that implements the class of the selected item. All BlackBerry® Integrated Development Environment panes update to reflect the new context.
Note: The first calling method that appears in the call stack pane is located at the bottom of the call stack.

View event logs
The event log pane displays all exception messages that the BlackBerry® Integrated Development Environment produces when you run a BlackBerry Java® Application in the BlackBerry Device Simulator or on a BlackBerry device. To identify an error that has occurred, use the event log pane to view the source code that caused the error message.

242

2. Set the BlackBerry® Integrated Development Environment to trigger a breakpoint when the code throws an object of the selected class. In the profile pane. use the profiler tool of the BlackBerry® Integrated Development Environment. set the following options: Drop-down list Method attribution Option Cumulative In method only Description The profiler tool calculates the time spent executing bytecode in a method and all methods that the method invokes. Click Break when exception thrown. Perform one of the following tasks: Step Click Source code. click Options. View classes Select a subset of classes Type the Class Name Prefix and press ENTER. classes that start with the string typed in the Class Name Prefix field appear. Set the BlackBerry® IDE to trigger a breakpoint when an object of the selected class is instantiated. The profiler tool displays the percentage of time spent in each code area to the current point of execution. View the methods in a class The methods pane displays all methods in a class. Note: To improve the quality of results when you run the profiler tool. on the Build tab.18: Testing BlackBerry Java Applications View the source of a logging message > In the event log pane. Set profile options 1. The methods pane updates to display all methods in the selected class.lang. In the classes pane. exit other Microsoft® Windows® applications. type java. The timer stops when a call is made to another method. Click Break on new object. 1. Optimize source code using the BlackBerry Integrated Development Environment profiler tool To optimize your code. Task > > > Display the source code that implements the selected class. double-click a class. In the classes pane. For example. 2. The profiler tool calculates the time spent executing bytecode in that method only. right-click a class. In the classes pane. double-click the error message. On the General tab. 243 .

Click OK. The profiler tool considers the number of objects the BlackBerry Java Application created. click Options. 8. 5. Click the Colors tab to change the colors of the source code highlighting. click Go. 3. click Clear. Generate profile data 1. 7.BlackBerry Java Development Environment Development Guide Drop-down list Sort method by Option Count Profiled data (select in “What to profile”) Description The profiler tool sorts methods in the profile pane by the number of times the BlackBerry® Java® Application executed the item The profiler tool sorts methods in the profile pane by the data you choose to profile The profiler tool considers execution time (measured in clock ticks). a sorting method. click Profile. on the View menu. 6. 10. 244 . The profiler tool considers the size of objects the BlackBerry Java Application created. If the profile pane is not visible. Set a breakpoint at the start of the section of code to profile. On the Debug menu. The debugger pauses the BlackBerry Java Application when it reaches the second breakpoint. The profiler tool considers the size of objects the BlackBerry Java Application moved into memory. The profiler tool considers the number of objects the BlackBerry Java Application committed. 4. On the Debug menu. In the profile pane. 9. On the View menu. Set a breakpoint at the end of the section of code to profile. run the BlackBerry Java® Application. In the BlackBerry® Device Simulator. 2. The profiler tool considers the size of objects the BlackBerry Java Application committed. click Go. This action removes the profiler data and sets the running time of Java® code to 0. 12. click Profile. In the profile pane. and the type of information to profile. The debugger pauses the BlackBerry Java Application when it reaches the first breakpoint. run the BlackBerry Java Application. The profiler tool considers the number of objects the BlackBerry Java Application moved into memory. Select the type of method attribution. 11. The profiler tool considers user counting. What to profile Time (clock ticks) Number of objects created Size of objects created Number of objects committed Size of objects committed Number of objects moved to RAM Size of objects moved to RAM User Counting 3. In the BlackBerry Device Simulator.

On the View menu. 2. Methods The Methods view displays a list of modules. The Source view displays the following items: • • A list of callers to the method. that method. Right-click a method. Click Save to save the contents of the profile pane to a comma separated values (. This action does not clear Profiler data. including the number of times that they make the call and the total time spent on these calls A list of source lines for the method and the total time spent on these lines You can expand a source line to show individual bytecode. Click one of the following tabs: View Summary Description The Summary view displays general statistics about the system and the garbage collector process. Right-click a line and select Show Source to view the source code in the Edit window. sorted either by the information that you are profiling or by the number of times the BlackBerry Java Application executed each item. click Refresh. This action retrieves all accumulated profile data from the BlackBerry JVM.csv) file. and performing quick and full garbage collection process. In this view. • • • • Expand the All item to see a list of all methods. You can further expand any bytecode that corresponds to a method invocation to show the target(s) of the method invasion. and the number of times the appplication ran the item. Source The Source view displays the source lines of a single method. the Percent column displays the percentage of VM execution time only. and are called by. not including idle and garbage collection time. and then click Profile Source to view source lines in the Source view. Right-click a method. The Percent column displays the percent of total BlackBerry JVM running time. 1. It displays the percentage of time that the BlackBerry® JVM spends idle. Expand a specific module to see only its methods. so running a BlackBerry Java Application again adds to the data. Each view contains details about an item of execution (such as a method). and then click Show Source to view source code in the Edit window. Analyze code coverage The Coverage tools display a summary of code that has run.18: Testing BlackBerry Java Applications 13. 245 . Click Back and Forward to follow the history of methods that you have visited in the Source view. Note: To view all accumulated data. click Profile. 14. View profile data The profile pane has three views. • Use profile views to view information about the section of code that you just ran. click Refresh. including idle and collection time. In the profile pane. the percentage of time the BlackBerry® Java® Application ran the item. executing code. You can navigate through the methods that call.

as shown in the following code: if( a ) { b. then “c” will never execute. You can work around this by rewriting the code to avoid the ternary operator. you must put the network connection request on a separate thread from the main thread so that it does not interfere with the process of the main thread. click Clear. On the View menu. double-click a method. your code might include the following statement: a ? b : c. The Coverage pane displays the percentage of code that you ran. in the coverage pane. the coverage tool displays accurate but misleading results. The BlackBerry Java Application locks because the connection request cannot complete until the BlackBerry device user approves it. 4. Approve HTTP connections The BlackBerry® device includes built-in security to prevent third-party BlackBerry Java® Applications from sending or receiving data without the knowledge of the BlackBerry device user.BlackBerry Java Development Environment Development Guide Run the Coverage tool 1. Run the BlackBerry® Java® Application to the first breakpoint. 6. Run the BlackBerry Java Application to the next breakpoint. This security feature causes network BlackBerry Java Applications to hang if a BlackBerry Java Application makes an HTTP connection from the main thread. To resolve this issue. View source code > In the coverage pane. For example. Note: When you use the ternary if-else operator. click Refresh. 3. and methods. Green bars in the source code indicate that the source code ran. a dialog box prompts the BlackBerry device user to turn the connection on or off. if “a” is always true. 2. and red bars in the source code indicate that the source code did not execute. however. click Coverage. classes. } The short-circuit logical operators && and || exhibit the same behavior. the UI cannot initiate a dialog box to prompt the BlackBerry device user to approve the connection attempt. Set two or more breakpoints in your code. 246 . in the coverage pane. It displays a nested view of packages. To reset information to 0. } else { c. When the main thread handles connection requests. To test this functionality on the BlackBerry Device Simulator. the coverage tool displays the statement as covered. To display the percentage of code that you ran since you clicked Clear. with the percentage of code executed in each. turn on the security function of the BlackBerry Device Simulator. 5. When a third-party BlackBerry Java Application attempts to open a connection.

247 . 8. On the Start menu. 2.1. 3. One or more email messages must exist inside the Inbox of the email account associated with the BlackBerry email simulator for the load test functionality to work. Check the command prompt window for detailed information about ESS startup. If you select Standalone mode. download the BlackBerry Email and MDS Services Simulator Package from the BlackBerry Developer Zone site: www. 7. The email client account must have the POP3 server set to localhost on port 110 and the SMTP server set to localhost on port 25. Click Load Test to select a message inside the associated Inbox and send it a number of times to a BlackBerry device.2 > ESS. Connected mode ESS polls the specified POP3 email server for incoming messages and uses the specified SMTP server to send messages. Select one of the following modes: Mode Standalone mode Description ESS stores messages on the local file system and communicates directly with the email client. click Clean FS to erase ESS messages that are on the local file system. Type information in the following fields: Field Name Email PIN Description name to display in outgoing messages from the BlackBerry Device Simulator email address to display in outgoing messages from the BlackBerry Device Simulator PIN that the BlackBerry Device Simulator uses (default is 21000000) 6. without a BlackBerry Enterprise Server. type information in the following fields: Field Outgoing Incoming User name Password Poll inbox Description host name of the SMTP server that your email account uses host name of the POP3 server that your email account uses user name with which to connect to your email account password with which to connect to your email account frequency with which the BlackBerry Device Simulator checks your email inbox for new messages 5. 4. To retrieve the BlackBerry email simulator.blackberry. Click Launch. You do not require a POP3 or SMTP server. If you select Connected mode. ESS can communicate with any email client that supports POP3 and SMTP communication. click Programs > Research In Motion > BlackBerry Email and MDS Services Simulators 4.com/developers 1.18: Testing BlackBerry Java 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. The Connected mode requires a Valid POP3 and SMTP server. including any login errors.

exe delete MyApplication. 1.jad) file RIM-COD-Module-Dependencies attribute.exe -u load MyApplication.cod files when testing BlackBerry® Java® Applications. the BlackBerry IDE compiles your source files into Java® bytecode. See “Appendix: BlackBerry Java Application .cod file For example: javaloader. Open a command prompt.cod files.cod JavaLoader loads the .cod files listed in the .cod file. and navigate to the location of the JavaLoader. If a BlackBerry Java Application contains more than 64 KB of bytecode or resource data. Remove a BlackBerry® Java® Application .cod file from the BlackBerry device.jad files” on page 271 for more information on BlackBerry Java Application .cod file on the BlackBerry device. Load BlackBerry® Java® Application . > Issue a command using the following format: javaloader [-u] erase [-f] module For example: javaloader. the BlackBerry IDE creates a . Steps > Issue a command using the following format: javaloader [-u] load .cod files.cod file contains sibling .cod file that contains sibling . If project A is dependent on project B.exe file. Perform one of the following actions: Task Load a BlackBerry® Java® Application . or save .cod file. use the JavaLoader.exe -u load MyApplication.jad file for a BlackBerry Java Application. Issue a command using the following format: javaloader delete . Connect the BlackBerry device to the computer. For production applications. 3. Note: You must load BlackBerry Java Applications with dependencies in the correct order. Any . To identify modules that a BlackBerry Java Application requires.exe tool.jad 248 .cod files > listed in the same .cod file and .cod file before loading the project A .cod file are the sibling files.jad file from the BlackBerry device.cod files in a CodeModuleGroup.jad file properties.BlackBerry Java Development Environment Development Guide Working with compiled BlackBerry Java Applications When you build a project using the BlackBerry® Integrated Development Environment. examine the BlackBerry Java Application descriptor (. Load and remove BlackBerry Java Applications To load.cod files listed in the same .exe -u erase MyApplication Remove BlackBerry® Java® Application . remove.cod files listed in the . 2.jad file onto the BlackBerry device.jad file on the BlackBerry device.jad file on the BlackBerry device and stores the . load the project B . use the BlackBerry Desktop Software. > Issue a command using the following format: javaloader [-u] load . performs preverification. and creates a single .jad file For example: javaloader. extract the contents of the .jad file For example: javaloader.cod files within the original . but are not provided with it.jad Javaloader loads the . To determine if a .

jad > Issue a command using the following format: javaloader save [-g] module Remove BlackBerry® Java® Application .cod file For example: javaloader. > Save BlackBerry® Java® Application . Size.cod file. Save BlackBerry® Java® Application .exe delete -g MyApplication Issue a command using the following format: javaloader save .cod file from the BlackBerry device to your computer.cod Retrieve information on • • • • • • sibling . 3. Issue a command using the following format: javaloader info [-d] . Save a BlackBerry® Java® Application .cod > Issue a command using the following format: javaloader save .18: Testing BlackBerry Java Applications Task Steps Issue a command using the following format: javaloader delete [-g] module For example: javaloader.cod files stored in the same CodeModuleGroup from the BlackBerry device to your computer.exe save MyApplication.cod files size of code section size of data section size of initialized data number of class definitions list of signatures applied to a .exe file.exe info -v MyApplication.cod file > Issue a command using the following format: javaloader info [-v] .cod file For example: javaloader.exe save -g MyApplication View BlackBerry Java Application information 1.cod files that a .cod file > requires to run. Issue one of the following tasks: Task Retrieve Name.cod file For example: javaloader.exe save MyApplication.exe info -d MyApplication. Open a command prompt and navigate to the location of the JavaLoader.cod 249 .cod files > stored in the same CodeModuleGroup from the BlackBerry device.cod file For example: javaloader. Steps > Issue a command using the following format: javaloader info .jad file from the BlackBerry device to your computer. For example: javaloader. 2. Connect the BlackBerry® device to the computer. Version. and Date created information for a .cod files listed in the same .cod Retrieve a list of .jad file For example: javaloader.exe info MyApplication.

BlackBerry Java Development Environment Development Guide 250 .

Code must have code signatures for deployment to BlackBerry devices.19 Packaging and distributing BlackBerry Java Applications Preverify BlackBerry Java Applications Determine if your code requires signatures Register to use RIM controlled APIs Request code signatures Distributing BlackBerry Java Applications over the wireless network Distributing BlackBerry Java Applications with the BlackBerry Desktop Software Preverify BlackBerry Java Applications To reduce the amount of processing the BlackBerry® device performs when you load your BlackBerry Java® Application. See the API Reference for more information about all RIM controlled APIs. use the BlackBerry Device Simulator.cod files onto a BlackBerry device.exe [-d] output -classpath directory input. however. directory You may also use the BlackBerry Device Simulator to preverify . you must request code signatures from RIM before you can load these BlackBerry Java Applications on BlackBerry devices. > Locate the item in the API Reference. > Issue a command from the command line in the following format: preverify. which RIM provides. Note: To test and debug your code before receiving code signatures. See the BlackBerry Device Simulator User Guide for more information about the BlackBerry Device Simulator. Controlled APIs Three categories of Research In Motion (RIM) Controlled APIs exist: Runtime APIs. If the item has a lock icon or is noted as ‘signed’ your BlackBerry Java Application requires a signed key or signature. partially verify your classes. Determine if your code requires signatures Research In Motion (RIM) tracks the use of sensitive APIs in the BlackBerry® Java® Development Environment for security and export control reasons. before you can load the BlackBerry Java Application . and BlackBerry Cryptography APIs. You can run BlackBerry Java® Applications that use controlled APIs in the BlackBerry Device Simulator without code signatures.cod files. . BlackBerry® Application APIs.

api.http net.rim.device.device.BlackBerry Java Development Environment Development Guide If you use any of the following BlackBerry® API packages.api.mail net.pdap net. Complete the registration form on the BlackBerry® Developer Zone at https://www. follow the instructions to create a new key pair file. Double-click the .rim.api.rim.system Register to use RIM controlled APIs 1.crypto.event net.rim. type the PIN that RIM provided.blackberry.csi file or the Client PIN and you are an ISV partner.blackberry.rim.api.blackberry.api.io. 5. 252 .rim.rim.phone net.api.options net. 3.notification net.csi file contains a list of signatures and your registration information.api.invoke net.field net.browser net. In the Registration PIN field.blackberry. Save the .com/JDEKeys.blackberry.rim.rim.phonelogs net.com.* net.rim. If the BlackBerry Signing Authority Tool administrator does not provide you with the . If you are not an ISV partner.blackberry.rim. send an email message to jde@rim.api.csi file that Research In Motion (RIM) sends to you in an email message.device.api.api.api.phone.servicebook net.plugin net. The .rim.mail.synchronization net.api.device.blackberry.blackberry.rim. If a dialog box appears that states that a private key cannot be found.blackberry.device.api.api.api. 2. your BlackBerry Java Application requires code signatures before you can load it on a BlackBerry device: • • • • • • • • • • • • • • • • • net.device.rim. contact your ISV Technical Partnership Manager.menuitem net. 4.csi file.rim.browser.device.rim.api.blackberry.rim.browser.device.api.

Click OK. 2. you must apply for a new . The private key password protects your private key. contact your system administrator. type a password of at least eight characters. locate the .csi file from RIM. Expiry Date Sets the expiry date for your . you must apply for a new . 253 . After the expiry date.csi file. Click Register. Make sure that a . contact RIM immediately.cod file that you want to add to the signature list. In Windows® Explorer. The Web Signer application installs when you install the BlackBerry Signing Authority Tool. Click Exit.csi file restriction # of Requests Description Sets the maximum number of requests you can make using a particular .csi file from Research In Motion (RIM). .csi file. The BlackBerry JDE is available for download from the BlackBerry Developer Zone: http://www. In the dialog box. 3. To make new signature requests.blackberry. See “Register to use RIM controlled APIs” on page 252 for more information on obtaining a .csl file with the same name as the . When you reach the maximum number of requests.0 . Although an administrator can permit an infinite number of requests. the number of requests is often set to a finite number for security reasons.cod file.Password Based Administrator Guide for more information about the Web Signer application.19: Packaging and distributing BlackBerry Java Applications 6.com/developers/ 6.csi file. 5. Double-click the . click Request. and it sends the signature list of .csi file to limit your access to code signatures. 8. 4. The signature list contains information on the .cod file exists in the same folder as the .cod files that you want permission to access and are requesting signatures for.csi file becomes invalid. 7. On the BlackBerry Signature Tool menu. In the Private Key Password field. The BlackBerry Integrated Development Environment compiler automatically generates the .csi file. 1.csi file.cod file to add it to the signature list. you must obtain a . you can no longer apply for code signatures with this . The BlackBerry Signature Tool is part of the BlackBerry Java® Development Environment installation. Repeat steps 1 through 3 for each . the .cod file for the BlackBerry® Java® Application for which you are requesting a signature. you must register again with RIM. If this password is stolen. See the BlackBerry Signing Authority Tool Version 1. The BlackBerry Signature Tool uses the private key password to append the signature to the request.csl file. 7. To make new code signature requests. Request code signatures To perform this task. To request changes to these restrictions. Restricted access to code signatures The BlackBerry® Signing Authority Tool administrator might place restrictions on your . If you lose this password.cod files to the Web Signer application for verification. type your private key password.

View the Status column: • • For files the Web Signer has signed. Use the following naming conventions for the keys: client-RRT-*.3. contact your ISV Technical Partnership Manager. 254 . At the command prompt.cod file because the private key password was typed incorrectly.csi file that you want to register. If you lose the registration key or the .csk file.csi • SigKey: The name of each signature key (. 1.jar SigKey. select the .com.csi file only once. Sign a BlackBerry® Java® Application using a proxy server. Type the following command: Java -jar -Dhttp. 4.proxyPort=80 SignatureTool. • Dhttp.1\bin 2. For example: C:\Program Files\Research In Motion\BlackBerry JDE 4. The Web Signer might have rejected the .proxyPort: The proxy server port number if you do not specify 80 as the default port number.csi) file.com -Dhttp.jar 3.3. 1. 3.proxyHost: The name or IP address of the proxy server. Start the BlackBerry® Signature Tool. View signature status 1. For example: C:\Program Files\Research In Motion\BlackBerry JDE 4. browse to the BlackBerry® Signature Tool bin directory. Type the following command: Java -jar -Dhttp.cod file(s) to sign.csi. browse to the BlackBerry Signature Tool bin directory. 3. you cannot request code signatures. At the command prompt. client-RBB-*.csi. Click Open.csk file.1\bin 2. For files the Web Signer did not sign.proxyHost=myproxy. the Status column contains Failed. Request a replacement registration key Your registration key and . • Dhttp.com -Dhttp.csi. send an email message to jde@rim.cod file.csk file are stored together. the Status column contains Signed. Repeat step 2 for each . client-RCR-*.proxyPort=80 SignatureTool. In the File Selection window. If you are not an ISV partner. Steps You can register each . > > If you are an ISV partner and lose the .BlackBerry Java Development Environment Development Guide Request code signatures using a proxy server Task Register signature keys using a proxy server.proxyHost=myproxy. Select a . 2.

Steps 1.cod. and the . the BlackBerry device recognizes the . Once the policy is set on the BlackBerry Enterprise Server.jar file into a .rim.cod file. set the MIME type to application/vnd.jar file. set the MIME type to application/java-archive. • For . Set the required MIME type on the web server.jar file. Note: When you name .sun. my1.jad file and download the BlackBerry Java® Application. for example. 2. since no transcoding by either the BlackBerry device or the BlackBerry MDS Data Optimization Service feature of the BlackBerry Enterprise Server is required. Server-initiated wireless push Distribute applications using wireless pull Deploying a . when a BlackBerry device user uses a BlackBerry device with the BlackBerry Enterprise Solution or the BlackBerry Internet Service to download the .app-descriptor. and BlackBerry device users can download the BlackBerry Java Application over the wireless network by pointing the web browser on their BlackBerry devices to this URL.19: Packaging and distributing BlackBerry Java Applications Distributing BlackBerry Java Applications over the wireless network Method User-initiated wireless pull Description Developers can post their compiled BlackBerry® Java® Applications to a public or private web site.cod.jad files on the web server for the BlackBerry® device users to download.cod files. • For .cod. set the MIME type to text/vnd.cod files. 255 .cod file as sibling .jar file into a . If the BlackBerry device user accepts.cod files is the most efficient way to deploy BlackBerry® Java® Applications for a BlackBerry device using wireless pull. BlackBerry device users use the BlackBerry device browser to browse to the . do not create a . the BlackBerry® Enterprise Server administrator can push BlackBerry Java® Applications out to BlackBerry device users over the wireless network and enforce that the BlackBerry Java Application installs.cod file does not properly load on to the BlackBerry device.cod format.jad file and . If a BlackBerry device user uses a WAP browser to download the . When a BlackBerry device user visits the URL.cod files. the BlackBerry Java Application downloads over the wireless connection and installs immediately. the browser prompts the BlackBerry device user to install the BlackBerry Java Application.jad files. Place the .cod and .cod file. the BlackBerry MDS Data Optimization Service feature of the BlackBerry Enterprise Server or the BlackBerry Internet Service transcodes the . • For . the BlackBerry Java Application is sent to the BlackBerry device users without the need for any actions on the part of the BlackBerry device users. If you deploy the . the BlackBerry device transcodes the .jar files for a BlackBerry Java Application.j2me. See the BlackBerry Enterprise Server for Microsoft Exchange System Administration Guide for more information about pushing BlackBerry Java Applications to a BlackBerry device over the wireless network.cod file using the name-#.jad file with .cod files. Task Deploy . The administrator simply creates a new policy and indicates that the BlackBerry Java Application is required. my-2.jar files. If you use this format. In an enterprise environment.

256 . the BlackBerry® Browser prevents the wireless installation of the BlackBerry Java® Application and lists the missing modules for the BlackBerry device user. When BlackBerry device users use the BlackBerry Browser to download a . net_rim_xml Determine if a .cod file.cod files to > a BlackBerry® device that is not connected to a BlackBerry Enterprise Server.jar file to a .jar files available for download.cod files.cod file dependencies.jar file to a BlackBerry device that connects to a BlackBerry Enterprise Server. Set . the BlackBerry MDS Data Optimization Service feature of the BlackBerry Enterprise Server converts the . Modify the BlackBerry Java® Application .cod files within the original .jar files. Any .cod file. Deploy a . Steps This task requires that a BlackBerry® device user download a .BlackBerry Java Development Environment Development Guide Perform advanced BlackBerry Java Application distribution tasks Task Deploy . If any of the required modules are not present.jar file.cod file with sibling .cod file contains sibling . The following information is required only if BlackBerry® device users access BlackBerry Java® Applications using the BlackBerry Internet Service or a WAP gateway. a BlackBerry Java Application that requires the RIM XML library might use the following in the BlackBerry Java Application descriptor: RIM-COD-Module-Dependencies: net_rim_cldc. > In the BlackBerry Java Application descriptor (. > Extract the contents of the . but that the BlackBerry Java Application does not provide.jad file so that the file lists each sibling file individually. > Make . use the RIM-COD-Module-Dependencies attribute to specify modules that the BlackBerry Java Application requires.jad) file. For example.cod file are the sibling files.

cod file and extract the sibling .cod file sizes listed in a .cod files. Add additional attributes to a . 257 . Place the RIM-COD-Size-<#> parameter immediately below the RIM-COD=URL-<#> parameter. Create .cod files. In the .jad file change after you use the BlackBerry® Signing Authority Tool to sign .cod.cod files: name of original . Place each sibling .cod files. • RIM-COD-URL-<#>: Create a RIM-COD-URL-<#> parameter for each sibling .jad file You can use the Updatejad tool to process .cod file onto a web server.jad files that reference multiple .cod file on a web server.0 MIDlet-Version: 1.cod’ file extension to each sibling file name. 3. Use the following naming convention for sibling .cod and myApp-2.cod file sizes listed in the .cod file.cod RIM-COD-Size-1: 50000 RIM-COD-URL-2: myApp-2. on the web server. # is a number that starts at 1 and increases by 1 for each sibling file. • RIM-COD-Size-<#>: Create a RIM-COD-Size-<#> parameter for each sibling . 1. The developer creates a RIM-COD-Size-<#> parameter for each sibling file.jad file. extract the sibling .cod files into a different directory than the directory where the original file exists.cod file.cod file . Steps To ensure a BlackBerry® device user does not override the original .cod files.cod files separately. For each sibling file. Give each sibling . after the original .0 RIM-COD-Module-Name: MyApp MIDlet-Name: My Application RIM-COD-URL: myApp. the existing attribute is not overwritten.cod file myAPP.19: Packaging and distributing BlackBerry Java Applications Task Extract sibling . If you try to add an attribute that already exists in the . RIM-COD-Module-Dependencies: net_rim_cldc MicroEdition-Configuration: CLDC-1. list the sibling .. and RIM-COD-Size-<#> parameters. The developer appends the ‘. 2. Modify information in a .0.cod RIM-COD-Size: 55000 RIM-COD-URL-1: myApp-1. Place each sibling . Manifest-Version: 1. and place the size of the sibling file to the right of this parameter. The developer names the sibling files myApp-1.jad files and perform the following actions: • • • Correct the . create RIM-COD-URL<#>.cod files the same name as the original . The following example shows two sibling files.jad file.cod file.cod file.cod files. # is the same number that is appended to the name of the sibling file. Unzip the original .0 Distribute individual sibling . The .0 MIDlet-1: .jad file. followed by -<#>.jad file.cod RIM-COD-Size-2: 25000 MicroEdition-Profile: MIDP-1.sequential number. and place the name of the sibling file to the right of this parameter.

From a command-prompt. 4. 3.jad.jad file. .jad file (in this example.Password Based Administrator Guide for more information. 2. updatejad. navigate to the location of the Updatejad tool.0 . type updatejad.cod file. Updatejad commands have the following format: updatejad.cod. file. Use the BlackBerry Signing Authority Tool to sign the new .jad files. For example.jad file.jad file. 5.cod file. Specifies the .jad.cod and test.BlackBerry Java Development Environment Development Guide Use Updatejad only on . If an error occurs during .jad) and to add the .jad files are provided. they are added to the list of RIMCOD-URL-n tags in the order they are encountered. Type a command to correct the .jad file When multiple additional . and signed using the BlackBerry Signing Authority Tool. Note: Once you load a BlackBerry® Java® Application onto a BlackBerry device.jad [additional. 2. Use the BlackBerry IDE to create two other BlackBerry Java Application files that use the .jad file processing.exe test. lib.exe test.cod files to a web server may require the extraction of siblings on the web server.jad additional. Use the BlackBerry® IDE to create two BlackBerry Java® Application files. For example.jad. When additional . The one exception is the RIM-COD attributes that include all values.cod and lib.jad file to update. test.jad Adding additional attributes to a .jad lib. type. See the BlackBerry Integrated Development Environment Help or the BlackBerry Signing Authority Tool Version 1. 4.jad files created using the BlackBerry IDE or the RAPC command-line tool.cod file sizes listed in the new . Suppresses the backup of the original . Type a command to correct the . a non-zero exit code is produced.jad files that reference multiple 1. navigate to the location of the Updatejad tool.cod file sizes listed in test. the BlackBerry Java Application cannot access any .cod and test.jad file to the new one. 3.cod file names from the first . Correct the . Specifies other attributes to add to the input. Use the BlackBerry Signing Authority Tool to sign test. 6.jad] Options -q -n input.jad.jad file to contain an attribute determines the value associated with that attribute.exe -q -n input. for example.jad file attributes added using the Updatejad tool. Steps Use the BlackBerry® IDE to create two BlackBerry Java® Application files.jad 1. test.jad Create . for example.jad Task Description Suppresses the creation of success output messages for . 258 .cod file sizes listed in a . The Updatejad tool does not extract the contents of sibling . Deployment of . From a command-prompt. the first .cod files. Use the BlackBerry Signing Authority Tool to sign the .cod files.jad file processing operations.cod files are specified using one or more additional . test. for example.

alx file for each BlackBerry® Java® Application. make sure the series attribute in the fileset opening tag refers to the BlackBerry device you want the BlackBerry Java Application to load on. The BlackBerry® JDE includes a command line tool called Javaloader. In the BlackBerry Integrated Development Environment. BlackBerry® Application Web Loader Javaloader Command Line Tool Create an application loader file 1. <fileset series="8700" Java="1. With the BlackBerry Application Web Loader.alx file with the .3\simulator.alx file for the BlackBerry® Java® Application. select a project. 3.0"> For more information on the series attribute. see the Platform.alx File. 3. 259 . they are asked to connect their BlackBerry device to the USB port. The executable file is in the BIN directory under the JDE installation. Javaloader can be useful when you are installing and removing your BlackBerry Java Application frequently during testing and development.exe. 2. you can post your compiled BlackBerry Java® Application on a central web site and BlackBerry device users can install the BlackBerry Java Application by using Microsoft® Internet Explorer® on their computer to visit the URL. See the BlackBerry Application Web Loader Developer Guide for more information on the BlackBerry Application Web Loader. Create an .alx file located in the simulator directory of your BlackBerry Java® Development Environment installation directory: Program Files\Research In Motion\BlackBerry JDE 4. Javaloader is not a tool that BlackBerry device users would use.19: Packaging and distributing BlackBerry Java Applications Distributing BlackBerry Java Applications with the BlackBerry Desktop Software Deployment method Application Loader tool of the BlackBerry® Desktop Manager Description The Application Loader tool of the BlackBerry Desktop Manager lets you install third party BlackBerry Java Applications as well as updated system software for the BlackBerry device. When BlackBerry device users visit the web page. 2. click Generate . Application Web Loader provides a simple approach for installing BlackBerry Java Applications from your desktop and does not require the BlackBerry device user to run BlackBerry Desktop Manager.alx files. and then distribute the . In the . See the Application Loader Online Help for more information about . Open a text editor. Locate the . It lets BlackBerry device users download BlackBerry Java® Applications on their computers and install them on their BlackBerry devices. However. Javaloader can be used to quickly install and remove compiled BlackBerry Java® Application files on the BlackBerry device directly over the USB port and does not require any descriptor files or web pages. Load a BlackBerry Java Application on a specific BlackBerry device 1. The BlackBerry Java Application is then installed using an ActiveX® Control. On the Project menu.cod files to BlackBerry® device users.alx file.

cod file for your BlackBerry Java Application.1838</version> <vendor>RIM</vendor> <copyright>Copyright (c) 2001-2005</copyright> <fileset series="8700" Java="1.0"> <files> My_application.0</version> <vendor>Research In Motion</vendor> <copyright>Copyright 1998-2003 Research In Motion</copyright> <language langid="0x000c"> <name>Application D'Échantillon</name> <description>Obtenir une page du réseau </description> </language> <fileset Java="1. in the .alx file uses an XML format: Sample . 2. Make sure the files tag contains a reference to the . and other tags to reflect the purpose of the .0"> 260 . 3. open the . 1. create a nested structure. you do not need to change the .device.. </description> <version>1.alx file you want to change.cod </files> </fileset> </application> </loader> Specify optional components In most cases.0"> <application id="com. <application id="Push only to 8700"> .alx file.02.cod </files> 5. Update the application.rim.alx file.BlackBerry Java Development Environment Development Guide 4.0"> <application id="Push only to 8700"> <name>Alien</name> <description>This will push the COD only to 8700s</description> <version>2006. <files> My_application.alx files that the BlackBerry® Integrated Development Environment generates..httpdemo"> <name>Sample Network Application</name> <description>Retrieves a sample page over HTTP connection. description. In the text editor. To provide optional components for a BlackBerry Java® Application. <description>This will push the COD only to 8700s</description> Example: Load a BlackBerry® Java® Application on a specific BlackBerry device <loader version="1.samples.alx file <loader version="1. The .14. Open a text editor.

Example: Sample .cod net_rim_resource__en.contacts"> <name>Sample Contacts Application</name> <description>Provides the ability to store a list of contacts.contacts.cod </files> </fileset> </application> </loader> 4.0"> <directory>samples/contacts</directory> <files> net_rim_contacts. use the <requires> tag.rim.mail"> <name>Sample Module for Contacts E-Mail Integration</name> <description>Provides the ability to access the messaging application</description> <version>1.19: Packaging and distributing BlackBerry Java Applications <directory>samples/httpdemo</directory> <files> net_rim_httpdemo. To define an explicit dependency on another BlackBerry Java Application or library.0"> <directory>samples/contacts</directory> <files> net_rim_contacts_mail.rim.sample. > Specify a range using the following rules: 261 .cod net_rim_resource.0"> <application id="net.cod </files> </fileset> <application id="net. </description> <version>1.cod net_rim_resource__fr.cod net_rim_resource__en.0</version> <vendor>Research In Motion</vendor> <copyright>Copyright 1998-2001 Research In Motion</copyright> <fileset Java="1.alx file for a BlackBerry® Java® Application with a nested module <loader version="1.cod net_rim_resource.cod net_rim_resource__fr.0</version> <vendor>Research In Motion</vendor> <copyright>Copyright 1998-2001 Research In Motion</copyright> <fileset Java="1.sample.cod </files> </fileset> </application> </application> </loader> Specify supported BlackBerry Device Software BlackBerry® Java® Applications that use APIs only available on particular versions of the BlackBerry Device Software should specify supported BlackBerry device versions using the _blackberryVersion attribute.

)"> . Missing upper ranges imply infinity.. The following example prevents modules from loading on versions of the BlackBerry Device Software earlier than version 4. Missing lower ranges imply 0. <application id="application_id" _blackberryVersion="[4.0 and later </fileset> </application> See “Appendix: .0.. modules for BlackBerry device software versions earlier than 4.0..0)"> .)"> . Round brackets () indicate exclusive (open) range matching.. 262 . [4.BlackBerry Java Development Environment Development Guide • • • • Square brackets [] indicate inclusive (closed) range matching. <application id="application_id>"> .alx file elements. </application> The following example provides alternative modules for different versions of the BlackBerry Device Software.0.4. <fileset _blackBerryVersion="(. modules for BlackBerry device software versions 4...0. For example.0 </fileset> <fileset _blackBerryVersion="[4.alx files” on page 267 for more information about ..0 and infinity..) indicates any version between 4.

An input file that contains BlackBerry Java Application information.cod file as a MIDlet and generate a preverified . Use the command line argument with the import= option to provide this .. RAPC stores this information in intermediate and temporary files in the BlackBerry device user’s temporary folder.jar file.]]filename =file. List dependent . Specify the . RAPC uses the first main(String[]) method it finds as the entry point.]]filename =[path\[.java and .. -class -codename -library -import -midlet -deprecation -nowarn -quiet -warning -verbose =[path\[.cod file uses the same name as the .jar file.. RAPC compiles . Specify the name and location of the output .. The java compiler ignores the value specified with the -deprecation option.cod file as a library. typically the output . The rapc. a command line compiler. For example. RAPC accepts the following command line options in the following order: Option java | class | jar Option format Description The input files: • • • jad ..jar files into . Display only errors. .cod file..exe file exists in the bin subdirectory of your BlackBerry JDE installation. Specify the name and location of the output . RAPC does not delete the temporary files. The java compiler does not issue warnings for the value specified with the -nowarn option.A Appendix: The command line compiler Using the command line compiler Using the command line compiler The BlackBerry® Java® Development Environment includes RAPC. Display information about RAPC activity.class file that javac has compiled.jar files. .jar: An archive of files that the compilation set must include.class: A Java .jar file to RAPC.java: A Java source program file that javac must compile..] . for example list RIM APIs and other dependent libraries. Note: net_rim_api.cod files that you can run in the BlackBerry Device Simulator or load onto a BlackBerry device. without this option. classname The name of the class containing the BlackBerry Java Application main entry point. it contains a list of attributes as specified by the MIDP specification. Generate warning messages.jar[.jar is required as an input file when you invoke RAPC.

jad Samples\SamplaApp. the following command line instruction compiles the SampleApp.. RAPC uses the -library option.java file name if you are compiling from java files.jar Option format =0xNNNNNNNN[. Add the filename to the .java [additional .jar codename=SampleApp\SampleAppDriver -midlet SampleApp.] =filename Description Treat certain warnings as errors.jar 264 .java files as required] JAR_filename. the '-' before the option name is optional.BlackBerry Java Development Environment Development Guide Option -wx -warnkey -workspace filename_1. Specify the .csl file.. For example.jar file into a .cod file of the same name: rapc import=net_rim_api. For option values that start with an '=' symbol (for example: -workspace). Note: If you specify both the -codename and -library options..jar file name if compiling from a . Generate a warning if you need to add a key to the .debug file for BlackBerry Integrated Development Environment browsing.jar file. Specify the .

Content is not delivered before this date. Specify a unique message ID. Content that has not been sent by this date and time is not delivered. Represent the date and time in UTC format. . 123@blackberry. Represent the date and time in UTC format: YYYY-MM-DDThh:mm:ssZ where • • • • • • • YYYY is a 4-digit year MM is a 2-digit month DD is a 2-digit day hh is a 2-digit hour based on 24-hour timekeeping system mm is a 2-digit minute ss is a 2-digit second Z indicates that the time is in UTC deliver-after-timestamp XML control entity attributes X-Wap-Application-Id push-id Example “/” 123@wapforum. use this control entity attribute to cancel or check the status of a message. Use a URL in combination with a value. Specify the date and time by which to deliver the content to the BlackBerry® device. transport. The destination is the destination internet messaging address or PIN.org ppg-notify-requested-to deliver-before-timestamp http://wapforum:8080/ ReceivePAPNotification 2004-01-20T22:35:00z Specify the date and time after which content is delivered to the BlackBerry® device.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 Specify the equivalent of the REQUEST URI HTTP parameter for RIM push. Specify the URL that the result notification is sent to.com. 2004-01-20T21:35:00z address-value Specify the address of the BlackBerry device that the push content is sent to. unconfirmed Specify the delivery reliability mode of the content. or application-level. WAPPUSH=destination%3AportI/ TYPE=USER@blackberry.com confirmed. Additionally. For example.delivery-method level.

see the Push Access Protocol (WAP247-PAP-20010429-a) specification at http://www.BlackBerry Java Development Environment Development Guide For more information about writing server-side push applications using PAP. See the PAP 2.0 DTD for information about the WAP Push DTDs. 266 .com.wmlclub.

com. The application element can also contain additional nested application elements. To provide uniqueness. For example: <application id="com.alx files Elements in BlackBerry application . to load onto the BlackBerry device.alx location>\MyCodFiles\MyCodFiles d.alx location>\MyCodFiles b.C Appendix: .cod </files> </fileset> </application> files — The files element provides a list of one or more BlackBerry Java Application .cod //resolves to <.cod </files> </fileset> <directory>MyCodFiles</directory> <fileset Java="1. use an ID that includes your company domain in reverse order. The directory element specifies the directory relative to the location of the .alx files Element application Attributes id Description The application element contains the elements for a single BlackBerry® Java® Application.samples.cod //resolves to <. The directory element provides the location of a set of files.0"> <files> a.docs.0"> <files> c. its prerequisite modules also load onto the BlackBerry device. when a BlackBerry Java Application loads onto the BlackBerry device.rim. which appears in the Application Loader. The description element provides a brief description of the BlackBerry Java Application. the files must exist in the same location as the . in a single directory.alx file.alx files Elements in BlackBerry application . . copyright description directory — — — The copyright element provides copyright information. For example. The directory element is optional. Directory elements are cumulative within a BlackBerry Java Application.my.abc.cod files.app"> <directory>MyCodFiles</directory> <fileset Java="1. The id attribute specifies a unique identifier for the BlackBerry Java Application.helloworld. If you do not specify a directory. which appears in the Application Loader. Nesting lets you require that.alx file.

description. so that when a particular BlackBerry Java Application loads onto the BlackBerry device. include one or more fileset elements in the .alx file. Only corporate system administrators should use the hidden tag. some Win32 langid codes are: 0x0009 (English). The langid attribute specifies the Win32 langid code for the language to which this information applies. which appears in the Application Loader. The name element provides a descriptive name for the BlackBerry Java Application. The value is a Boolean. To specify the name. vendor. a library module does not appear in the Application Loader.cod files. DataTAC. You cannot nest modules.BlackBerry Java Development Environment Development Guide Element fileset Attributes Java radio langid Colour Description The fileset element includes an optional directory element and one or more files elements. Note: The BlackBerry Desktop Software Version 3. for example: 0x0009 (English). If you do not nest a tag. The langid attribute is optional.0. The version attribute specifies the version of the Application Loader. To hide a package. add the following line: <hidden>true</hidden>. Note: The BlackBerry Desktop Software Version 3. a required library also loads onto the BlackBerry device. loader version The loader element contains one or more application element. to load onto the BlackBerry device. The value is a Win32 langid code. language langid The language tag lets you override the text that appears in the Application Loader when the Application Loader runs in the language that the langid attribute specifies. or set the requires tag to load this package if another BlackBerry Java Application exists. in a single directory. the text appears in the default language.6 or later supports this element. The radio attribute is optional. Possible values include Mobitex. It contains the elements for a single library module. Use this element in conjunction with the required element to load the BlackBerry Java Application by default. and IDEN. The langid attribute lets you load different BlackBerry Java Applications or modules depending on the language support that BlackBerry device users add to the BlackBerry device.cod files are compatible. 0x000a (Spanish). nest these tags in the language tag. To support multiple languages. For example. and 0x000c (French). The Java attribute specifies the minimum version of the BlackBerry JVM with which the . CDMA. hidden — The hidden element hides a package so that it does not appear to BlackBerry device users in the Application Loader. 0x000a (Spanish). library id You can use the library element instead of the application element. and 0x000c (French). By default. The Java attribute is required. To load files from more than one directory. GPRS. version.6 or later supports this element. The colour attribute lets you load different BlackBerry Java Applications or modules for color or monochrome displays. and copyright tags for each language. 0x0007 (German). Typically. true means color display and false means monochrome. The current BlackBerry JVM is Version 1. name — 268 . It specifies a set of . specify multiple language tags. use the library element as the target of a <requires> element. This tag is not intended for use by thirdparty software vendors. 0x0007 (German). The radio attribute lets you load different BlackBerry Java Applications or modules onto the BlackBerry device depending on the network type of the BlackBerry device.

5 or later supports this element. all packages that the <requires> tag specifies also load onto the BlackBerry device. This version number is for information purposes only. Note: The BlackBerry Desktop Software Version 3.6 or later supports this element. which appears in the Application Loader. The Application Loader selects the BlackBerry Java Application for installation. Note: The BlackBerry Desktop Software Version 3.Appendix: . which appears in the Application Loader. This element can appear more than once. The vendor element provides the name of the company that created the BlackBerry Java Application. and the BlackBerry device user cannot change this selection. requires id The requires element is an optional element that specifies the id of a package on which this BlackBerry Java Application depends. vendor version — — 269 . if the BlackBerry Java Application depends on more than one BlackBerry Java Application.alx files Element required Attributes — Description The required element lets you force an application to load. Only corporate system administrators should use the required tag. This tag should not be used by thirdparty software vendors. The version element provides the version number of the BlackBerry Java Application. Add the following line: <required>true</required>. When a BlackBerry Java Application loads onto the BlackBerry device.

BlackBerry Java Development Environment Development Guide 270 .

D Appendix: BlackBerry Java Application .jad file Properties of BlackBerry Java Application . on other wireless devices.jad file that contains both the RIM-COD-URL and RIM-COD-Size attributes and the MIDlet-Jar-URL and MIDlet-Jar-Size attributes. download the .cod file dependencies The application descriptor (. Optional RIM attribute RIM-Library-Flags RIM-MIDlet-Flags RIM-MIDlet-NameResourceBundle RIM-MIDlet-Position The BlackBerry® Integrated Development Environment lets you create a dual-purpose .jad file to support the downloading of MIDlets onto BlackBerry devices and other wireless devices.jad files Accessing application attribute properties from a . download the .jad) file contains a RIM-COD-Module-Dependencies attribute that specifies the modules that the BlackBerry® Java® Application requires. Set . net_rim_xml .cod file contains SHA1 hash of the .cod file requires name of the module that the . The RIM-COD-Module-Dependencies attribute takes a comma-separated module name list as a parameter. For example. a BlackBerry Java Application that requires the RIM XML library might use the following entry in the application descriptor: RIM-COD-Module-Dependencies: net_rim_cldc.cod file list of modules that the . The RIM-COD-ModuleDependencies attribute lets a BlackBerry device user avoid downloading a BlackBerry Java Application that will not run.jar files.jad files Required RIM attribute RIM-COD-Creation-Time RIM-COD-Module-Dependencies RIM-COD-Module-Name RIM-COD-SHA1 RIM-COD-Size RIM-COD-URL Description creation time of the .cod files. On BlackBerry devices. To do this.cod file can be loaded Description reserved for use by Research In Motion (RIM) reserved for use by RIM name of the resource bundle on which the BlackBerry® Java® Application depends suggested position of the BlackBerry Java Application icon on the Home screen Note: This position might not be the actual position of the BlackBerry Java Application icon on the Home screen.jad files Properties of BlackBerry Java Application .cod file URL from which the . create a .cod file size (in bytes) of the . but are not provided with it.

the application can use the CodeModuleGroup to access the name-value pair information in the application’s .jad file of a BlackBerry device application to download the application onto a BlackBerry device.nextElement(). and store a reference to the CodeModuleGroup object.out.getProperty(name) ).load(group_name). System.BlackBerry Java Development Environment Development Guide Accessing application attribute properties from a . e. ) { String name = (String)e.jad file. Let a BlackBerry device application retrieve name-value pair information from a . Retrieve properties from the CodeModuleGroup by invoking the CodeModuleGroup.out.println( "Value: " + cmg.getProperty(name) method. CodeModuleGroup cmg = CodeModuleGroupManager. Load a code module group into a CodeModuleGroup object using the name of the required module group as a parameter. group_name refers to the name of the code module group.jad file 1. 272 . System. 2.load(group_name).println( "Name: " + name ). for( Enumeration e = cmg. In this example.jad file After a BlackBerry device user uses the . CodeModuleGroup cmg = CodeModuleGroupManager.getPropertyNames().hasMoreElements(). } See the API reference for the BlackBerry Java Development Environment for more information about the CodeModuleGroup class. The following example iterates through all the properties of a code module group.

Set project variables Extend the Sun JRE 1. install and configure the Eclipse™ development environment. 2. 7. 4. On the Eclipse taskbar.E Appendix: The Eclipse development environment Use the Eclipse development environment Use the Eclipse development environment The Java® Debug Wire Protocol (JDWP) program provides an interface to the BlackBerry® Device Simulator. Perform the following steps: 1. Start the JDWP > Click Start > Programs > Research In Motion > BlackBerry JDE 4. Select Installed JREs. Note: You must start the BlackBerry Device Simulator from the BlackBerry® IDE before you can start the JDWP. Expand the Java item. you can use third-party integrated development environments. 6. When you start the JDWP. In the Add JRE window. specify Standard VM. Extend the Sun JRE 2. Click Add. Set up your workspace and project. click Window > Preferences. . click Run > Debug. Add the API documentation 3.3 > JDWP. Start the Eclipse workbench 3. Set builder settings 4. in the JRE type field. Connect to the Eclipse development environment Note: Before completing the tasks in this section. 5. To start a BlackBerry Device Simulator in the Eclipse development environment.

For example: C:\Program Files\Research In Motion\BlackBerry JDE 4.jar file. For example: C:\Program Files\Research In Motion\BlackBerry JDE 4. type a name for the JRE. 6. 10. For example: C:\Program Files\Research In Motion\BlackBerry JDE 4. 8. Click Edit. 12. Navigate to the docs\api folder of your BlackBerry® JDE installation. 3. 2. Select Javadoc location. Browse to the lib folder of your installation of the BlackBerry® JDE. The default is RIM JVM.5. click Project > Properties. For example: C:\Java\jdk1. On the Eclipse taskbar. In the Location field. select Program. 11. click OK. Select the rapc. 10. Select net_rim_api. 274 . type a name for the builder. click Browse File System. Click New. Click OK. In the Choose configuration type window. Add a RIM . 4.jar. Click Add External JARs. Click Browse. In the Properties for New_Builder window. 2. Click OK. Click Open. type the location of the Sun JRE. Set builder settings 1. 7. Select Builders.exe file.jar file to your project.BlackBerry Java Development Environment Development Guide 8. 8. Click OK. 4. 9. In the Add JRE window. 9. Add the API documentation 1. Make sure the Use default system libraries field is cleared. 14. expand the net_rim_api. select the newly created JRE.3\docs\api 7.3\lib 13. 5. 5. In the JRE name field.3\bin 9. 3. Navigate to the bin folder of your BlackBerry® JDE installation. In the JRE home directory field.0_02\jre. 6. In the Add JRE window. in the Name field. In the Installed JREs window.

In the Run the builder section. If an input path error occurs. 1. For example.java import=”C:\Program Files\Research In Motion\BlackBerry JDE 4. or jad files] import=”C\Program Files\Research In Motion\BlackBerry JDE 4. In the Properties for New_Builder window. In the Launch timeout field. In the Working Directory field. click the Build Options tab. verify that the following options are selected: • • • After a “Clean” During manual builds During auto builds 8. replace C:\Development\TestProject\*. in the Debugger timeout field.3\lib\net_rim_api. type a value. Note: The values you set in the Debugger timeout and Launch timeout fields depend on the processing speed of your computer. click Variables.jar” codename=C:\Development\ProjectName Example: -quiet C:\Development\TestProject\*. If connection problems continue after setting these fields. In the Communication section.Appendix: The Eclipse development environment 10. 4. 7. In the Properties for window.java with C:\Development\A. 2. 5. use a space separated list of files. class. click Windows > Preferences. 275 .jar” codename=C:\Development\TestProject. In the Arguments field. Set the connection time To prevent connection timeouts when debugging in the Eclipse development environment. type: -quiet [desired space separated java. set the timeout values for the debug program.3\lib\net_rim_api. 4. 9. increase the timeout values. In the Select Variable window. type a value. Select Debug. On the Eclipse taskbar. Note: RAPC does not support wildcard characters. 3. click OK. 2. Click OK. 3. jar. 5. Expand the Java item. select Build project. 6. Click OK. Click OK.java C:\Development\B. Set project variables 1.java. Click Open.

3. Under the Remote Java Application item. 8.BlackBerry Java Development Environment Development Guide Debug an application using the Eclipse development environment 1. 2. click Run > Debug. 5. increase the debugger timeout values. See “Set the connection time” on page 275 for more information. Verify that your application is listed. 6. click Run > Debug. Click Debug. Click Close. From the Eclipse taskbar. See “Start the JDWP” on page 273 for more information. Click New. 9. 4. 7. Connection timed out”. Click the Source tab. 276 . On the Eclipse taskbar. select an application. Open the JDWP application. Select Remote Java Application. Note: If the following error message appears: “Failed to connect to remote VM. 10.

Acronym list 3 3GPP 3rd Generation Partnership Project A AES Advanced Encryption Standard API application programming interface APN Access Point Name ATR Answer To Reset B bpm beats per minute C H CAC common access card CDMA Code Division Multiple Access D DTD document type definition DTMF Dual Tone Multiple Frequency I ID identification HTTPS Hypertext Transfer Protocol over Secure Sockets Layer HTTP Hypertext Transfer Protocol GSM Global System for Mobile Communications G GAN generic access network GERAN GSM-EDGE Radio Access Network GPRS General Packet Radio Service GPS Global Positioning System E EDGE Enhanced Data Rates for Global Evolution EVDO Evolution Data Optimized .

BlackBerry Java Development Environment Development Guide J JSR Java Specification Request L LAN local area network LBS location based services LMM Low Memory Manager M MIDP Mobile Information Device Profile P S/MIME Secure Multipurpose Internet Mail Extensions T TCP Transmission Control Protocol TCP/IP Transmission Control Protocol/Internet Protocol Triple DES Triple Data Encryption Standard U UDP User Datagram Protocol UI user interface UMA PAP Push Access Protocol Unlicensed Mobile Access UMTS PDE Position Determination Entity URI Universal Mobile Telecommunications System Uniform Resource Identifier PME Plazmic Media Engine POST power-on self test R RAM random access memory W S SSID service set identifier 278 USB Universal Serial Bus UTC Coordinate Universal Time UTRAN UMTS Terrestrial Radio Access Network WAP Wireless Application Protocol .

Acronym list WLAN wireless local area network X XML Extensible Markup Language 279 .

BlackBerry Java Development Environment Development Guide 280 .

.

.©2007 Research In Motion Limited Published in Canada.

Sign up to vote on this title
UsefulNot useful