Motorola E680 - Smartphone - GSM Developer's Manual

Page 1
Technical Manual
IBU
Motorola E680 Handset J2ME™ Developer Guide
Version 1.5
Page 2
Table of Contents
TABLE OF CONTENTS ............................................................................................................................... 2
1 INTRODUCTION ...................................................................................................................................... 6
PURPOSE...................................................................................................................................................... 6
AUDIENCE .................................................................................................................................................... 6
DISCLAIMER ................................................................................................................................................ 6
REFERENCES ................................................................................................................................................ 7
REVISION HISTORY .................................................................................................................................... 8
DEFINITIONS, ABBREVIATIONS, ACRONYMS............................................................................................. 8
DOCUMENT OVERVIEW .................................................................................................................................. 9
2 J2ME INTRODUCTION......................................................................................................................... 11
THE JAVA 2 PLATFORM, MICRO EDITION (J2ME).............................................................................. 11
THE MOTOROLA J2ME PLATFORM............................................................................................................. 12
RESOURCES AND API’S AVAILABLE........................................................................................................ 12
3 DEVELOPING AND PACKAGING J2ME APPLICATIONS............................................................. 14
GUIDE TO DEVELOPMENT IN J2ME.......................................................................................................... 14
4 DOWNLOADING APPLICATIONS........................................................................................................ 16
METHOD OF DOWNLOADING......................................................................................................................... 16
ERROR LOGS.............................................................................................................................................. 18
5 APPLICATION MANAGEMENT............................................................................................................. 20
DOWNLOADING A JAR FILE WITHOUT A JAD.......................................................................................... 20
MIDLET UPGRADE ..................................................................................................................................... 20
INSTALLATION AND DELETION STATUS REPORTS.................................................................................... 21
6 MULTIPLE APPLICATIONS............................................................................................................... 22
MULTIPLE APPLICATIONS......................................................................................................................... 22
7 JAD ATTRIBUTES................................................................................................................................23
JAD / MANIFEST ATTRIBUTE IMPLEMENTATIONS .................................................................................. 23
8 GAMING API/MULTIPLE KEY PRESS............................................................................................ 26
GAMING API............................................................................................................................................. 26
MULTIPLE KEY PRESS SUPPORT .............................................................................................................. 26
2
Page 3
Table of Contents
9 JSR 184 ................................................................................................................................................ 29
OVERVIEW .................................................................................................................................................. 29
MOBILE 3D API...................................................................................................................................... 29
Mobile 3D API File Format Support ............................................................................... 30
Mobile 3D Graphics – M3G API ........................................................................................... 30
10 VIBE AND BACKLIGHT API .......................................................................................................... 38
VIBE AND BACKLIGHT API...................................................................................................................... 38
11 JAVA.LANG IMPLEMENTATION...................................................................................................... 40
JAVA.LANG SUPPORT................................................................................................................................. 40
12 NETWORK APIS.................................................................................................................................. 41
NETWORK CONNECTIONS............................................................................................................................. 41
USER PERMISSION .................................................................................................................................... 43
INDICATING A CONNECTION TO THE USER.............................................................................................. 43
HTTPS CONNECTION ................................................................................................................................44
13 JSR 135 MOBILE MEDIA API...................................................................................................... 46
JSR 135 MOBILE MEDIA API............................................................................................................... 46
TONECONTROL............................................................................................................................................ 48
VIDEO CONTROL ........................................................................................................................................ 48
Snapshot Image............................................................................................................................. 48
GUICONTROL............................................................................................................................................. 48
VOLUMECONTROL ........................................................................................................................................ 49
STOPTIMECONTROL.................................................................................................................................... 49
MANAGER CLASS ........................................................................................................................................ 49
AUDIO MEDIA............................................................................................................................................ 50
14 JSR 120 – WIRELESS MESSAGING API .................................................................................. 52
WIRELESS MESSAGING API (WMA)........................................................................................................ 52
SMS CLIENT MODE AND SERVER MODE CONNECTION.............................................................................. 52
SMS PORT NUMBERS................................................................................................................................. 53
SMS MESSAGE TYPES............................................................................................................................... 54
SMS MESSAGE STRUCTURE ....................................................................................................................... 54
SMS NOTIFICATION ................................................................................................................................. 54
15 PHONEBOOK ACCESS API............................................................................................................... 60
PHONEBOOK ACCESS API ......................................................................................................................... 60
PHONEBOOK ACCESS API PERMISSIONS.................................................................................................. 60
16 FILE SYSTEM ACCESS API .......................................................................................................... 65
FILE CONNECTION METHODS..................................................................................................................... 65
ESTABLISHING A CONNECTION ................................................................................................................. 65
CONNECTION BEHAVIOR............................................................................................................................. 66
SECURITY .................................................................................................................................................. 66
17 TELEPHONY API................................................................................................................................72
DIALER CLASS.......................................................................................................................................... 72
CLASS DIALEREVENT................................................................................................................................72
CLASS DIALER.......................................................................................................................................... 74
getDefaultDialer........................................................................................................................75
3
Page 4
setDialerListener ..................................................................................................................... 75
startCall ........................................................................................................................................ 75
startCall ........................................................................................................................................ 76
sendExtNo ........................................................................................................................................ 76
endCall............................................................................................................................................. 76
INTERFACE DIALERLISTENER................................................................................................................... 77
SAMPLE DIALERLISTENER IMPLEMENTATION ........................................................................................... 77
notifyDialerEvent ..................................................................................................................... 79
CLASS HIERARCHY .................................................................................................................................... 79
INTERFACE HIERARCHY............................................................................................................................. 79
18 DRM PROTECTION IN JAVA .......................................................................................................... 80
OVERVIEW .................................................................................................................................................. 80
RIGHTS ENFORCEMENT - MIDLETS ACCESSING DRM PROTECTED CONTENT ........................................... 80
ACQUIRING LICENSE ................................................................................................................................80
19 CLDC 1.1............................................................................................................................................ 81
CLDC 1.1 COMPLIANCE.......................................................................................................................... 81
20 JTWI..................................................................................................................................................... 86
OVERVIEW .................................................................................................................................................. 86
CLDC RELATED CONTENT FOR JTWI....................................................................................................... 87
MIDP 2.0 SPECIFIC INFORMATION FOR JTWI .................................................................................... 88
WIRELESS MESSAGING API 1.1 (JSR 120) SPECIFIC CONTENT FOR JTWI .................................. 89
MOBILE MEDIA API 1.1 (JSR 135) SPECIFIC CONTENT FOR JTWI.............................................. 90
MIDP 2.0 SECURITY SPECIFIC CONTENT FOR JTWI .......................................................................... 90
21 MIDP 2.0 SECURITY MODEL........................................................................................................ 91
UNTRUSTED MIDLET SUITES.................................................................................................................... 92
UNTRUSTED DOMAIN .................................................................................................................................. 92
TRUSTED MIDLET SUITES ....................................................................................................................... 93
PERMISSION TYPES CONCERNING THE HANDSET ...................................................................................... 93
USER PERMISSION INTERACTION MODE................................................................................................... 93
IMPLEMENTATION BASED ON RECOMMENDED SECURITY POLICY............................................................... 94
TRUSTED 3
RD
PARTY DOMAIN.................................................................................................................... 94
TRUSTED MIDLET SUITES USING X.509 PKI..................................................................................... 95
SIGNING A MIDLET SUITE...................................................................................................................... 96
SIGNER OF MIDLET SUITES.................................................................................................................... 96
MIDLET ATTRIBUTES USED IN SIGNING MIDLET SUITES.................................................................... 96
CREATING THE SIGNING CERTIFICATE ................................................................................................... 96
INSERTING CERTIFICATES INTO JAD .................................................................................................... 97
CREATING THE RSA SHA-1 SIGNATURE OF THE JAR .......................................................................... 97
AUTHENTICATING A MIDLET SUITE ........................................................................................................ 97
VERIFYING THE SIGNER CERTIFICATE ................................................................................................... 98
VERIFYING THE MIDLET SUITE JAR..................................................................................................... 98
APPENDIX A: AUDIO MIX TABLE.................................................................................................... 100
APPENDIX B: KEY MAPPING............................................................................................................. 101
KEY MAPPING FOR THE E680 ............................................................................................................... 101
APPENDIX C: MEMORY MANAGEMENT CALCULATION.................................................................. 102
4
Page 5
Table of Contents
VAILABLE MEMORY ................................................................................................................................102
A
MEMORY CALCULATION FOR MIDLETS .................................................................................................... 102
APPENDIX D: FAQ................................................................................................................................103
ONLINE FAQ........................................................................................................................................... 103
APPENDIX E: HTTP RANGE ............................................................................................................... 104
GRAPHIC DESCRIPTION........................................................................................................................... 104
APPENDIX F: SPEC SHEET ............................................................................................................... 105
E680 SPEC SHEET ................................................................................................................................105
5
Page 6
Purpose
1
Introduction
This document describes the applicat ion program interfaces used to develop Motorola compliant Java™ 2 Platform, Micro Edition (J2ME™) app lications for the E680 handset.
Audience
This document is intended for premium J2ME developers and specific carriers involved with the development of J2ME applications for the E680 handset.
Disclaimer
Motorola reserves the right to make changes without notice to any products or services described herein. “Typical” parameters, which may be provided in Motorola Data sheets and/or specifications can and do vary in different a pplications and actual performance may vary. Customer’s technical experts will validate all “Typicals” for each customer application.
Motorola makes no warranty with regard to the products or services contained herein. Implied warranties, including without limitation, the implied warranties of merchantability and fitness for a particular purpose, are given only if specifically required by applicable law. Otherwise, they are specifically excluded.
No warranty is made as to coverage, availability, or grade of service provided by the products or services, whether through a service provider or otherwise.
No warranty is made that the software will meet your requir ements or will work in combination with any hardware or applications software products provided by third parties, that the operation of the software products will be uninterrupted or error free, or that all defects in the software products will be corrected.
6
Page 7
1 Introduction
In no event shall Motorola be liable, whether in contract or tort (including negligence), for any damages resulting form use of a product or service described herein, or for any indirect, incidental, special or consequential damages of any kind, or loss of revenue or profits, loss of business, loss of information or data, or othe r financial loss arising out of or in connection with the ability or inability to use the Products, to the full extent these damages may be disclaimed by law.
Some states and other jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, or limitation on t he length of an implied warranty, so the above limitations or exclusions may not apply to you.
This warranty gives you specific legal rights, and you ma y also have other rights, which vary from jurisdiction to jurisdiction.
Motorola products or services are not designed, i ntended, or authorized for use as components in systems intended for surgical implant into the body, or other applications intended to support or sustain life, or for any other application in which the failure of the Motorola product or service could create a situation where personal injury or death may occur.
Should the buyer purchase or use Motorola products or services for any such unintended or unauthorized application, buyer shall release, indemnify and hold Motorola and its officers, employees, subsidiaries, affiliates, and distributors harmless against all claims, costs, damages, and expenses, and reasonable attorney fees arising out of, directly or indirectly, any claim of personal injury or death associated with such unintended or unauthorized use, even if such claim alleges that Motorola was negligent regarding the designing or manufacture of the product or service.
Motorola recommends that if you are not the sole author or creator of the graphics, video, or sound, you obtain sufficient license rights, including the rights under all patents, trademarks, trade names, copyrights, and other third party proprietary rights.
References
Reference Link
RFC 2068 SAR http://www.wapforum.org MIDP 2.0 http://java.sun.com/products/midp/ JSR 118 http://www.jcp.org JSR 120 http://www.jcp.org JSR 135 http://www.jcp.org Sun MIDP 2.0 SDK http://java.sun.com/products/midp/ TLS protocol version 1.0 http://www.ietf.org/rfc/rfc2246.txt SSL protocol version 3.0 http://home.netscape.com/eng/ssl3/draft302.txt
http://ietf.org/rfc/rfc2068.txt
GSM 03.38 standard
7
http://www.etsi.org
Page 8
GSM 03.40 standard RFC 2437 Sun J2ME http://java.sun.com/j2me/).
http://www.etsi.org http://ietf.org/rfc/rfc2437.txt
Revision History
Version Date Name Reason
0.1 January 14, 2004 Motorola Initial Draft
0.2 February 1, 2004 Motorola Revised Draft
0.3 February 10, 2004 Motorola Revised Draft
0.4 February 16, 2004 Motorola Updated TOC
0.5 March 1, 2004 Motorola JSR 184 added
1.4 June 22, 2004 Motorola Updated per SW
Definitions, Abbreviations, Acronyms
Acronym
AMS Application Management Software API Application Program Interface. CLDC Connected Limited Device Configuration GPS Global Positioning System IDE Integrated Development Environment ITU International Telecommunication Union JAD Java Application Descriptor JAL Java Application Loader JAR Java Archive. Used by J2ME applications for compression and packaging. J2ME Java 2 Micro Edition JSR 120 Java Specification Request 120 defines a set of optional APIs that provides
JVM Java Virtual Machine
Description
standard access to wireless communicatio n resources.
8
Page 9
1 Introduction
KVM Kilo Virtual Machine MIDP Mobile Information Device Profile MMA Multimedia API MT Mobile Terminated OEM Original Equip m ent Manufacturer OTA Over The Air RMS Record Management System RTOS Real Time Operating System SDK Software Development Kit SMS Short Message Service SMSC Short Messaging Service Center SU Subscribe Unit UI User Interface URI Unified Resource Identifier VM Virtual Machine WMA Wireless Messaging API
Document Overview
This developer’s guide is organized int o the following chapters and appendixes: Chapter 1 – Introduction: this chapter has general information about th is document,
including purpose, scope, references, and def initions. Chapter 2 – J2ME Introduction: this chapter describes the J2ME platform and the
available resources on the Motorola E680 handset. Chapter 3 – Developing and Packaging J2ME Applications: this chapter describes
important features to look for when selecting tools and emu lation environments. It also describes how to package a J2ME application, how to package a MIDlet, and generate JAR and JAD files properly.
Chapter 4 –Downloading Applications: this chapter describes the process for downloading applications.
Chapter 5 – Application Management: this chapter describes the lifecycle, installation/de-installation, and updatin g process for a MIDlet suite.
Chapter 6 -- Multiple Applications: this chapter describes all multiple applications. Chapter 7– JAD Attributes: this chapter describes what attributes are supported. Chapter 8 – Gaming API/Multiple Key Press: this chapter describes the Gaming API.
9
Page 10
Chapter 9 – JSR 184: this chapter describes JSR 184. Chapter 10 -- Vibe and Backlight API – this chapter describes the Vibe and Backlight
API. Chapter 11 – Java.lang Implementation: this chapter describes the java.lang
implementation.
Chapter 12 – Networking APIs: this chapter describes the Java Networking API. Chapter 13 – JSR 135 Mobile Media: this chapter describes imag e types and supported
formats. Chapter 14 – JSR 120 Wireless Messaging API: this chapter describes JSR 120
implementation.
Chapter 15 -- Phonebook Access: this chapter describes the Phonebook Access API. Chapter 16 – File System Access: this chapter describes the File System Access API. Chapter 17 – Telephony API: this chapter describes the Telephony API. Chapter 18 – DRM Protection in Java: this chapter describes DRM prot ection of files in
Java.
Chapter 19 – CLDC 1.1: this chapter describes CLDC 1.1 Chapter 20 – JTWI: this chapter describes JTWI functionality. Chapter 21 – MIDP 2.0 Security Model: this chapter describes the MIDP 2.0 default
security model. Appendix A – Key Mapping: this appendix describes the key map ping of the Motorola
E680 handset, including the key name, key cod e, a nd game action of all Motorola keys. Appendix B – Memory Management Calculation: this appendix describes the memory
management calculations.
Appendix C – FAQ: this appendix provides a link to the dynamic online FAQ. Appendix D – HTTP Range: this appendix provides a graphic description of HTTP
Range. Appendix E – Spec Sheet: this appendix provide s the spec sheet for the Motorola E680
handset.
10
Page 11
2 J2ME Introduction
2
J2ME Introduction
The Motorola E680 handset includes the Java™ 2 Platform, Micro Edition, also known as the J2ME platform. The J2ME platform enables developers to easily create a variety of Java applications ranging from business ap plications to games. Prior to its inclusion, services or applications residing on small consumer devices like cell phones could not be upgraded or added to without significant effort. By implementing the J2ME platform on devices like the Motorola E680 handset, service providers, as well as customers, can easily add and remove applications allowing for quick and easy personalization of each device. This chapter of the guide presents a quick overview of the J2ME environment and the tools that can be used to develop applications for the Motorola E680 handset.
The Java 2 Platform, Micro Edition (J2ME)
The J2ME platform is a new, very small application environment. It is a framework for the deployment and use of Java technology in small devices such as cell phones and pagers. It includes a set of APIs and a virtual machine that is designed in a modular fashion allowing for scalability among a wide range of devices.
The J2ME architecture contains three layers cons isting of the Java Virtual Machine, a Configuration Layer, and a Profile Layer. Th e Virtual Machine (VM) supports the Configuration Layer by providing an interface to the host operating system. Above the VM is the Configuration Layer, which can be thought of as the lowest common denominator of the Java Platform available across devices of the same “horizontal market.” Built upon this Configuration Layer is the Profile Layer, typically encompassing the presentation layer of the Java Platform.
Native
MIDP-Compliant
MIDP-Compliant
Apps
Apps
MIDP
MIDP
CLDC
CLDC Native System Software
Native System Software
OEM
OEM Apps
Apps
OEM
OEM Classes
Classes
Native Apps
Apps
Mobile Information Device
Mobile Information Device
11
Page 12
The Configuration Layer used in the Motorola E680 handset is the Connected Limited Device Configuration 1.1 (CLDC 1.1) and th e Profile Layer used is the Mobile Information Device Profile 2.0 (MIDP 2.0). Together, the CLDC and MIDP provide common APIs for I/O, simple math functionality, UI, and more.
For more information on J2ME, see the Sun™ J2ME do cumentation (http://java.sun.com/j2me/
).
The Motorola J2ME Platform
Functionality not covered by the CLDC and MIDP APIs is left for individual OEMs to implement and support. By adding to the standard APIs, manufacturers can allow developers to access and take advantage of the unique functionality of their handsets.
The Motorola E680 handset contain OEM APIs for extended functionality ranging from enhanced UI to advanced data security. While t he Motorola E680 handset can run any application written in standard MIDP, it can also run app lications that take advantage of the unique functionality provided by these APIs. These OEM APIs are described in this guide.
Resources and API’s Available
MIDP 2.0 will provide support to the following functional areas on the Motorola E680 handset:
MIDP 2.0
Application delivery and billing
Application lifecycle
Application signing model and privileged security model
End-to-end transactional security (HTTPS)
MIDlet push registration (server push model)
Networking
Persistent storage
Sounds
Timers
User Interface
File Image Support (.PNG, .JPEG, .GIF)
12
Page 13
2 J2ME Introduction
Additional Functionality
WMA (JSR 120)
MMA (JSR 135)
M3D (JSR 184)
Fun Lights API
Phonebook API
File System API
Telephony API
13
Page 14
Developing and Packaging
J2ME Applications
Guide to Development in J2ME
3
Introduction to Development
This appendix assumes the reader has previous experience in J2ME development and can appreciate the development process for Java MIDlets. This appendix will provide some information that a beginner in devel op m ent can use to gain an understanding of MIDlets for J2ME handsets.
There is a wealth of material on this subject on websites maintained by Motorola, Sun Microsystems and others. Please refer to the following URLs for more information:
http://www.motocoder.comhttp://www.java.sun.com/j2mehttp://www.corej2me.com/http://www.javaworld.com/
As an introduction, brief details of J2ME are explaine d below. The MIDlet will consist of two core specifications, namely Connected, Limited Device
Configuration (CLDC) and Mobile Informat ion Device Profile (MIDP). Both of these specifications (Java Specification Reque s ts) can be located at the http://www.jcp.org/ for reading.
For MIDP 1.0; JSR 37 should be reviewed.
site
For MIDP 2.0; JSR 118 should be reviewed. For CLDC 1.0.4; JSR 30 should be reviewed. For CLDC 1.1; JSR 139 should be reviewed.
To determine what implementation is on Motorola handset, review the “Java System” details through the menu on the Motorola handset (located under Java Settings).
14
Page 15
3 Developing and Packaging J2ME Applications
For beginning development, key points to remember are memory size, processing power, screen capabilities and wireless networ k characteristics. These all play an important part in development of a MIDlet. The specifications listed above are designed to work upon devices that have these characteristics.
Network conditions would only apply for n etworked applications such as streaming tickers, email clients, etc.
In addition to the specifications, an array of tools is available to assist the development cycle. These range from the command line tools provided with Software Development Kits (SDK) from Sun (as of writing 1.4.1_04) to Integrated Develo pment Environments (IDEs) which can be free or purchased. These IDEs come from a range of sources such as Sun, IBM, Metrowerks and Borland to name a few.
For a look at such environments, review the “M otorola T720 Handset Developer Guide” which is available from the MOTOCODER website.
In addition to the IDEs and Sun SDK for development, Motorola offers access to our own SDK which contains Motorola device emulators. From here, a MIDlet can be built and then deployed onto an emulated target handset. This will enable debugging and validation of the MIDlet before deployment to a real, physical hands et. The latest Motorola SDK can be downloaded from the MOTOCODER website.
Please refer to the product specifications at the back of this guide for detailed information on each handset.
15
Page 16
Downloading Applications
Method of Downloading
The option open to the developer for deploying the MIDlet t o a p hysical Motorola device is OTA (over -the-air) downloading.
4
OTA
To use the OTA method, the developer will have a connection through a wireless network to a content server. This content server could be, for example, Apache (
http://httpd.apache.org) which is free to use, deployable on multiple operating systems,
and has extensive documentatio n on how to configure the platform. The required file will be downloaded (eith er .jad and/or .jar) by issuing a direct URL
request to the file in question or it could be a URL r equest to a WAP page and a hyperlink on that page to the target file. This request will be made through the Motorola Internet Browser (MIB). In MIDP 2.0, the need for a JAD file before download is not required, so the JAR file can be downloaded directly. The information about the MIDlet will be pulled from the manifest file.
The transport mechanism used to download the file will be one of two depending on the support from the network operators WAP Gateway and the size of file requested.
HTTP Range – see specification RFC 2068 at
if content greater than 30k in size. Below is a ladder diagram showing the flow through HTTP range transfer, although recall use of the .JA D is optional.
SAR (Segmentation & Reassembly) – see specification of wireless transaction
protocol at the
During a download of the application, the use r will see the MIB 2.2 browser displaying a progress dialog for either SAR or HTTP Byte Range type downloads.
http://www.wapforum.org if less than 100k in size.
http://www.rfc-editor.org/rfc.html
A complete guide for setting up an OTA server can be obtained through the MOTOCODER website (http://www.motocoder.com the server and also example WAP pages.
In this handset, the user is given an option of deleting any MIDlets that are on the phone if an OTA download cannot be achieved due to lack of space.
16
). This includes details of configuring
Page 17
4 Downloading Applications
The following error codes are supported:
900 Success 901 Insufficient Memory 902 User Cancelled 903 Loss Of Service 904 JAR Size Mismatch 905 Attribute Mismatch 906 Invalid Descriptor 907 Invalid JAR 908 Incompatible Configuration or Profile 909 Application Authentication Failur e 910 Application Authorization Failure 911 Push Registration Failure 912 Deletion Notification 913 Required package not supporte d by device 999 Other errors
Please be aware that the method used by the handset, as per the specifications, is POST. Using a GET (URL encoding) style for the URL will fail. This is not the correct use of the MIDlets JAD parameters.
Possible Screen Messages Seen With Downloading:
If JAR -file size does not match with specified size, it will display a dialog stating
When downloading is done, the handset displays a transient notice “Download
Upon completing installation, the handset displays a dialog “Install complete”. To
If the MANIFEST file is wrong, the handset displays a dialog stating “Installation
If JAD does not contain mandatory attributes, “Installation failed. Package
“Installation failed. Package in valid.” To dismiss this dialog, press “OK”.
Completed” and starts to install the application.
dismiss this dialog, press “OK”.
failed. Package invalid.” To dismiss this dialog, press “OK”.
invalid.” notice appears.
The USER-AGENT String
The following table describes USER_AGENT strings associated with Motorola devices:
Motorola Device USER_AGENT STRING
E680
User-Agent: MOT-E680/xx.xx.xx MIB/2.2 Profile/MIDP-2.0 Configuration/CLDC-1.1
The USER_AGENT string can be used to identify a handset and render specific content to it based on it information provided in this string (example CGI on a content server). These strings can be found in the connection logs at the content server.
17
Page 18
This table above provides information about the following components:
1. WAP Browser Release, Motorola Internet Browser (MIB) 2.2
2. MIDP version 2.0
3. CLDC version 1.1
4. The Phone Software Version is detailed by xx.xx.xx
Error Logs
The following table represents the error logs associated with downloading applications.
Error Logs Scenario Possible Cause Error Dialog
Failed: Invalid File JAD
Download
Download Failed OTA JAR
Download
Cancelled: <Icon> <Filename> Download Failed OTA JAR
OTA JAR Download
Download
Missing or incorrectly formatted mandatory JAD attributes
Mandatory: MIDlet-Name (up to 32 symbols) MIDlet-Version MIDlet-Vendor (up to 32 symbols) MIDlet-JAR-URL (up to 256 symbols) MIDlet-JAR_Size The received JAR size does not match the
size indicated
User cancelled download 902
Browser lost connection with server Certification path cannot be validated JAD signature verification failed Unknown error during JAD validation
906 Installation failed. Package invalid.
904 Installation failed. Package invalid.
903 Dowload failed.
Insufficient Storage OTA JAR
Download
Application Already Exists
18
OTA JAR Download
See ‘Details’ field in the dialog for information about specific error
Insufficient data space to temporarily store the JAR file
MIDlet version numbers are identical 905 Attribute
901 Memory Full. Cannot install application.
Mismatch
Page 19
4 Downloading Applications
Different Version Exists
OTA JAR Download
MIDlet version on handset supercedes v ersion being downloaded
Failed File Corrupt Installation Attributes are not identical to respective JAD
attributes
Insufficient Storage Installation Insufficient Program Space or Data Space to
install suite
Application Error Installation Class references non-existent class or method
Security Certificate verification failure Checksum of JAR file is not equal to
Checksum in MIDlet-JAR-SHA attribute Application not authorized
Application Expired MIDlet
Security Certificates expired or removed
Launching
Application Error MIDlet
Execution
Authorization failure during MIDlet exec ution Incorrect MIDlet
901 Memory Full. Cannot install application.
19
Page 20
5
Application Management
The following sections describe the application management scheme for the Motorola E680 handset. This chapter will discuss the following:
Downloading a JAR without a JAD
MIDlet upgrade
Installation and Deletion Status Reports
Downloading a JAR file without a JAD
In Motorola’s MIDP 2.0 implementation, a JAR file can be downloaded without a JAD. In this case, the user clicks on a link for a JAR file, the file is downloaded, and a confirmation will be obtained before the installation begi ns. The information presented is obtained from the JAR manifest instead of the JAD.
MIDlet Upgrade
Rules from the JSR 118 will be followed to help determine if the data from an old MIDlet should be preserved during a MIDlet upgrade. When th ese rules cannot determine if the RMS should be preserved, the user will be given an option to preserve the data.
The following conditions are used to determine if data can be saved:
The data is saved if the new MIDlet-version is the same or newer, and if the new MIDlet-data-space requirements is the same or more than t he current MIDlet.
The data is not saved if the new MIDlet-data-space requirement is smaller than the current MIDlet requirement.
The data is not saved if the new MIDlet-version is older than the current version.
If the data cannot be saved, the user will be warned a bout losing data. If the user proceeds, the application will be downloaded. If the user decides to save the data from the current MIDlet, the data will be preserved during the upgrade and the data will be made available for the new application. In any case, an unsigned MIDlet will not be allowed to update a signed MIDlet.
20
Page 21
5 Application Management
Installation and Deletion Status Reports
The status (success or failure) of an installation, upgra de, or deletion of a MIDlet suite will be sent to the server according to the JSR 118 specification. If the status report cannot be sent, the MIDlet suite will still be enabled and the user will be allowed to use it. In some instances, if the status report cannot be sent, the MIDlet will be deleted by operator’s request. Upon successful deletion, the handset will send the status code 912 to the MIDlet-Delete-Notify URL. If this notification fails, the MIDlet suite will still be deleted. If this notification cannot be sent due to lack of network connectivity, the notification will be sent at the next available network connection.
Refer to the table below for application management feature/class support for MIDP 2.0:
Feature/Class
Application upgrades performed directly through the AMS When removing a MIDlet suite, the user will be pr ompted to confirm the entire MIDlet suite will be
removed Application Descriptor included the attribute MIDlet-Delete-Confirm, its value will be included in the
prompt Prompt for user approval when the user has chos en to download an application that is identical to, or an
older version of an application currently in the handset Unauthorized MIDlets will not have access to any restricted function call AMS will check the JAD for security indicated every time a download is initiate d Application descriptor or MIDlet fails the security check, the AMS will prevent the installation of that
application and notify the user that the MIDlet could not be installed Application descriptor and MIDlet pa ss the security check , the AMS will install the MIDlet and grant it the
permissions specified in the JAD A method for launching Java application that mainta ins the same look and feel as other features on the
device will be provided User will be informed of download and installation with a single progress indicator and will be given an
opportunity to cancel the process User will be prompted to launch the MIDlet after installation A method for creating shortcuts to Java applications wil l b e provided. A no forward policy on DRM issues, included but not limited to transferring the application over-the-air,
IRDA, Bluetooth, I/O Cables, External storage devices, etc until further guidance is provided
21
Page 22
Multiple Applications
Since the Motorola E680 is a Linux based device, multiple tasks are allowed to run at the same time. If the focus is out, the MIDlet method pauseApp () will be called. From there, the developer will decide what happens next as the VM continues to run. If the focus is in, the application will start from MIDlet method startApp ().
6
Multiple Applications
For the limited resource, native applications such as notebook or calendar will kill the VM if they are launched.
22
Page 23
7 JAD Attributes
JAD Attributes
JAD / Manifest Attribute Implementations
The JAR manifest defines attributes to be used by the application management software (AMS) to identify and install the MIDlet suite. These attributes may or may not be found in the application descriptor.
7
The application descriptor is used, in conjunction with the JAR manifest, by the application management software to manage the MIDlet. The application descriptor is also used for the following:
By the MIDlet for configuration specific attributes
Allows the application management software on the handset to verify the MIDlet
is suited to the handset before loading the JAR file
Allows configuration-specific attributes (parameters) to be supplied to the MIDlet(s) without modifying the JAR file.
Motorola has implemented the follo wing support for the MIDP 2.0 Java Application Descriptor attributes as outlined in the JSR-118. The table below lists all MIDlet attributes, descriptions, and its location in the JAD and/or JAR manifest that are supported in the Motorola implementation.
Attribute Name Attribute Description JAR Manifest JAD
MIDlet-Name The name of the MIDlet suite that
identifies the MIDlets to the user
MIDlet-Version The version number of the MIDlet suite Yes Yes
Yes Yes
MIDlet-Vendor The organization that provides the
MIDlet suite.
MIDlet-Icon The case-sensitive absolute name of a
PNG file within the JAR used to
23
Yes Yes
Yes Yes
Page 24
represent the MIDlet suite. MIDlet-Description The description of the MIDlet suite. Yes Yes MIDlet-Info-URL A URL for information further
Yes No
describing the MIDlet suite. MIDlet-<n> The name, icon, and class of the nth
MIDlet in the JAR file.
Name is used to identify this MIDlet to
Yes, or no if included in the JAD.
Yes, or no if included in the JAR Manifest.
the user. Icon is as stated above.
Class is the name of the class
extending the
javax.microedition.midl
et.MIDletclass.
MIDlet-Jar-URL The URL from which the JAR file can
Yes
be loaded. MIDlet-Jar-Size The number of bytes in the JAR file. Yes MIDlet-Data-Size The minimum number of bytes of
Yes Yes
persistent data required by the MIDlet. MicroEdition-Profile The J2ME profiles required. If any of
the profiles are not implemented th e
installation will fail. MicroEdition-
Configuration
The J2ME Configuration required, i.e
CLDC 1.0
Yes, or no if included in the JAD.
Yes, or no if included in the JAD.
Yes, or no if included in the JAR Manifest.
Yes, or no if included in the JAR Manifest.
MIDlet-Permissions Zero or more permissions that are
critical to the function of the MIDlet
suite. MIDlet-Permissions-Opt Zero or more permissions that are non-
critical to the function of the MIDlet
suite. MIDlet-Push-<n> Register a MIDlet to hand le inbound
connections MIDlet-Install-Notify The URL to which a POST request is
sent to report installation status of the
MIDlet suite. MIDlet-Delete-Notify The URL to which a POST request is
sent to report deletion of the MIDlet
suite. MIDlet-Delete-Confirm A text message to be provided to the
user when prompted to confirm
deletion of the MIDlet suite. Background MIDlets with this Motorola specific
attribute will continue to run when not
Yes Yes
Yes Yes
Yes Yes
Yes Yes
Yes Yes
Yes Yes
No No
24
Page 25
7 JAD Attributes
in focus.
25
Page 26
Gaming API/Multiple Key Press
Gaming API
The Gaming API provides a series of classes that enable rich gaming content for the handset. This API improves performance by minimizing the amount of work done in Java, decreasing application size. The Gaming API is structured to provide freedom in implementation, extensively using native code, hardware acceleration, and device-specific image data formats as needed.
8
The API uses standard low-level graphic classes from MIDP so the high-level Gaming API classes can be used in conjunction with graphics primitives. This allows for rendering a complex background using the Gaming API while rendering something on top of it using graphics primitives.
Methods that modify the state of Layer, LayerManager, Sprite, and TiledLayer objects generally do not have any immediate visible side effects. Instead, this state is stored within the object and is used during subsequent calls to the paint() method. This approach is suitable for gaming applications where there is a cycle within the objects’ states being updated and the entire scr een is redrawn at the end of every game cycle.
Multiple Key Press Support
Multi-button press support enhances the gaming experience for the user. Multi-button press support gives the user the ability to press two (2) keys simultaneously and the corresponding actions of both keys will occur simultaneously. An example of this action would be the following:
If Left + Fire were pressed at the same time, the Java object (e.g C anvas) will receive Left Pressed + Fire Pressed. In the same way, when the 2 keys are released, Java object (e.g. Canvas) will recei ve Left Released + Fire Released.
The following sets of keys will support multi-button press su pport on the Motorola E680 handset. Multi-button press within each set will be supported, while multi-button press across these sets or with other keys will not be supported.
Set 1 – Nav (Up), Nav (Down), Nav (Right, Nav (Left)
26
Page 27
8 Gaming API/Multiple Key Press
Refer to the table below for gaming and keypad feature/class support for MIDP 2.0:
Feature/Class Implementation
lcdui.game package Supported setBacklight as defined in javax.microedition.lcdui.Display Supported setVibrator as defined in javax.microedition.lcdui.Display Supported All constructors and inherited classes for the IllegalStateException in
java.lang All constructors, methods, and inherited classes for the Timer class in
java.util All the constructors, methods, and inherited classes for the TimerTask
class in java.util All fields, constructors, methods, inherited fields and inherited methods
for the GameCanvas class in javax.microe dition.lcdui.game Map the UP_PRESSED field in
javax.microedition.lcdui.game.GameCanvas to the top position of the key.
Map the DOWN_PRESSED field in javax.microedition.lcdui.GameCanvas to the bottom position of the key
Map the LEFT_PRESSED field in javax.microedition.lcdui.GameCanvas to the left position of the key
Map the RIGHT_PRESSED field in javax.microedition.lcdui.GameCanvas to the right position of the key
All methods and inherited methods for the Layer class in javax.microedition.lcdui.game
Supported
Supported
Supported
Supported
Supported
Supported
Supported
Supported
Supported
All constructors, methods, and inherited methods for the LayerManager class in javax.microedition.lc du i.game. La yer
All fields, constructors, methods, and inherited methods for the Sprite Class in javax.microedition.lcdui.game
Sprite Frame height will not be allowed to exceed the height of the view window in javax.microedition.lcdui.Layer
Sprite frame width will not be allowed to exceed the width view of the view window in javax.microedition.lcdui.Layer
Sprite recommended size 16*16 or 32*32 All constructors, methods, and inherited methods for the Ti ledLayer
class in javax.microedition.lcdui.game MIDlet Queries to keypad hardware Supported Alpha Blending Transparency only
27
Supported
Supported
Any, limited by heap size only
Any, limited by heap size only
Supported
Page 28
28
Page 29
9 JSR 184
Overview
JSR 184 Mobile 3D API defines an API for rendering three- dimensional (3D) graphics at interactive frame rates, including a scene graph structure and a corresponding file format for efficient management and deployment of 3D content. Typical applications that might make use of JSR 184 Mobile 3D API include games, ma p visualizations, user interface, animated messages, and screen savers. JSR 184 requires a J2ME device supporting MIDP 2.0 and CLDC 1.1 at a minimum.
9
JSR 184
Mobile 3D API
The Motorola E680 contains full implementation of JSR 184 Mobile 3D API (
http://jcp.org/en/jsr/detail?id=184). The Motorola E680 has also implemented the
following:
Call to
1.0, otherwise null will be returned.
Floating point format for input and output is the standar d IEEE float having a 8-bit exponent and a 24-bit mantissa normalized to 1.0, 2.0.
Implementation will ensure the Object3D instances will be kept reference to reduce overhead and possible inconsistency.
Thread safety
Necessary pixel format conversions for renderin g output onto device
Support at least 10 animation tracks to be associated with an Object 3D instance
(including animation controller) subject to dynamic memory availability.
System.getProperty with key – microedition.m3g.version will return
29
Page 30
Mobile 3D API File Format Support
The Motorola E680 supports both M3G and PNG file formats for loading 3D content. The E680 supports the standard .m3g and .png extensions for its file formats. Mime type and not extension will be used for identifying fil e type. In the case that the Mime type is not available, M3G files will be identified using the file identifier and PNG files using signature.
Mobile 3D Graphics – M3G API
The M3G API lets you access the realtime 3D engine embedded on the device, to create console quality 3D applications, such as games and menu systems. The main benefits of the M3G engine are the following:
the whole 3D scene can be stored in a very small file size (typically 50-150K),
allowing you to create games and a pplications in under 256K;
the application can change the properti es (such as position, rotation, scale, color
and textures) of objects in the scene based on user interaction with the device;
the application can switch between cameras to get different views onto the
scene;
the rendered images have a very high photorealistic quality.
Typical M3G Application
An application consists of logic that uses the M3G, MIDP 2.0 and CDLC 1.1 classes. The application is compiled into a Java MIDlet that can be downloaded OTA or embedded on the target device. The MIDlet can also cont ain additional assets, such as one or more M3G files that define the 3D scene graph for the objects in t he scene, images and sounds.
30
Page 31
9 JSR 184
Most M3G applications use an M3G resource file that contains all the information required to define the 3D resources, such as objects, their appearance, lights, cameras and animations, in a scene graph. The file must be lo aded into memory where object properties can be interrogated and altered using the M3G API. Alternatively all objects can be created from code, although this is likely to be slower and limits creativity for designers.
Simple MIDlets
The simplest application consists of an M3G file that is l oaded into the application using the M3G Loader class, which is then passed to a Graphics3D object that renders the world to the Display.
31
Page 32
The World object contains the objects that define a complete 3D scene - geometry, textures, lights, cameras, and animations. The World o bj ect mediates access to the objects within the world. It can be passed as a block to the renderer, the Graphics3D class.
The Loader object, populates a World by loading an M3G file from a URI or other asset source, such as a buffer of bytes in M3G format. The Loader is not restricted to loading just Worlds, each file can contain as little as a si ngle object and multiple files can be merged together on the device, or you can put everything into a single file.
The rendering class Graphics3D (by analogy to the MIDP Graphics class) takes a whole scene (or part of a scene graph), and renders a view onto that scene using the current camera and lighting setup. This view can be to the screen, to a MIDP image, or to a texture in the scene for special effects. You c an pass a whole world in one go (retained mode) or you can pass individual objects (immediate mode). There is only one Graphics3D object present at one time, so that hardware accelerators can be used.
The following graphic shows the structure of a more typical MIDlet.
32
Page 33
9 JSR 184
Initializing the world
The Loader class is used to initialize the world. It has two static methods: one takes in a byte array, while the other takes a named resource, s uch as a URI or an individual file in the JAR package.
The
load methods return an array of Object3Ds that are the root level objects in the file.
The following example calls Loader.load () and passes it an M3G file from the JAR file using a property in the JAD file. Alternatively, you could specify a URI, for example:
Object3D[] roots = Loader.load(http://www.example.com/m3g/simple.m3g)[0
The example assumes that there is only one root node in the scene, which will be the world object. If the M3G file has multiple root nodes the cod e must be changed to reflect this, but generally most M3G files have a single root node.
public void startApp() throws MIDletStateChangeException { myDisplay.setCurrent(myCanvas);
];
try { // Load a file. Objects3D[] roots = Loader.load(getAppProperty("Content-
33
Page 34
1"));
// Assume the world is the first root node loaded. myWorld = (World) roots[0]; } catch(Exception e) { e.printStackTrace(); }
// Force a repaint so the update loop is started. myCanvas.repaint(); }
Using the Graphics3D object
Using the Graphics3D is very straightforw ard. Get the Graphics3D instance, bind a target to it, render everything, and release the target.
public class myCanvas extends Canvas { Graphics3D myG3D = Graphics3D.getInstance();
public void paint(Graphics g) { myG3D.bindTarget(g); try { myG3D.render(myWorld); } finally { myG3D.releaseTarget(); } }
34
Page 35
9 JSR 184
}
The finally block makes sure that the target is rel eased and the Graphics3D can be reused. The bindTarget call must be outside the try block, as it can throw exceptions that will cause releaseTarget to be called w hen a target has not been bound, and releaseTarget throwing an exception.
Interrogating and interacting with objects
The World object is a container that sits at the top of the hierarchy of obj ects that form the scene graph. You can find particular objects with in the scene very simply by calling find() with an ID. find() returns a reference to the object which has been assigne d that ID in the authoring tool (or manually assigned from code). This is important because it largely makes the application logic independent of the detailed structure of the scene.
final int PERSON_OBJECT_ID = 339929883; Node personNode = (Node)theWorld.find(PERSON_OBJECT_ID);
If you need to find many objects, or you don’t have a fixed ID, then you can follow the hierarchy explicitly using the Object3D.getReferences() or Group.getChild() method s.
static void traverseDescendants(Object3D obj) { int numReferences = obj.getReferences(null);
if (numReferences > 0) { Object3D[] objArray = new Object3D[numReferences]; obj.getReferences(objArray);
for (int i = 0; i < numReferences; i++) traverseDescendants(objArray[i]); } }
Once you have an object, most of the properties on it can be modified using the M3G API. For example, you can change the position, size, orientation, color, brightness, or whatever other attribute of the object is important. You can also create and delete objects and insert them into the world, or link parts of other M3G files into the scene graph.
35
Page 36
Animations
As well as controlling objects from code, scene designers can specify how objects should move under certain circumstances, and store this movement in “canned” or block animation sequences that can be triggered from code. Many object properties are animatable, including position, scale, orientation, color and textures. Each of these properties can be attached to a sequence of keyframes using an AnimationTrack. The keyframe sequence can be looped, or just pl ayed once, and they can be interpolated in several ways (stepwise, linear, spline).
A coherent action typically requires the simultaneous animation of several properties on several objects, the tracks are grouped together using the AnimationController object. This allows the application to control a whole animation from one place.
All the currently active animatable prope r ties can be updated by calling animate() on the World. (You can also call this on individual objects if you need more control). The current time is passed through to animate(), and is used to determine the interpolated value to assign to the properties.
The animate() method returns a validity value that i ndicates how long the current value of a property is valid. Generally this is 0 which means that the object is still being animated and the property value is no longer valid, or i nfin ity when the object is in a static state and does not need to be updated. If nothing is happening in the scene, you do not have to continually redraw the screen, reducin g the processor load and extending battery life. Similarly, simple scenes on powerful hardware may run very fast; by restricting the frame­rate to something reasonable, you can extend battery life and are more friendly to background processes.
The animation subsystem has no memory, so time is completely arbitrary. This means that there are no events reported (for example, animation finished). The application is responsible for specifying when the animati on is active and from which position in the keyframe sequence the animated property is played.
Consider a world myWorld that contains an animati on of 2000 ms, that you want to cycle. First you need to set up the active interval for the animation, and set th e position of the sequence to the start. Then call World.animate() with the current worl d time:
anim.setActiveInterval(worldTime, worldTime+2000); anim.setPosition(0, worldTime);
int validity = myWorld.animate(worldTime);
36
Page 37
9 JSR 184
Authoring M3G files
You can create all your M3G content from code if necessary but this is likely to be very time consuming and does not allow 3D artists and scene designers to easily create and rework visually compelling content with com plex animations. You can use professional, visual development tools such as Swerve Superscape Group plc, which export content from 3ds max, the industry standard 3D animation tool, in fully compliant M3G format. For more information please visit http://www.superscape.com/.
TM
Studio or SwerveTM M3G exporter from
37
Page 38
Vibe and Backlight API
Vibe and Backlight API
The Vibe and Backlight API allows J2ME applications access to vibrator, backlight, and keypad controls. This API gives a MIDlet the ability to turn thes e features on or off based on the applications needs. The MIDlet will use this API to enhance the activity being performed by the application.
10
Examples of this enhancement are the following:
1. When in a driving game application, the vibra tor is turned on during a crash.
2. An alarm application would have access to turn the vibrator on and off.
3. A stock ticker application turns the backlight on and off wh en a specified stock hits a target price.
Native constraints are in place to protect the battery life of the product. These native constraints will be flexible to allow the operator to make the final call on implementation. For more information refer to the MIDP 2.0 specification.
The following are code samples to show implementation of the Vibe and Backlight API:
Sample of code for calling of ‘vibrate(int)’ method of Display class:
int duration = 5000;//5 seconds;
java.lang.boolean returnValue = display.vibrate(duration);
if (returnValue != false) { System.out.println("Invoke vibrate method with parameter = "
+ duration + ", method returns : " + returnValue); } else { System.out.println("Failed: invoke vibrate(" + duration +
"), method returns false"); }
38
Page 39
10 Vibe and Backlight API
Sample of code for calling of ‘flashBacklight(int)’ method of Display class:
int duration = 30000;// 30 seconds;
java.lang.boolean returnValue = display.flashBacklight(duration);
if (returnValue != false) { System.out.println("Invoke flashBacklight method with
parameter = " + duration + ", method returns : " + returnValue);
} else { System.out.println("Failed: invoke flashBacklight(" +
duration + "), method returns false"); }
39
Page 40
Java.lang Implementation
java.lang support
Motorola implementation for the java.lang.System.getProperty method will support additional system properties bey on d what is outlined in the JSR 118 specification and is controlled by a flex bit. These additional system properties can only be accessed by trusted MIDlets.
11
The additional system properties are as follows:
Cell ID: The current Cell ID of the device will be returned during implementation.
IMEI: The IMEI number of the device will be returned during implementation.
The following are code samples for java.lang support:
System.getProperty("phone.mcc") System.getProperty("phone.mnc") System.getProperty("phone.imei") System.getProperty("phone.cid") System.getProperty(“phone.lai”) System.getProperty(“phone.ta”)
40
Page 41
12 Network APIs
Network Connections
The Motorola implementation of Networking APIs will support several network connections. The network connections necessary for Motorola implementation are the following:
12
Network APIs
CommConnection for serial interface
HTTP connection
HTTPS connection
SSL
Refer to the table below for Network API feature/class support for MIDP 2.0:
Feature/Class Implementation
All fields, methods, and inherited methods for the Connector class in the javax.microedition.io package
Mode parameter for the open () method in the Connector class the javax.microedition.io package
The timeouts parameter for the open () method in the Connector clas s of the javax.microedition.io package
HttpConnection interface in the javax.microedition.io p ackage Supported HttpsConnection interface in the javax.microeditio n.io package Supported SecureConnection interface in the javax.microedition.io package Supported SecurityInfo interface in the javax.microedition.io package Supported
Supported
READ, WRITE, READ_WRITE
Supported
ServerSocketConnection interface in the javax.microedition.io package Supported UDPDDatagramConnection interface in the javax.microedition.io
package
41
Supported
Page 42
Connector class in the javax.microedition.io.package Supported Dynamic DNS allocation through DHCP Supported
HttpConnection interface in the javax.microedition.io.package. Supported HttpsConnection interface in the javaxmicroedition.io.package Supported SecureConnection interface in the javax.microedition.io.package Supported SecurityInfo Interface in the javax.microedition.io.package Supported ServerSocketConnection interface in the javax.microedition.io.package Supported UDPDatagramConnection interface in the
javax.microedition.io.package
The following is a code sample to show implementation of Socket Connection:
Socket Connection
import javax.microedition.io.*; import java.io.*; import javax.microedition.midlet.*;
….
try { //open the connection and io streams sc = (SocketConnection)Connector.open("socket://www.myserver.com :8080", Connector.READ_WRITE, true); is = sc[i].openInputStream(); os = sc[i].openOutputStream();
} catch (Exception ex) { closeAllStreams(); System.out.println("Open Failed: " + ex.getMessage()); } } if (os != null && is != null) { try { os.write(someString.getBytes()); //write some data to server
int bytes_read = 0; int offset = 0; int bytes_left = BUFFER_SIZE;
//read data from server until done do { bytes_read = is.read(buffer, offset,
Supported
42
Page 43
12 Network APIs
bytes_left);
if (bytes_read > 0) { offset += bytes_read; bytes_left -= bytes_read; } } while (bytes_read > 0);
} catch (Exception ex) { System.out.println("IO failed: "+ ex.getMessage()); } finally { closeAllStreams(i); //clean up } }
User Permission
The user of the handset will explicitly grant permission to add additional network connections.
Indicating a Connection to the User
When the java implementation makes any of the additional network connections, it will indicate to the user that the handset is actively interacti ng with the network. To indicate this connection, the network icon will appear on the h andset’s status bar as shown below.
Conversely, when the network connection is no longer used the network icon will be removed from the status bar.
43
Page 44
HTTPS Connection
Motorola implementation supports a HTTPS connection on the Motorola E680 handset. Additional protocols that will be supported are the following:
TLS protocol version 1.0 as defined in
http://www.ietf.org/rfc/rfc2246.txt
SSL protocol version 3.0 as defined in
http://home.netscape.com/eng/ssl3/draft302.txt
The following is a code sample to show implementation of HTTPS:
HTTPS
import javax.microedition.io.*; import java.io.*; import javax.microedition.midlet.*; …
try { hc[i] =
(HttpConnection)Connector.open(“https://” + url[i] + "/");
} catch (Exception ex) { hc[i] = null; System.out.println("Open Failed: " +
ex.getMessage()); }
if (hc[i] != null) { try { is[i] = hc[i].openInputStream();
byteCounts[i] = 0; readLengths[i] = hc[i].getLength();
System.out.println("readLengths = " + readLengths[i]);
if (readLengths[i] == -1) { readLengths[i] = BUFFER_SIZE; }
int bytes_read = 0; int offset = 0; int bytes_left = (int)readLengths[i];
do
44
Page 45
12 Network APIs
{ bytes_read = is[i].read(buffer, offset,
bytes_left); offset += bytes_read; bytes_left -= bytes_read; byteCounts[i] += bytes_read; } while (bytes_read > 0);
System.out.println("byte read = " + byteCounts[i]);
} catch (Exception ex) { System.out.println("Downloading Failed: "+
ex.getMessage()); numPassed = 0; } finally { try { is[i].close(); is[i] = null; } catch (Exception ex) {} } } /** * close http connection */ if (hc[i] != null) { try { hc[i].close(); } catch (Exception ex) { } hc[i] = null; }
45
Page 46
JSR 135 Mobile Media API
JSR 135 Mobile Media API
The JSR 135 Mobile Media APIs feature sets are defined for five different types of media. The media defined is as follows:
13
Tone Sequence
Sampled Audio
MIDI
When a player is created for a particular type, it will follow the guidelines and control types listed in the sections outlined below.
The following is a code sample to show implementation of the JSR 135 Mobile Media API:
JSR 135
Player player;
// Create a media player, associate it with a stream containing media data
try { player =
Manager.createPlayer(getClass().getResourceAsStream("MP3.mp3 "), "audio/mpeg");
} catch (Exception e) { System.out.println("FAILED: exception for createPlayer:
" + e.toString()); }
// Obtain the information required to acquire the media resources
try
46
Page 47
13 JSR 135 Mobile Media API
{ player.realize(); } catch (MediaException e) { System.out.println("FAILED: exception for realize: " +
e.toString()); }
// Acquire exclusive resources, fill buffers with media data try { player.prefetch(); } catch (MediaException e) { System.out.println("FAILED: exception for prefetch: " +
e.toString()); }
// Start the media playback try { player.start(); } catch (MediaException e) { System.out.println("FAILED: exception for start: " +
e.toString()); }
// Pause the media playback try { player.stop(); } catch (MediaException e) { System.out.println("FAILED: exception for stop: " +
e.toString()); }
// Release the resources
player.close();
47
Page 48
ToneControl
ToneControl is the interface to enable playback of a user-defined monotonic tone sequence. The JSR 135 Mobile Media API will implement public interface ToneControl.
A tone sequence is specified as a list of non-tone duration pairs and user-defined sequence blocks and is packaged as a n array of bytes. The setSequence() method is used to input the sequence to the ToneControl.
The following is the available method for ToneControl:
-setSequence (byte[] sequence): Sets the tone sequence
Video Control
VideoControl is an interface for manipulati ng the video of a Player. The JSR 135 Mobile Media API will implement public interface VideoControl. An application can use the VideoControl to display a viewfinder on the screen, then take a picture using VideoControl.getSnapshot (String imageType). VideoControl controls the display of the video, and for example, its location relative to the ca nvas where it is displayed.
Snapshot Image
If a video snapshot is taken (by VideoControl's method 'getSnapshot'), the supported image types are:
"encoding=png" and "encoding=jpeg". The image type may optionally include width and height parameters (which default to 192x192, the minimum size is 160x120, the maximum size is 640*480):
• videoControl.getSnapshot(null); // default PNG, 192x192
• videoControl.getSnapshot("encoding=jpeg"); // JPEG, 192x192
• videoControl.getSnapshot("width=80&height=60"); // default PNG, change to minimum size 160 x120
• videoControl.getSnapshot("encoding=jpeg&width=176&height=144"); // JPEG, 176 x144
GUIControl
GUIControl extends control and is defined for controls that provide GUI functionalities.
USE_GUI_PRIMITIVE defines a mode on how the GUI is displayed. initializes
the mode on how the GUI is displayed.
USE_GUI_PRIMITIVE is specified for initDisplayMode, a GUI primitive
When will be returned. This object is where the GUI of this control will be displayed. It can be used in conjunction with other GUI objects and conforms to the GUI behaviors specified.
48
Page 49
13 JSR 135 Mobile Media API
VolumeControl
VolumeControl is an interface for manipu lating the audio volume of a Player. The JSR 135 Mobile Media API will implement public int erface VolumeControl.
The following describes the different volume settings fo und within VolumeControl:
Volume Settings - allows the output volume to be specified using an integer value that varies between 0 and 100.
Specifying Volume in the Level Scale - specifies v olume in a linear scale. It ranges from 0 – 100 where 0 represents silence and 100 represents the highest volume available.
Mute – setting mute on or off does not change the vol ume level returned by the getLevel. If mute is on, no audio signal is produced by the Player. If mute is off, an audio signal is produced and the volume is restored.
The following is a list of available methods with regar ds to VoumeControl:
-getLevel: Get the current volume setting.
-isMuted: Get the mute state of the signal associated with this VolumeContr ol.
-setLevel (int level): Set the volume using a linear point scale with values
between 0 and 100.
-setMute (Boolean mute): Mute or unmute the Player associated with this VolumeControl.
StopTimeControl
StopTimeControl allows a specific preset sleep timer for a player. The JSR 135 Mobile Media API will implement public interface StopTimeControl.
The following is a list of available methods with regards to StopTimeControl:
-getStopTime: Gets the last value successfully by setStopTime.
-setStopTime (long stopTime): Sets the media time at which you want the
Player to stop.
Manager Class
Manager Class is the access point for obtaining system dependant resources such as players for multimedia processing. A Player is an object used to control and render media that is specific to the content type of the data. Manager provides access to an implementation specific mechanism for constructing P layers. For convenience, Manager also provides a simplified method to generate simple tones. Primarily, the Multimedia API will provide a way to check available/su pported content types.
49
Page 50
Audio Media
The following multimedia file formats are supported:
File Type CODEC
WAV PCM SP MIDI General MIDI MIDI Type 1 General MIDI MP3 MPEG-1 layer III AMR AMR MIDI Type 0 General MIDI
The following is a list of audio MIME types support ed:
Category Description MIME Type
Audio/Video/Image
Wav AMR Audio MP3 Audio MIDI Audio SP MIDI Audio Tone Sequences
Audio/x-wav Audio/amr Audio/mpeg Audio/midi Audio/sp-midi Audio/x-tone-sequence
Audio MP4 Video 3GP Video
Video/mp4 Video/3gpp
Refer to the table below for multimedia feature/class sup port for JSR 135:
Feature/Class Implementation
Media package found Supported Media control package Supported Media Protocol package Supported Control interface in javax.microedition.medi a Supported All methods for the Controllable interface in
javax.microedition.media.control All fields, methods, and inherited methods for the Player interface in
javax.microedition.media
50
Supported
Supported
Page 51
13 JSR 135 Mobile Media API
All fields and methods for the PlayerListener interface in
Supported
javax.microedition.media PlayerListener OEM event types for the PlayerListener interface Standard types only All fields, methods, and inherited methods for the Manager Class in
Supported
javax.microedition.media TONE_DEVICE_LOCATOR support in the Manager class of
Supported
javax.microedition.media TONE_DEVICE_LOCATOR content type will be audio/x-tone-seq Supported TONE_DEVICE_LOCATOR media locator will be device://tone Supported All constructors and inherited methods in
Supported
javax.microedition.medi.MediaException All fields and methods in the StopTimeControl int erface in
Supported
javax.microedition.media.control All fields and methods in the ToneControl interface in
Supported
javax.microedition.media.control All methods in the VolumeControl interface in
Supported
javax.microedition.media.control Max volume of a MIDlet will not exceed the maximum speaker setting
Supported
on the handset All fields and methods in the VideoControl interface in
javax.microedition.media.control All fields and methods in the GUIControl interface in
javax.microedition.media.control Multiple SourceStreams for a DataSource 2
Note: If two wave plays have the same frequency, they can mix. See Appendix A – mix audio table.
Player number limitation <=4 and MIDI size limitation is 150K
MP3, AMR, MP4, and 3GP stream size has the limitation
Supported
Supported
51
Page 52
JSR 120 – Wireless Messaging
API
Wireless Messaging API (WMA)
14
Motorola has implemented certain features that are defined in the Wireless Messaging API (WMA) 1.0. The complete specification document is defined in JSR 120.
The JSR 120 specification states that developers can be provided access to send (MO – mobile originated) and receive (MT – mob ile terminated) SMS (Short Message Service) on the target device.
A simple example of the WMA is the ability of two J2ME applications using SMS to communicate game moves running on the handsets. This can take the form of chess moves being passed between two players via the WMA.
Motorola in this implementation of the specif ication supports the following features.
Creating a SMS Sending a SMS Receiving a SMS Viewing a SMS Listening to a SMS
SMS Client Mode and Server Mode Connection
The Wireless Messaging API is based on the Generic C on nection Framework (GCF), which is defined in the CLDC specification 1.0. The use of the “Connection” framework, in Motorola's case is “
52
MessageConnection”.
Page 53
14 JSR 120 – Wireless Messaging API
The MessageConnection can be opened in either server or cl ient mode. A server connection is opened by providing a URL that specifies an identifier (port number) for an application on the local device for incoming messages.
(MessageConnection)Connector.open("sms://:6000"); Messages received with this identifier will then be delivered to the application by this
connection. A server mode connection can be used for both sending and receiving messages. A client mode connection is opened by providing a URL which points to another device. A client mode connection can only be used for sending messages.
(MessageConnection)Connector.open("sms://+441234567890 :6000");
SMS Port Numbers
When a port number is present in the address, the TP-User-Data of th e SMS will contain a User-Data-Header with the application port addressing scheme information element. When the recipient address does not contain a port number, the TP-User-Data will not contain the application port addressing header. The J2ME MIDlet cannot receive this kind of message, but the SMS will be handled in the usual manner for a standard SMS to the device.
When a message identifying a port number is sent from a server type
MessageConnection, the originating port number in the messag e is set to the port
number of the the message that will be received by this
However, when a client type with a port number, the originating port number is set to an implementation specific value and any possible messages received to this port number are not delivered to the
MessageConnection. Please refer to the section A.4.0 and A.6.0 of the JSR 12 0.
When a MIDlet in server mode requests a port number (identifier) to use and it is the first MIDlet to request this identifier it will be allocated. If other applications apply for the same identifier then an
MessageConnection is made. If a system application is using this identifier, the
MIDlet will not be allocated the identifier. The port numbers allowed for this request are restricted to SMS messages. In addition, a MIDlet is not allowed to send mess ages to certain restricted ports a
JSR 120 Section A.6.0 Restricted Ports: 2805, 2923, 2948, 2949, 5502, 5503, 5508, 5511, 5512, 920 0, 92 01, 9202, 9203, 9207, 49996, 49999.
If you intend to use SMSC numbers then please revie w A.3.0 in the JSR 120 specification. The use of an SMSC would be used if th e MIDlet had to determine what recipient number to use.
MessageConnection. This allows the recipient to send a response to
IOException will be thrown when an attempt to open
MessageConnection.
MessageConnection is used for sending a message
SecurityException will be thrown if this is attempted.
53
Page 54
SMS Message Types
The types of messages that can be sent are TEXT or BINARY, the method of encoding the messages are defined in GSM 03.38 standard (Part 4 SMS Data Coding Scheme). Refer to section A.5.0 of JSR 120 for more information.
SMS Message Structure
The message structure of SMS will comply with GSM 03.40 v7.4.0 Digital cellular telecommunications system (Phase 2+); Technical realization of the Short Message Service (SMS) ETSI 2000.
Motorola’s implementation uses the concatenation feature specified in sections 9.2.3.24.1 and 9.2.3.24.8 of the GSM 03.40 standard for mess ages that the Java application sends that are too long to fit in a single SMS protocol message.
This implementation automatically concatenates the received SMS protocol messages and passes the fully reassembled message to the application via the API. The implementation will support at least three SMS messages to be received and concatenated together. Also, for sending, support for a minimum of three messages is supported. Motorola advises that developers should not send messages that will take up more than three SMS protocol messages unless the recipient’s device is known to support more.
SMS Notification
Examples of SMS interaction with a MIDlet would be the following:
A MIDlet will handle an incoming SMS message if the MIDlet is registered to
receive messages on the port (identifier) and is running.
When a MIDlet is paused and is registered to receive messages on the port
number of the incoming message, then the user will be queried to launch the MIDlet.
If the MIDlet is not running and the Java Virtual Machine is not initialized, then a
Push Registry will be used to initialize the Virtual Machine and launch the J2ME MIDlet. This only applies to trusted, signed MIDlets.
If a message is received and the untrusted unsigned application and the KVM
are not running then the message will be discarded.
The following is a list of Messaging features/ classes supported in the device.
54
Page 55
14 JSR 120 – Wireless Messaging API
Feature/Class Implementation
JSR-120 API. Specifically, APIs defined in the
Supported javax.wireless.messaging package will be implemented w ith regards to the GSM SMS Adaptor
All fields, methods, and inherited methods for the C onnector Class in
Supported the javax.microedition.io package
All methods for the BinaryMessage interface in the
Supported javax.wireless.messaging package
All methods for the Message interface in the javax.wire less.messaging
Supported package
All fields, methods, and inherited methods for the MessageConnection
Supported interface in the javax.wireless.messaging package
Number of MessageConnection instanc es in the
5 javax.wireless.messaging package
All methods for the MessageListener interface in the
Supported javax.wireless.messaging package
All methods and inherited methods for the TextMessage inte rface in
Supported the javax.wireless.messaging package
Number of concatenated messages. 40 messages in inbox, each can
be concatenated from 10 parts at
max.
No limitation on outbox
(immediately transmitted)
The following are code samples to show implementation of the JSR 120 Wireless Messaging API:
Creation of client connection and for calling of method ‘numberOfSegments’ for Binary message:
BinaryMessage binMsg; MessageConnection connClient; int MsgLength = 140;
/* Create connection for client mode */ connClient = (MessageConnection) Connector.open("sms://"
+ outAddr);
/* Create BinaryMessage for client mode */ binMsg =
(BinaryMessage)connClient.newMessage(MessageConnection.BINAR Y_MESSAGE);
/* Create BINARY of 'size' bytes for BinaryMsg */
55
Page 56
public byte[] createBinary(int size) { int nextByte = 0; byte[] newBin = new byte[size];
for (int i = 0; i < size; i++) { nextByte = (rand.nextInt()); newBin[i] = (byte)nextByte; if ((size > 4) && (i == size / 2)) { newBin[i-1] = 0x1b; newBin[i] = 0x7f; } } return newBin; }
byte[] newBin = createBinary(msgLength); binMsg.setPayloadData(newBin);
int num = connClient.numberOfSegments(binMsg);
Creation of server connection:
MessageConnection messageConnection = (MessageConnection)Connector.open("sms://:9532");
Creation of client connection with port number:
MessageConnection messageConnection = (MessageConnection)Connector.open("sms://+18473297274:9532")
;
Creation of client connection without port number:
MessageConnection messageConnection = (MessageConnection)Connector.open("sms://+18473297274");
Closing of connection:
MessageConnection messageConnection.close();
Creation of SMS message:
Message textMessage = messageConnection.newMessage(MessageConnection.TEXT_MESSAGE) ;
Setting of payload text for text message:
((TextMessage)message).setPayloadText("Text Message");
Getting of payload text of received text message:
receivedText = ((TextMessage)receivedMessage).getPayloadText();
56
Page 57
14 JSR 120 – Wireless Messaging API
Getting of payload data of received binary message:
BinaryMessage binMsg; byte[] payloadData = binMsg.getPayloadData();
Setting of address with port number:
message.setAddress("sms://+18473297274:9532");
Setting of address without port number:
message.setAddress("sms://+18473297274");
Sending of message:
messageConnection.send(message);
Receiving of message:
Message receivedMessage = messageConnection.receive();
Getting of address:
String address = ((TextMessage)message).getAddress();
Getting of timestamp for the message:
Message message; System.out.println("Timestamp: " +
message.getTimestamp().getTime());
Creation of client connection, creation of binary message, setting of payload for binary message and calling of method ‘numberOfSegments(Message)’ for Binary message:
BinaryMessage binMsg; MessageConnection connClient; int MsgLength = 140;
/* Create connection for client mode */ connClient = (MessageConnection) Connector.open("sms://"
+ outAddr);
/* Create BinaryMessage for client mode */ binMsg =
(BinaryMessage)connClient.newMessage(MessageConnection.BINAR Y_MESSAGE);
/* Create BINARY of 'size' bytes for BinaryMsg */ public byte[] createBinary(int size) { int nextByte = 0;
57
Page 58
byte[] newBin = new byte[size];
for (int i = 0; i < size; i++) { nextByte = (rand.nextInt()); newBin[i] = (byte)nextByte; if ((size > 4) && (i == size / 2)) { newBin[i-1] = 0x1b; newBin[i] = 0x7f; } } return newBin; }
byte[] newBin = createBinary(msgLength); binMsg.setPayloadData(newBin);
int num = connClient.numberOfSegments(binMsg);
Setting of MessageListener and receiving of notifications about incoming messages:
public class JSR120Sample1 extends MIDlet implements CommandListener {
… JSR120Sample1Listener listener = new
JSR120Sample1Listener(); … // open connection messageConnection =
(MessageConnection)Connector.open("sms://:9532"); … // create message to send … listener.run(); … // set payload for the message to send … // set address for the message to send messageToSend.setAddress("sms://+18473297274:9532"); … // send message (via invocation of ‘send’ method) … // set address for the message to receive receivedMessage.setAddress("sms://:9532"); … // receive message (via invocation of ‘receive’ method) …
class JSR120Sample1Listener implements MessageListener,
58
Page 59
14 JSR 120 – Wireless Messaging API
Runnable { private int messages = 0;
public void notifyIncomingMessage(MessageConnection connection) {
System.out.println("Notification about incoming message arrived");
messages++; }
public void run() { try { messageConnection.setMessageListener(listener); } catch (IOException e) { result = FAIL; System.out.println("FAILED: exception while setting
listener: " + e.toString()); } } }
59
Page 60
Phonebook Access API
Phonebook Access API
Using the Phonebook Access API, an application will be able to locate and update contact information on the handset. This contact info rmation includes phone numbers, email addresses, and any other directory information related to individuals, groups, or organizations. The database used to store phonebook information wil l be unique an d integrated for native phonebook, SIM card, and other applications using Phonebook API.
15
The primary goal of the Phonebook Access API is to be simple and thin to fit in resource­limited devices like the Motorola E680 handset. This API will specify a base storage class for all types of contacts items presented in the vCard specification (RFC2426 –vCard MIME Directory Profile – vCard 3.0 Specification). In addition, schema strings used in querying and storing contact information are those specified in the RFC2426 specification.
The Phonebook Access API will perform the following functions:
Allow multiple phone numbers and em ail addresses for each contact
Store new entries
Retrieve entries
Edit existing entries
Delete entries
Check memory status
Order and sort contact parameters
Support standard schema strings
Phonebook Access API Permissions
Prior to a MIDlet accessing the Phonebook API for all Pho nebook operations, the implementation will check the Phonebook permissions granted to the application.
60
Page 61
15 Phonebook Access API
In the Motorola E680, Phonebook API permissions have been added to the MIDP 2.0 security framework “com.motorola.phon ebook.” The behavior is up to the domain setting where the MIDlet falls in. For an untrusted MIDlet, the permission for the API is “Oneshot”.
The following are code samples to show implementation of the Phonebook API:
Sample of code to create object of PhoneBookRecord class:
PhoneBookRecord phbkRecEmpty = new PhoneBookRecord();
String name = “Name”; String telNo = “9999999”; int type = PhoneBookRecord.MAIN;
PhoneBookRecord phbkRec = new PhoneBookRecord(name, telNo, type);
Sample of code for calling of ‘add()’ method:
int index = phbkRec.add();
Sample of code for calling of ‘update(int index)’ method:
phbkRec.type = PhoneBookRecord.HOME; int newIndex = phbkRec.update(index);
Sample of code for calling of ‘delete(int index)’ method:
PhoneBookRecord.delete(index);
Sample of code for calling of ‘deleteAll()’ method:
PhoneBookRecord.deleteAll();
Sample of code for calling of ‘getRecord(int index)’ method:
phbkRec.getRecord(index);
Sample of code for calling of ‘findRecordByTelNo(String tel)’ method:
index = phbkRec.findRecordByTelNo(telNo);
Sample of code for calling of ‘findRecordByName(char firstChar)’ method:
index = PhoneBookRecord.findRecordByName('N');
Sample of code for calling of ‘findRecordByEmail(String email)’ method:
String email = “email@mail.com”; index = phbkRec.findRecordByEmail(email);
Sample of code for calling of ‘getNumberRecords(int device)’ method:
61
Page 62
// get total number of records int numberRecsInPhone = PhoneBookRecord.getNumberRecords(PhoneBookRecord.PHONE_MEMOR
Y); int numberRecsInSim =
PhoneBookRecord.getNumberRecords(PhoneBookRecord .SIM_MEMORY);
int numberRecsAll = PhoneBookRecord.getNumberRecords(PhoneBookRecord.ALL_MEMORY) ;
Sample of code for calling of ‘getAvailableRecords(int device)’ method:
// get number of available records int numberRecsAvalPhone = PhoneBookRecord.getAvailableRecords(PhoneBookRecord.PHONE_ME
MORY); int numberRecsAvalSim =
PhoneBookRecord.getAvailableRecords(PhoneBookRecord.SIM_MEMO RY);
int numberRecsAvalAll = PhoneBookRecord.getAvailableRecords(PhoneBookRecord.ALL_MEMO RY);
Sample of code for calling of ‘getUsedRecords(int device)’ method:
// get number of used records int numberRecsUsedPhone = PhoneBookRecord.getUsedRecords(PhoneBookRecord.PHONE_MEMORY)
; int numberRecsUsedSim = PhoneBookRecord.getUsedRecords(PhoneBookRecord.SIM_MEMORY); int numberRecsUsedAll = PhoneBookRecord.getUsedRecords(PhoneBookRecord.ALL_MEMORY);
Sample of code for calling of ‘getNumberRecordsByName(String name)’ method:
int num = PhoneBookRecord.getNumberRecordsByName(name);
Sample of code for calling of ‘getMaxNameLength(int device)’ method:
int maxNameLengthPhone = PhoneBookRecord.getMaxNameLength(PhoneBookRecord.PHONE_MEMOR
Y); int maxNameLengthSim = PhoneBookRecord.getMaxNameLength(PhoneBookRecord.SIM_MEMORY)
; int maxNameLengthAll = PhoneBookRecord.getMaxNameLength(PhoneBookRecord.ALL_MEMORY)
;
62
Page 63
15 Phonebook Access API
Sample of code for calling of ‘getMaxTelNoLength (int device)’ method:
int maxTelNoLengthPhone = PhoneBookRecord.getMaxTelNoLength(PhoneBookRecord.PHONE_MEMO
RY); int maxTelNoLengthSim = PhoneBookRecord.getMaxTelNoLength(PhoneBookRecord.SIM_MEMORY
); int maxTelNoLengthAll = PhoneBookRecord.getMaxTelNoLength(PhoneBookRecord.ALL_MEMORY
);
Sample of code for calling of ‘getMaxEmailLength ()’ method:
int maxEmailLength = PhoneBookRecord.getMaxEmailLength();
Sample of code for calling of ‘getIndexBySpeedNo(int speedNo)’ method:
int speedNo = 1; index = PhoneBookRecord.getIndexBySpeedNo(speedNo);
Sample of code for calling of ‘getNewSpeedNo(int num, int device)’ method:
int speedNo = 1; int speedNo_phone = PhoneBookRecord.getNewSpeedNo(speedNo, PhoneBookRecord.PHONE_MEMORY); int speedNo_sim = PhoneBookRecord.getNewSpeedNo(speedNo, PhoneBookRecord.PHONE_MEMORY); int speedNo_all = PhoneBookRecord.getNewSpeedNo(speedNo, PhoneBookRecord.PHONE_MEMORY);
Sample of code for calling of ‘getDeviceType(int speedNo)’ method:
int speedNo = 1; int type = PhoneBookRecord.getDeviceType(speedNo);
Sample of code for calling of ‘setPrimary(int index)’ method:
int index = 1; PhoneBookRecord.setPrimary(index);
Sample of code for calling of ‘resetPrimary(int index)’ method:
int index = 1; PhoneBookRecord.resetPrimary(index);
Sample of code for calling of ‘isPrimary(int speedNo)’ method:
63
Page 64
int speedNo = 1; boolean res = PhoneBookRecord.isPrimary(speedNo);
Sample of code for calling of ‘fromVFormat(InputStream in, int device)’ method:
buffer = new String("BEGIN:VCARD\r\nN:;" + new String(name) +
"\r\nTEL;TYPE=WORK:1\r\nEND:VCARD\r\n"); int num = PhoneBookRecord.fromVFormat((InputStream)(new
ByteArrayInputStream(buffer.getBytes())), PhoneBookRecord.PHONE_MEMORY);
Sample of code for calling of ‘toVFormat(OutputStream out, int index, int outFormat, int sortOrder)’ method:
int index = 1; ByteArrayOutputStream outStream = new
ByteArrayOutputStream(); PhoneBookRecord.toVFormat(outStream, index,
PhoneBookRecord.VCARD_3_0, PhoneBookRecord.SORT_BY_NAME);
System.out.println("***** Contents of the output stream: *****");
System.out.print(new String(outStream.toByteArray()));
64
Page 65
16 File System Access API
The File System Access API for the Motorola E680 handset is intended to allow J2ME applications access to files that are stored on the handsets. Internal file systems can be accessed via the File System Access API. Please note that the maximum file name length supported by Motorola is 36 characters.
16
File System Access API
File Connection Methods
The File System Access API will provide file connections provided there is underlying hardware and OS support on the handset. If file connection s are not supported, attempts to open a file connection through Connector.open() will throw
javax.micdoedition.io.ConnectionNotFoundException.
Establishing a Connection
To establish a connection, the format of the Connector.open() input string used to access a File Connection will follow the format described in the file URL format as part of IETF RFCs 1738 and 2386. These IETF RFCs dictate that a file URL will take the following form:
file://<host>/<path>
In the format shown above, the following def initions will be used:
<host> - fully qualified domain name of the system on whic h the <path> is accessible
<path> - a hierarchical directory path of the form
<root>/<directory>/<directory>/…/<name>/
For successful implementation, <host> will be the empty string. This is read as the machine from which the URL is being interprete d. This type of file connection only supports file access to files contained on a device or on e of its attached memory cards. This type of file connections does not support access to files on a remote file system. Attempts to open a remote file system connection with Connector.open() will throw a javax.microedition.io.IOException.
65
Page 66
The file connection defines the first directory as the root, which corresponds to a logical mount point for a particular storage unit or memory. The r oo t of a file system supporting only one card reader will return the conte nts of the card directly. If more than one card reader is supported, or the device supports a file system in RAM, the root strings are device specific. Since roots are part of the path string as a directory, they have a trailing ”/”. The valid <root> values for a device can be retrieved by querying open a root connection to the root URL of the device (file:///) and getting the results of the list() method. A single connection object can only ref erence a single file or directory. A connection object cannot be changed dynamically to refer to a different file or directory than originally connected to. A completely separate connection will be established through the Connector.open() method to reference a different file or directory.
Connection Behavior
The File System Access API is different from other Generic Connection Framework APIs because a connection object can successfully return from the Connector.open() method without referencing an existing fil e or directory. This method is used to allow the creation of new files and directories on a file system. Al ways check for the file’s or directory’s existence after a connection is established to determine if the file or directory actually exists.
Security
Similarly, files or directories can be deleted using the delete() method. The connection should immediately be closed after a deletion to prevent exceptions from accessing a connection to a non-existent file or directory.
To prevent unauthorized manipulation of data, access to fil e co nnections is restricted. The security model applied to the file connection is defined by the implementing profile. This security model will be applied on the invocat ion of the Connector.open() method with a valid file connection string. Should the application not be granted access to the file system through the profile authorization scheme, a java.lang.SecurityException will be thrown. The security model will be applied during execution, specifically when the methods openInputStream(),
openDataInputStream(), openOutputStream(), openDataOutputStream(), and other file system operation methods are
invoked. File access through the File System Access API is restricted in order to protect the user’s
files and data from malicious and unintentional access. A file connection will not be able to access RMS databases, files that are private to another application, system conf iguration files, and device and OS specific files.
Please note that only signed applications residing in manufacturer domain will have access to the File System.
The following are code samples to show implementation of the File System API:
66
Page 67
16 File System Access API
Sample for FileConnection Interface
import javax.microedition.io.*; import com.motorola.io.*;
/* * Get a root of file system */ java.lang.String root = FileSystemRegistry.listRoots()[0];
/* * Create a FileConnection object pointing to root directory */ FileConnection fc = null; try { fc = (FileConnection) Connector.open("file://"+root); } catch (IOException ioe) { }catch (Security Exception se) {} … }
/* * Get available, used and total size of file system */
long availableSize = fc.availablesize();
long usedSize = fc.usedSize();
long totalSize = fc.totalSize();
/* * Determine the size in bytes that is used by a directory */
try { long rootSize = fc.directorySize(false); } catch (IOException ioe) { … }
/* * Get list of files in root */
java.lang.String list[] = fc.list();
/* * Check if first item in the list is directory */
try { fc = (FileConnection) Connector.open("file://" +list[0]); } catch (IOException ioe) {
67
Page 68
}
if (fc.isDirectory()) { // first item is directory } else { //first item is file }
/* * Create a FileConnection object pointing to file */ FileConnection fc = null; try { fc = (FileConnection) Connector.open("file://"+root+"testfile.txt"); } catch (IOException ioe) { … }
/* * If file does not exists, create it */
if (! fc.exists() ) { try {
fc.create(); } catch (SecurityException se) { ... } }
/* * Open stream for writing data */
DataOutputStream dataOutputStream; try { dataOutputStream = fc.openDataOutputStream(); //write data dataOutputStream.close(); } catch (IOException ioe) { … }
/* * Open stream for reading data */
DataInputStream dataInputStream; try { dataInputStream = fc.openDataInputStream(); // read data dataInputStream.close(); } catch (IOException ioe) {
68
Page 69
16 File System Access API
}
/* * Get file size */
try { long fileSize = fc.fileSize(); } catch (IOException ioe) { … }
/* * Set file's attributes */
try { boolean isSetToWrite = fc.setWriteable(true); } catch (IOException ioe) { … }
try { boolean isSetToRead = fc.setReadable(true); } catch (IOException ioe) { … }
try { boolean isSetHidden =fc.setHidden(true); } catch (IOException ioe) { … }
/* * Get file's attributes */
try { boolean isWriteable = fc.canWrite(); } catch (IOException ioe) { … } try { boolean isReadable =fc.canRead(); } catch (IOException ioe) { … } try { boolean isHidden =fc.isHidden(); } catch (IOException ioe) { … }
/* * Rename file
69
Page 70
*/
boolean isRenamed = fc.rename("file://"+root+"newfile.txt");
/* * Get path and URL of file */
java.lang.String filePath = fc.getPath(); java.lang.String fileURL = fc.getURL();
/* * Get time of last modification */
long lastModifiedTime = fc.lastModified();
/* * Delete file
*/
boolean isDeleted = fc.delete();
/* * Close File Connection */
try { fc.close(); } catch (IOException ioe) { … }
70
FileSystemRegistry Class
/* * Get list of roots */
java.lang.String listOfRoot = FileSystemRegistry.listRoots();
/* * To add/remove file system listener it is necessary to create an instance of FileSystemListener interface: */
Listener newListener = new Listener();
/* * add listener */ FileSystemRegistry.addFileSystemListener(listener);
Page 71
16 File System Access API
/* * remove listener */
FileSystemRegistry.removeFileSystemListener(listener);
/* Implementation of FileSystemListener interface * * Method rootAdded(FileSystemEvent e) is invoked when a root is added to the filesystem * Method rootRemoved(FileSystemEvent e) is invoked when a root is removed from the filesystem * To get information about just added/removed roots, the following methods of FileSystemEvent should be used: * - to get event ID: e.getID(); * - to get root name: e.getRootName(); */ class Listener implements FileSystemListener {
Listener() { } public void rootAdded(FileSystemEvent e) { //implementation of the method } public void rootRemoved(FileSystemEvent e) { //implementation of the method }
}
71
Page 72
17
Telephony API
The Telephony API allows a MIDlet to make a voice call, however, the user needs to confirm the action before any voice call is ma de. The reason for the confirmation is to provide a measure of security from rogue appli cations overtaking the handset.
Unlike standard TAPI, the wireless Telephony API provide simple function and simple even listener: startCall (), send ExtNo(), and endCall (), DialerListener.
The tables below describe the Interface and Class Summary:
Interface Summary
DialerListener The DialerListener interface provides a mechanism for the application to be
notified of phone call event.
Class Summary
Dialer The Dialer class defines the basic functionality for start and end phone
call.
DialerEvent The DialerEvent class defines phone call events.
Dialer Class
The dialer Class can be used to start and end a phone call and user listener to receive an event. The applications use a Dialer to make a phone call and use DialerListener to receive event.
Class DialerEvent
The DialerEvent class defines phone call events. The ta ble below describes the Field Summary:
Summary
static byte PHONE_VOICECALL_CONNECT
Phone call was connected event
72
Page 73
17 Telephony API
static byte PHONE_VOICECALL_DISCONNECT
Phone call was disconnected event
static byte PHONE_VOICECALL_DTMF_FAILURE
Send extension number error event
static byte PHONE_VOICECALL_FAILURE
start phone call error event
static byte PHONE_VOICECALL_HOLD
Current java phone call was held by native phone event
static byte PHONE_VOICECALL_INIT
Phone start dial-up event
static byte PHONE_VOICECALL_TIMEOUT
Phone process timeout event
static byte PHONE_VOICECALL_UNHOLD
Current java phone call was unheld event
The table below describes the Constructor Summary:
Constructor Summary
DialerEvent()
The following methods are inherited from class java.lang.Object:
equals
getClass
hashCode
notify
notifyAll
toString
wait
The following table describes the Field Details:
Field
PHONE_VOICECALL_INIT
PHONE_VOICECALL_FAILURE
PHONE_VOICECALL_CONNECT
PHONE_VOICECALL_DISCONNECT
Detail Definition public static final byte
PHONE_VOICECALL_INIT
public static final byte
PHONE_VOICECALL_FAILURE
Phone start dial-up event
Start phone call error event
public static final byte PHONE_VOICECALL_CONNECT
Phone call was connected event
public static final byte PHONE_VOICECALL_DISCONNECT
Phone call was
73
Page 74
PHONE_VOICECALL_TIMEOUT
public static final byte PHONE_VOICECALL_TIMEOUT
PHONE_VOICECALL_HOLD
public static final byte PHONE_VOICECALL_HOLD
PHONE_VOICECALL_UNHOLD
public static final byte PHONE_VOICECALL_UNHOLD
PHONE_VOICECALL_DTMF_FAILURE public static final byte
PHONE_VOICECALL_DTMF_FAILURE
disconnect ed event
Phone process timeout event
Current java phone call was held by native phone event
Current java phone call was unheld event
Send extension number error event
Class Dialer
The Dialer class defines the basic functionali t y for starting and ending a phone call. The table below describes the Method Summary:
Method Summary
void
static Dialer
void void void void
endCall() end or cancel a phone call
getDefaultDialer()
sendExtNo(String extNumber)
send extension number. setDialerListener(DialerListener listener)
Registers a DialerListener object. startCall(String telenumber) start a phone call using given telephone number. startCall(String teleNumber, String extNo) start a phone call using given telephone number and extension number.
The following methods are inherited from java.lang.object:
74
Page 75
17 Telephony API
equals
getClass
hashCode
notify
notifyAll
toString
wait
getDefaultDialer
public static Dialer getDefaultDialer()
Get a Dialer instance.
setDialerListener
startCall
public void setDialerListener(DialerListener listener) Registers a The platform will notify this listener object when a phone ev ent has been received to this
Dialer object.
There can be at most one listener object registered for a point in time. Setting a new listener will implicitly de-register the possibly previously set listener.
Passing Parameters:
listener - DialerListener object to be registered. If null, the possibly currently
registered listener will be de-register ed and will not receive phone call event.
public void startCall(String telenumber) throws start a phone call using given telephone number.
DialerListener object.
Dialer object at any given
null as the parameter de-registers the currently registered listener, if any.
IOException
Parameters:
telenumber - the telephone number to be call. extNo - the extension number to be send.
Throws:
75
Page 76
startCall
IOException NullPointerException - if the parameter is null SecurityException - if the application does not have permission to start the call
- if the call could not be created or because of network failure
public void startCall(String teleNumber,
throws
String extNo)
IOException
start a phone call using given telephone number and extension number. Parameters:
telenumber - the telephone number to be call. extNo - the extension number to be send.
Throws:
IOException - if the call could not be created or because of network failure NullPointerException - if the parameter is null
sendExtNo
endCall
SecurityException - if the application does not have permission to start the call
public void sendExtNo(String extNumber) throws
IOException
send extension number. Parameters:
sendExtNo - the extension number to be send.
Throws:
IOException - if the extension could not be send or because of network failure
public void endCall() throws end or cancel a phone call
76
IOException
Page 77
17 Telephony API
Throws:
IOException - if the call could not be end or cancel.
Interface DialerListener
public interface DialerListener The
DialerListener interface provides a mechanism for the application to be notified
of phone call event. When an event arrives, the
notifyDialerEvent() method is called
The listener mechanism allows applications to receive TAPI voice call event without needing to have a listener thread
If multiple event arrive very closely together in time, the imp lementation has calling this listener in serial.
Sample DialerListener Implementation
Dialer listener program
import java.io.IOException; import javax.microedition.midlet.*; import javax.microedition.io.*; import com.motorola.*;
public class Example extends MIDlet implements DialerListener { Dialer dialer;
// Initial tests setup and execution.
public void startApp() { try { dialer = Dialer.getDefaultDialer();
// Register a listener for inbound TAPI voice call events. dialer.setDialerListener(this); dialer.startCall("01065642288");
} catch (IOException e) { // Handle startup errors } }
Asynchronous callback for receive phone call event
public void notifyDialerEvent(Dialer dialer, byte event) { switch (event) {
77
Page 78
case DialerEvent.PHONE_VOICECALL_INIT: // your process break; case DialerEvent.PHONE_VOICECALL_FAILURE: // your process break; case DialerEvent.PHONE_VOICECALL_CONNECT: // your process break; case DialerEvent.PHONE_VOICECALL_DISCONNECT: // your process break; case DialerEvent.PHONE_VOICECALL_TIMEOUT: // your process break; case DialerEvent.PHONE_VOICECALL_HOLD: // your process break; case DialerEvent.PHONE_VOICECALL_UNHOLD: // your process break; case DialerEvent.PHONE_VOICECALL_DTMF_FAILURE: // your process break; } }
// Required MIDlet method - release the connection and // signal the reader thread to terminate.
public void pauseApp() { try { dialer.endCall(); } catch (IOException e) { // Handle errors } }
// Required MIDlet method - shutdown. // @param unconditional forced shutdown flag
public void destroyApp(boolean unconditional) { try { dialer.setDialerListener(null); dialer.endCall(); } catch (IOException e) { // Handle shutdown errors. } } }
78
Page 79
17 Telephony API
notifyDialerEvent
public void notifyDialerEvent(Dialer dialer, byte event) Called by the platform when a phone call event was received by a
the application has registered this listener object. This method is called once for each TAPI voice call event to the NOTE: The implementation of this method MUST return quickly and MUST NOT perform
any extensive operations. The application SHOULD NOT receive and handle the message during this method call. Instead, it should act only as a trigger to start the activity in the application's own thread.
Parameters:
dialer - the Dialer where the TAPI voice call event has arrived event - the TAPI voice call event type.
Class Hierarchy
class java.lang.Object
Dialer object where
Dialer object.
o class com.motorola.phone.Dialer o class com.motorola.phone.DialerEvent
Interface Hierarchy
interface com.motorola.phone.DialerListener
79
Page 80
Overview
Digital Rights Management (DRM) is an approach to protect content against illegal use by packaging the content into an encrypted format with rules dictating its use. With a valid rights object for the specific content file, a DRM application can decrypt the content for playback. DRM is almost invisible to the user, except for those cases where a valid rights object has not arrived. The instances may occur because of the following:
18
DRM Protection in Java
Elapsed number of times the content to be executed/played
Elapsed validity for the license
Content received through separate delivery
A DRM mechanism has been implemented to prevent MIDlets from distributing decrypted DRM content using any packet data network connection, and from executing MIDlets who have no valid rights object files at the time.
For Java in E680, we support the downloading, i nstallation, execution and de-installation of a DRM-protected Java application.
Rights Enforcement - MIDlets Accessing DRM protected content
A MIDlet can access files for which it has the permissions in the device. For those DRM­protected files, the MIDlet can only get the encrypted contents.
Acquiring License
If the user does not have a valid rights object for an installed MIDlet, the system will stop invoking the MIDlet and prompt the user with a dialog to acquire additional rights.
80
Page 81
19 CLDC 1.1
This chapter covers the additional functionality of CLDC 1.1 as it pertains to the Motorola E680. This chapter assumes that the developer is aware of CLDC 1.0 and its uses on Motorola handsets. CLDC 1.1 is fully backwards compatible with CLDC 1.0.
CLDC 1.1 Compliance
19
CLDC 1.1
The general goal of CLDC 1.1 is to make CLDC 1.0 compliant with the Java Language and Virtual Machine Specifications by reintroducing features such as floating point support and improved error handling capabilities.
The following attributes will be supported for CLDC 1.1 compliance on the Motorola E680:
Floating point:
Weak reference
Classes Calander, Date and Time Zone to be most J2SE compliant
Thread objects to be compliant with J2SE. This requires the addition of
Thread.getName and a few new constructors as listed in the table below.
Improved Error handling
The method System.getProperty with key “microedit ion.configuration” returns
“CLDL-1.1”
The following table lists the additional classes, fields, and methods that will be implemented for CLDC 1.1 compliance:
Classes Additional Fields/Methods Comments
System Classes Java.lang.Thread Thread (Runnable target, String
name)
Allocates a new Thread object with the given target and name
Thread (String name) Allocates a new
81
Thread object with the given name
Page 82
String getName () Returns this thread’s
name Void interrupt () Interrupts this thread Java.lan.String Boolean equalIgnoreCase
(String anotherString)
Compares this String
to another String,
ignoring case
considerations String intern () Returns a cnonical
representation for the
string object Static String valueOf (float f) Returns the string
representation of the
float argument Static String valueOf (double d) Returns the string
representation of the
double argument Data Type Classes Java.lang.Float New Class; Refer
CLDC Specification
1.1 for more details
Java.lang.Double New Class; Refer
CLDC Specification
1.1 for more details
Calendar and time classes
Java.util.Caleneder Protected int [] fields The field values for
the currently set time
for this calendar Protected Boolean [] isSet The flags which tell if
a specified time field
for the calendar is set Protected long time The currently set time
for this calander,
expressed in
milliseconds after
January 1, 1970,
0:00:00 GMT Protected abstract void
ComputeFields
Converts the current
millisecond time value
time to field values in
fields [] Protected abstract void
ComputeTime
Converts the current
field values in fields []
to the millisecond
time value time Java.lang.Date String toString () Converts this date
object to a String of
82
Page 83
19 CLDC 1.1
the form:
Dow mon dd
hh:mm:ss zzz yyyy Excption and error
classes
Java.land.NoClassDefF oundError
New Class; Refer to
CLDC Specification
1.1 for more details
Weak References Java.lang.ref.Reference New Class; Refer to
CLDC Specification
1.1 for more details
Java.lang.ref.WeakRefe
rence
New Class; Refer to
CLDC Specification
1.1 for more details
Additional Utility Classes
Java.util.Random Do uble ne xtDo uble () Returns the next
pseudorandom,
uniformly distributed
double value between
0.0 and 1.0 from the
random number
generator’s sequence Float nextFloat () Returns the next
pseudorandom,
uniformly distributed
int value between 0
and the 1.0 from this
random number
generator’s sequence Int nexrInt (int n) Returns a
pseudorandom,
uniformly distributed
int value between 0
(inclusive) and the
specified value
(exclusive), drawn
from this random
number generator’s
sequence Java.lang.Math Static double E The double value that
is closer thatn any
other to e, the base of
the natural logarithms Static double PI The double value that
is closer than any
other to pi, the ratio of
the circumference of
a circle to its diameter
83
Page 84
Static double abs (double a) Returns the absolute
calue of a double
value Static double ceil (double a) Returns the smallest
(closest to negative
infinity) double value
that is not less than
the arguement and is
equal to a
mathematical integer Static double cos (double a) Returns the
trigonometric cosine
of an angle Static double floor (double a) Returns the largest
(closest to positive
infinity) double value
that is not greater
than the argument
and is equal to a
mathematical integer Static double max (double a,
double b)
Returns the greater of
two double valuable
values Static float max (float a, float b) Returns the greater of
two float values Static double min (double a,
double b)
Returns the smaller of
two double values Static float min (float a, float b) Returns the smaller of
two float values Static double sin (double a) Returns the
trigonometric sine of
an angle Static double sqrt (double a) Returns the correctly
rounded positive
square root of a
double value Static double tan (double a) Returns the
trgnometric tangent of
angle Static double todegrees (double
angrad)
Converts an angle
measured in radians
to the equivalent
angle measured in
degrees
84
Page 85
19 CLDC 1.1
Static double toradians (double
angdeg)
Converts an angle
measured in degrees
to the equivalent
angle measured in
radians
85
Page 86
JTWI specifies a set of services to develop highly portable, interoperable Java applications. JTWI reduces API fragmentation and broadens the number of applications for mobile phones.
Overview
20
JTWI
Any Motorola device implementing JTWI will supp ort the fo llowing minimum hardware requirements in addition to the minimum requirements s pecified in MIDP 2.0:
At least a 125 x 125 pixels screen size as returned by full screen mode Canvas.getHeight () and Canvas.getWidth ()
At least a color depth of 4096 colors (12-bit) as returned by Display.numColors ()
Pixel shape of 1:1 ratio
At least a Java Heap Size of 512 KB
Sound mixer with at least 2 sounds
At least a JAD file size of 5 KB
At least a JAR file size of 64 KB
At least a RMS data size of 30 KB
Any Motorola JTWI device will implement the following and pass the corresponding TCK:
CLDC 1.0 or CLDC 1.1
MIDP 2.0 (JSR 118)
Wireless Messaging API 1.1 (JSR 120)
Mobile Media API 1.1 (JSR 135)
86
Page 87
20 JTWI
CLDC related content for JTWI
JTWI is designed to be implemented on top of CLDC 1.0 or CLDC 1.1. The configuration provides the VM and the basic APIs of the application environment. If floating point capabilities are exposed to Java Applications, CLDC 1.1 will be implemented.
The following CLDC requirements will be supported:
Minimum Application thread count will allow a MIDlet suite to create a minimum of 10 simultaneous running threads
Minimum Clock Resolution – The method java.land.System.currentTimeMillis () will record the elapsed time in increments not to exceed 40 msec. At least 80 % of test attemps will meet the time elapsed requirement to achieve acc eptable conformance.
Names for Encodings will support at least the preferred MIME name as defined by IANA ( character encodings. If not preferred name has been defined, the registered name will be used (i.e UTF-16).
Character Properties will provide support for character properties and case conversions for the characters in the Basic Latin and Latin-1 Supplement blocks of Unicode 3.0. Other Unicode character blocks will be supported as necessary.
http://www.iana.org/assignments/character-sets) for the supported
Unicode Version will support Unicode characters. Character information is based on the Unicode Standard version 3.0. Since the fu ll character tables required for Unicode support can be excessively large for devices with tight memory budgets, by default, the character property and case conversion facilities in CLDC assume the presence of ISO Latin-1 range of characters only. Refer to JSR 185 for more information.
Custom Time Zone Ids will permit use of custom time zones which adhere to the following time xone format:
o General Time Zone: For time zones representing a GMT offset value,
the following syntax is used:
Custom ID:
GMT Sign Hours: Minutes
GMT Sign Hours Minutes
GMT Sign Hours Hours
Sign: one of:
+ -
Hours:
Digit
87
Digit Digit
Minutes:
Digit Digit
Page 88
Digit: one of:
0 1 2 3 4 5 6 7 8 9
NOTE: Hours will be between 0 and 23, and minutes will be between 00 and 50. For example, GMT +10 and GMT +0010 equates to ten ho urs a nd ten minutes ahead of GMT.
When creating a TimeZone, the specified custom time zone ID is normalized in the following syntax:
NormalizedCustomID:
o GMT Sign TwoDigitHours: Minutes o Sign: one of:
+ -
o TwoDigitHours:
Digit Digit
o Minutes:
Digit Digit
o Digit: one of:
0 1 2 3 4 5 6 7 8 9
MIDP 2.0 specific information for JTWI
MIDP 2.0 provides the library support for use r interface, persistent storage, networking, security, and push functions. MIDP 2.0 contains a number of optional functions, some of which will be implemented as outline d below. The following JTWI requirements for MIDP
2.0 will be supported: Record Store Minimum will permit a MIDlet suite to create at least 5 independent
RecordStores. This requirement does not intend to mandate that memory be reserved for these Record Stores, but it will be possible to create the RecordStores if the required memory is avai lable.
HTTP Support for Media Content will provide support for HTTP 1.1 for all
supported media types. HTTP 1.1 conformance will match the MIDP 2.0 specification. See package.javax.microedition.io for specific requirements.
JPEG for Image Objects – ISO/IEC JPEG together wil JFIF will be supported.
The support for ISO/IEC JPEG only applies to baseline DCT, non-differential, Huffman coding, as defined in JSR 185 JTWI specification, symbol ‘SOF0’. This support extends to the class javax.microedition.lcdui.Image, including the methods outlined above. This mandate is voided in the event that the JPEG image format becomes encumbered with licensing requirements.
Timer Resolution will permit an application to specify the values for the firstTime,
delay, and period parameters of java.util.timer.schedule () methods with a distinguishable resolution of no more than 40 ms. Various factors (such as
88
Page 89
20 JTWI
garbage collection) affect the ability to achieve this requirement. At least 80% of test attempts will meet the schedule resolution requirement to achieve acceptable conformance.
Minimum Number of Timers will allow a MIDlet to create a minimum of 5
simultaneously running Timers. This requirement is in dependent of the minimum specified by the Minimum Application Thread Count.
Bitmap Minimums will support the loading of PNG images with pixel color depths
of 1, 2, 4, 8, 16, 24, and 32 bits per pixel per the PNG format specification. For each of these color depths, as well as for JFIF image formats, a compliant implementation will support images up to 76800 total pixels.
TextField and TextBox and Phonebook Coupling – when the center select key is
pressed while in a TextBox or TextField and the constraint of the TextBox or TextField is TextField.PHONENUMBER, the names in the Phonebook will be displayed in the “Insert Phonenumber?” screen.
Supported characters in TextField and TextBox – TextBox and TextField with
input constraint TextField.ANY will support in putting all the characters listed in JSR 185.
Supported characters in EMAILADDR and U RL Fields – Class
javax.microedition.lcdui.TextBox and javax.microedition.lcdui.TextField with either of the constraints TextField.EMAILADDR or TextField.URL will allow the same characters to be input as are allowed for input co nstraint TextField.ANY
Push Registry Alarm Events will implement alarm-based push registry entries. Identification of JTWI via system property – to identify a compliant device and the
implemented version of this specification, the value of the system property microedition.jtwi.version will be 1.0
Wireless Messaging API 1.1 (JSR 120) specific content for JTWI
WMA defines an API used to send and receive short messages. The API provides access to network-specific short message services suc h as GSM SMS or CDMA short messaging. JTWI will support the following as it is outlined in the JSR 120 chapter of this developer guide:
Support for SMS in GSM devices Cell Broadcast Service in GSM devices SMS Push
89
Page 90
Mobile Media API 1.1 (JSR 135) specific content for JTWI
The following will be supported for JTWI compliance:
HTTP 1.1 Protocol will be supported for media file download for all supported
media formats
MIDI feature set specified in MMAPI (JSR 135) will be implemented. MIDI file
playback will be supported.
VolumeControl will be implemented and is required for controlling the colume of
MIDI file playback.
JPEG encoding in video snapshots will be supported if the handset su pports the
video feature set and video image capture.
Tone sequence file format will be supported. Tone sequences provide an
additional simple format for supporting the audio needs of many types of games and other applications.
MIDP 2.0 Security specific content for JTWI
The Motorola E680 follows the security polic y outlined in the Security chapter of this developer guide.
90
Page 91
21 MIDP 2.0 Security Model
The following sections describe the MIDP 2.0 Default Security Model for the Motorola E680 handset. The chapter discusses the followin g topics:
Untrusted MIDlet suites and domains
Trusted MIDlet suites and domains
Permissions
21
MIDP 2.0 Security Model
Certificates
For a detailed MIDP 2.0 Security process diagram, refer to the Motocoder website (
http://www.motocoder.com).
Refer to the table below for the default security feature/class support for MIDP 2.0:
Feature/Class Implementation
All methods for the Certificate interface in the javax.microedition.pki package
All fields, constructors, methods, and inherited methods for the CertificateException class in the javax.microedition.pki package
MIDlet-Certificate attribute in the JAD Supported A MIDlet suite will be authenticated as stated in Trusted MIDletSuites
using X.509 of MIDP 2.0 minus all root certificates processes and references
Verification of RSA-1 signatures with a SHA-1 message digest algorithm
Only one signature in the MIDlet-Jar-RSA-SHA1 attribute Supported
Supported
Supported
Supported
Supported
All methods for the Certificate interface in the javax.microedition.pki package
All fields, constructors, methods, and inherited methods for the CertificateException class in the javax.microedition.pki package
Will preload at least one self authorizing Certificates Supported
91
Supported
Supported
Page 92
All constructors, methods, and inherited methods for the MIDletStateChangeException class in the javax.microedition.midlet package
All constructors and inherited methods for the MIDletStateChangeException class in the javax.microedition.midlet package
Please note the domain configuration is selected upon agreement with the operator.
Supported
Supported
Untrusted MIDlet Suites
A MIDlet suite is untrusted when the origin or integrity of the JAR file cannot be trusted by the device.
The following are conditions of untrusted MIDlet suites:
If errors occur in the process of verifying if a MIDlet suite is truste d, then the MIDlet suite will be rejected.
Untrusted MIDlet suites will execute in the untrusted dom ai n where access to protected APIs or functions is not allowed or allow ed with explicit confirmation from the user.
Untrusted Domain
Any MIDlet suites that are unsigned will belong to the untrusted domain. Untrusted domains handsets will allow, without explicit confirmation, untrusted MIDlet suites access to the following APIs:
javax.microedition.rms – RMS APIs
javax.microedition.midlet – MIDlet Lifecycle APIs
javax.microedition.lcdui – User Interface APIs
javax.microedition.lcdui.game – Gaming APIs
javax.microedition.media – Multimedia APIs for sound playback
javax.microedition.media.control – Multimedia APIs for
sound playback
The untrusted domain will allow, with ex plicit user confirmation, untrusted MIDlet suites access to the following protected APIs or functions:
javax.microedition.io.HttpConnection – HTTP protocol
javax.microedition.io.HttpsConnection – HTTPS protocol
92
Page 93
21 MIDP 2.0 Security Model
Trusted MIDlet Suites
Trusted MIDlet suites are MIDlet suites in which the int egrity of the JAR file can be authenticated and trusted by the dev ice, and bound to a protection domain. The Motorola E680 will use x.509PKI for signing and verifying trusted MIDlet suites.
Security for trusted MIDlet suites will utilize pr otection domains. Protection domains define permissions that will be granted to the MIDlet suite in th at particular domain. A MIDlet suite will belong to one protection do main and its defined permissible actions. For implementation on the Motorola E680, the following protection domains are supported:
Manufacturer
Untrusted – all MIDlet suites that are unsigned will belong to this domain.
Permissions within the above domains will authorize access to the protected APIs or functions. These domains will consist of a set of “Allowed” and “User” permissions that will be granted to the MIDlet suite.
Permission Types concerning the Handset
A protection domain will consist of a set of permissions. Each permission will be “Allowed” or “User”, not both. The following is the description of these sets of permissions as they relate to the handset:
“Allowed” (Full Access) permissions are any permissions that explic itly allo w access to a given protected API or function from a protected domain. Allowed permissions will not require any user interaction.
“User” permissions are any permissions th at require a prompt to be given to the user and explicit user confirmation in order to allow the MIDlet suite access to the protected API or function.
User Permission Interaction Mode
User permission for the Motorola E680 handsets is designed to allow the user the ability to either deny or grant access to the protected API or function using the following interaction modes (bolded term(s) is prompt displ ayed to the user):
blanket – grants access to the protected API or function eve r y time it is required by the MIDlet suite until the MIDlet suite is uninstalled or the permission is changed by the user. (Never Ask)
session – grants access to the protected API or function eve ry time it is required by the MIDlet suite until the MIDlet suite is terminated. This mode will prompt the user on or before the final invocation of the protected API or function. (Ask Once Per App Running)
93
Page 94
oneshot – will prompt the user each time th e protected API or function is requested by the MIDlet suite. (Always Ask)
No – will not allow the MIDlet suite access to the requ ested API or function that is protected. (No Access)
The prompt No, Ask Later will be displayed during runtime dialogs and will enable the user to not allow the protected function to be accessed thi s instance, but to ask the user again the next time the protected function is called.
User permission interaction modes will be determined by the security policy and device implementation. User permission will have a def ault interaction mode and a set of other available interaction modes. The user should be presented with a choice of available interaction modes, including the ability to deny access to the protected API or function. The user will make their decision based on the user-friendly description of the requested permissions provided for them.
The Permissions menu allows the user to configure permission settings for each MIDlet when the VM is not running. This menu is synchro nized with available run-time options.
Implementation based on Recommended Security Policy
The required trust model, the supported domain, and th eir corresponding structure will be contained in the default security policy for Mo torola’s implementation for MIDP 2.0. Permissions will be defined for MIDlets relating to their domain. User permission types, as well as user prompts and notifications, will also be d efined.
Trusted 3rd Party Domain
A trusted third party protection domain root certificate is used to verify third party MIDlet suites. These root certificates will be mapped to a location on the handset that cannot be modified by the user.
The following table shows the specific wording to be used in the first line of the above prompt:
Protected Functionality Top Line of Prompt
Data network “Send Data?” Data network (server mode) “Receive Data?” Comm “Connect?” Push “Auto Start-Up?” SMS “Use SMS?”
94
Page 95
21 MIDP 2.0 Security Model
SMS send “Send SMS?” SMS receive “Receive SMS?” Access phonebook “Use Phonebook?” Dial a call “Make Phone Call?” CBS “Use CBS?” Receive CBS “Receive CBS?” Record audio/video “Record?” Capture snapshot image “Video capture?” Access File System “Using File?”
The radio button messages will appear as follows and mapped to the permission types as shown in the table below:
MIDP 2.0 Permission Types Dialog Prompts
Blanket “Always yes. Do not ask again.” Session “Yes, this is running.” Oneshot “Only this oper ation. Ask me again.” No access
The above runtime dialog prompts will not be displayed when the protected function is set to “Allowed” (or full access), or if that permission type is an option for that protected function according to the security policy table flexed in the handset.
“Not this operation. Ask me again.” “Not this running.” “No, always denied. Do not ask again.”
Trusted MIDlet Suites Using x.509 PKI
Using the x.509 PKI (Public Key Infrastructure) mechan ism, the handset will be able to verify the signer of the MIDlet suite and bind it to a protection domain which will allow the MIDlet suite access to the protected API or function. Once the MIDlet suite is bound to a protection domain, it will use the permission defined in the protection domain to grant the MIDlet suite access to the defined protected APIs or functions.
The MIDlet suite is protected by signing the JAR file. The signature and certificates are added to the application descriptor (JAD) as attributes and will be used by the handset to verify the signature. Authentication is complete when the handset uses the root certificate (found on the handset) to bind the MIDlet suite to a protection domain (found on the handset).
95
Page 96
Signing a MIDlet Suite
The default security model involves the MIDlet suite, the signer, and public key certificates. A set of root certificates are used to verify certificates generated by the signer. Specially designed certificates for code signing can be obtained from the manufacturer, operator, or certificate authority. Only root certificates stored on the handset will be supported by the Motorola E680 handset.
Signer of MIDlet Suites
The signer of a MIDlet suite can be the develo per or an outside party that is responsible for distributing, supporting, or the billing of the MIDlet suite. The signer will have a public key infrastructure and the certificate will be validated to one of the protection domain root certificates on the handset. The public key is used to verify the signature of JAR on the MIDlet suite, while the public key is provided as a x.5 09 certificate included in the application descriptor (JAD).
MIDlet Attributes Used in Signing MIDlet Suites
Attributes defined within the manifest of the JAR are pr otected by the signature. Attributes defined within the JAD are not protected or secured. Attributes that appear in the manifest (JAR file) will not be overridden by a different value in the JAD for all trusted MIDlets. If a MIDlet suite is to be trusted, the value in the JAD will equal the value of the corresponding attribute in the manifest (JAR file), if not, the MIDlet suite will not be installed.
The attributes MIDlet-Permissions (-Opt) are ignored for unsigned MIDlet suites. The untrusted domain policy is consistently applied to the untrusted applications. It is legal for these attributes to exist only in JAD, only in the manifest, or in both locations. If these attributes are in both the JAD and the manifest, they will be identical. If the permissions requested in the JAD are different than those requested in the manifest, the installation must be rejected.
Methods:
1. MIDlet.getAppProperty will return the attribute value from the manifest (JAR) if one id defined. If an attribute value is not defined, the attribute value will return from the application descriptor (JAD) if present.
Creating the Signing Certificate
The signer of the certificate will be made aware of the authorization policy for the handset and contact the appropriate certificate authority. The signer can then send its distinguished name (DN) and public key in the form of a certificate request to the certificate authority used by the handset. The CA will cr eate a x.509 (version 3) certificate
96
Page 97
21 MIDP 2.0 Security Model
and return to the signer. If multiple CAs are used, all signer certificates in the JAD will have the same public key.
Inserting Certificates into JAD
When inserting a certificate into a JAD, the certificate path includes the signer certificate and any necessary certificates while omitting the root certificate. Root certificates will be found on the device only.
Each certificate is encoded using base 64 without line breaks, and inserted into the application descriptor as outlined below per MIDP 2.0.
MIDlet-Certificate-<n>-<m>: <base64 encoding of a certificate>
Note the following: <n>:= a number equal to 1 for first certification path in the descriptor, or 1 greater than
the previous number for additional certification paths. This defines the sequence in which the certificates are tested to see if the corresponding root certificate is on the device.
<m>:= a number equal to 1 for the signer’s certificate in a certific ation path or 1 greater than the previous number for any subsequent intermediate certificates.
Creating the RSA SHA-1 signature of the JAR
The signature of the JAR is created with the signer’s private key according to the EMSA­PKCS1 –v1_5 encoding method of PKCS #1 version 2.0 standard from RFC 2437. The signature is base64 encoded and formatted as a single MIDlet-Jar-RSA-SHA1 attribute without line breaks and inserted into the JAD.
It will be noted that the signer of the MIDlet suite is responsible to its protection domain root certificate owner for protecting the domain’s APIs and protected functions; therefore, the signer will check the MIDlet suite before signi ng it. Protecti on dom ain root certific ate owners can delegate signing MIDlet suites t o a third party and in some instances, the author of the MIDlet.
Authenticating a MIDlet Suite
When a MIDlet suite is downloaded, the handset will check the JAD attri bute MIDlet-Jar­RSA-SHA1. If this attribute is present, the JAR will be authenticated by verifying the signer certificates and JAR signature as d escribed. MIDlet suites with application descriptors that do not have the attributes previously stated will be installed and invoked as untrusted. For additional information, refer to the MIDP 2.0 specification.
97
Page 98
Verifying the Signer Certificate
The signer certificate will be found in the application descriptor of the MIDlet suite. The process for verifying a Signer Certificate is outlined in the steps below:
1. Get the certification path for the signer certificate from the JAD attributes MIDlet­Certificate-1<m>, where <m> starts a 1 and is incremented by 1 until there is no attribute with this name. The value of each attribut e is abase64 encoded certificate that will need to be decoded and parsed.
2. Validate the certification path using the basic validation process as described in RFC2459 using the protection domains as the source of the protection domain root certificates.
3. Bind the MIDlet suite to the corresponding protection d oma in that contains the protection domain root certificate that validated the first chain from signer to root.
4. Begin installation of MIDlet suite.
5. If attribute MIDlet-Certificate-<n>-<m> with <n> being greater than 1 are present and full certification path could not be establ ished after verifying MIDlet­Certificate-<1>-<m> certificates, then repeat step 1 t hrough 3 for the value <n> greater by 1 than the previous value.
The following table describes actions perf ormed upon completion of signer certificate verification:
Result Action
Attempted to validate <n> paths. No public keys of the issuer for the certificate can be found, or none of the certificate paths can be validated.
More than one full certification path is established and validated.
Only one certification path established and validated. Implementation proceeds with the signature
Authentication fails, JAR installation is not allowed.
Implementation proceeds with the signature verification using the first successfully verified certificate path for authentication and authorization.
verification.
Verifying the MIDlet Suite JAR
The following are the steps taken to verify the MIDlet su ite JAR:
1. Get the public key from the verified signer certificate.
2. Get the MIDlet-JAR-RSA-SHA1 attribute from the JAD.
3. Decode the attribute value from base64 yielding a PKCS #1 signature, and refer to RFC 2437 for more detail.
98
Page 99
21 MIDP 2.0 Security Model
4. Use the signer’s public key, signature, and SHA-1 digest of JAR to verify the signature. If the signature verification fails, rej ect the JAD and MIDlet suite. The MIDlet suite will not be installed or allow MIDlets from the MIDlet suite to be invoked as shown in the following table.
5. Once the certificate, signature, and JAR have b een verified, the MIDlet suite is known to be trusted and will be installed (authentication process will be performed during installation).
The following is a summary of MIDlet suite verific ation including dialog prompts:
Initial State Verification Result
JAD not present, JAR downloaded Authentication can not be performed, will install JAR. MIDlet suite is
treated as untrusted. The following error prompt will be shown, “Application installed, but may have limited function ality.”
JAD present but is JAR is unsigned
JAR signed but no root certificate present in the keystore to validate the certificate chain
JAR signed, a certificate on the path is expired
JAR signed, a certificate rejected for reasons other than expiration
JAR signed, certificate path validated but signature verification fails
Parsing of security attributes in JAD fails
Authentication can not be performed, will install JAR. MIDlet suite is treated as untrusted. The following error prompt will be shown, “Application installed, but may have limited function ality.”
Authentication can not be performed. JAR installation will not be allowed. The following error prompt will b e shown, “Root certificate missing. Application not installed.”
Authentication can not be completed. JAR installation will not be allowed. The following error prompt will be shown, “Expired Certificate. Application not installed.”
JAD rejected, JAR installation will not be allowed. The foll owing error prompt will be shown, “Authentication Error. Application not installed.”
JAD rejected, JAR installation will not be allowed. The foll owing error prompt will be shown, “Authentication Error. Application not installed.”
JAD rejected, JAR installation will not be allowed. The foll owing error prompt will be shown, “Failed Invalid File.”
JAR signed, certificate path validated, signature verified
99
JAR will be installed. The following prompt will be shown, “Installed.”
Page 100
Appendix A:
Audio Mix Table
Single
tons
Single tone
Tone­sequence
WAV No No Partly
MP3 No No No No No Yes No Yes AMR No No No No No Yes No No MIDI Yes Yes Yes Yes Yes No No Yes Video
w/audio Video
w/o audio
No No No No No Yes No Yes
No No No No No Yes No Yes
No No No No No No No No
Yes Yes Yes Yes No Yes No no
Tone­Sequence
NOTE: If two wave plays have the same frequency, they can mix
Wav MP3 AMR MIDI Video
No No Yes No Yes
yes
w/audio
Video w/o audio
100
Loading...