Java on Wireless Devices J2ME Contents Introduction to J2ME Constituents of J2ME – Configurations and Profiles More into MIDP Applications - MIDlets Designing User Interfaces using MIDP Networking using MIDP J2ME Database J2ME An Introduction What is J2ME ? J2ME stands for Java 2, Micro Edition It just means Java for small devices which have many usability constraints such as • Memory • Display area • Battery Life • Network Connectivity J2ME is not: • A fixed, specific set of software • A fixed, specific set of API J2ME is divided into Configurations and Profiles, which provide specific information and features for a group of related devices Why J2ME ? Java’s perspective Java API for low bandwidth devices Advanced Java API for Rapid Application Development on low end clients Inherits Java’s USP: Platform Independence, Objectoriented approach, In-built security, Easy to Use Large Developer community Why J2ME ? Applications perspective Dynamically downloadable/upgradeable/removable Applications Dynamic content Applications Off-line execution on Device – J2ME’s edge over WAP API’s for Data Security applicable to banking and mcommerce applications Richer GUI related to the devices’ constraints APIs for Network Connectivity Stand alone applications – (Usually) Do not need any browser to run Position of J2ME in Java arena Personal Profile Optional Pkgs J2EE Optional Pkgs J2SE JVM Foundation Profile J2ME MIDP PDA Pr ofil e CDC CLDC Java Card API CVM KVM Card VM HOST Operating System Relative Features of various VMs JVM Java Spec Target Devices Processor Memory HotSpot VM J2EE Enterprise Servers Up to 64 bit Upwards of 2 MB HotSpot VM J2SE Workstations, Desktop Clients, Laptops 32-64 bit Upwards of 2MB CVM J2ME High end, consumer electronic and embedded devices like wireless communicators eg. devices running Symbian's EPOC OS), high-end PDAs (e.g. devices running embedded Linux or Windows CE), residential gateways, automotive telematic systems, set-top boxes and screen phones 32 bit 2MB – 10 MB Min 512Kb ROM Min 256 kB RAM Relatively constrained GUI KVM J2ME Cell Phones, Pagers, PDAs 16 bit 160-512 kB Highly constrained GUI Card VM Java Card API Smart Cards 8 bit <32 kB Constituents of J2ME Configurations and Profiles Configurations Sun’s definition: A configuration is defined as the combination of a Virtual Machine (VM) and "core" APIs that represent an underlying development platform for a broad class of devices Thus, A configuration is a specification for a certain class of devices having similar capabilities Usually based on available memory, display and processing power of the target set of devices Specifies a JVM, which can be ported to the target set of devices Specifies a subset of J2SE APIs that will be available to the target set of devices Profiles Sun’s definition: A profile is defined as a set of APIs for a specific vertical market and relies upon the underlying configuration's capabilities to create new, market-specific APIs. Thus, a Profile Is Built on Configurations Targets more specific set of devices than configurations Adds APIs for User Interface, Persistent storage, available input and output facilities and other features that may be needed to run applications on that particular segment of devices. J2ME Delivers: Two Configurations: • • CDC – Connected Device Configuration CLDC – Connected, Limited Device Configuration Two major Profiles: • • • MIDP – Mobile Information Device Profile Foundation Profile Others Upcoming – PDA Profile, Personal Profile, RMI Profile, Java Game Profile, MIDP_NextGen Profile Configurations-1: CDC CDC is based on CVM The CVM is a full-featured, Java 2 Virtual Machine; designed for devices needing the functionality of the Java 2 VM feature set. The CDC is a configuration that could become interesting for mobile terminals as their capabilities increase CDC targets networked devices with relatively constrained Graphical user Interfaces. Basic packages: java.lang, java.util, java.net, java.io, java.text, java.security Configurations-2: CLDC CLDC is based on KVM Limitations w.r.t. J2SE: • • • • • • • • • No support for JNI (Java Native Interface) Limited bytecode verifier Limited support for internationalization No support for object finalization No thread groups and daemon threads Limited error handling Simplified sandbox security model No certificates supported No refection: No Serialization, RMI or JINI Features like Floating point support and J2ME Web Services support added in latest CLDC v1.1 CLDC Packages java.io - Provides for system input and output through byte and data streams. java.lang - Language Classes included from J2SE java.util - Utility Classes included from J2SE. Profiles 1 - MIDP Target devices have a small display area (min. 96x54 pixels) and a touch pad Adds the following features to CLDC: • • • • • Defining and controlling applications Displaying text, graphics and responding to user events Storing data in simple databases Network connectivity via a subset of HTTP Timer notifications kxml and Nanoxml are two XML parsers on the device side Latest MIDP v2.0 adds support of HTTPS for ensuring end-to-end security. Other features enhanced in GUI, network connectivity (using different types of sockets), Audio support, Game Support, OTA Provisioning etc. More details to be taken later Profiles 1: MIDP (Contd.) New features added in MIDP 2.0 • • • • • • • Enhanced UI – Richer and more flexible screen widgets Media Support – You can add audio to your applications Game Support – Game API for enhanced graphics, performance and ease of development Expanded Connectivity – Added support for different types of sockets Push Architecture – Servers can now invoke MIDlets for alerts and broadcast OTA Provisioning – Mandates a single, standard approach for OTA MIDlet deployment on the devices. End to End Security – Support of HTTPS and X.509 PKI certificates. Profiles 2 – Foundation Profile It provides a profile of the Java 2 Platform, suitable for devices that need support for a rich, network enabled Java environment, but do not require a graphical user interface. It is used by other profiles, targeted for devices of similar profile, but having their own GUI packages. Other Upcoming Profiles PDA Profile – Is based on CLDC, meant for PDAs • • adds a display toolkit, which is a subset of AWT Simple persistent data storage for applications, data, and configuration information. Personal Profile – Is based on CDC, meant for devices providing high Internet connectivity and web fidelity RMI Profile – Provides RMI features for invoking remote services e.g. Printer, distributed objects from the device Java Games Profile – Provides core audio-video features for development of Games, animations, videos etc. MIDP Applications An Insight MIDP Applications in a Device Layout of applications on a typical device is as shown below: MIDP Applications - MIDlets Applications in MIDP are called MIDlets These applications/MIDlets can be downloaded, updated for newer versions or removed from the device These MIDlet applications can be used in offline mode as well, e.g. Games, Text Editors etc. The user need to connect to the server only if he/she wants to upload some data. Properties of MIDlets are described in a application descriptor file: a regular text file with an extension of .jad MIDlet suites are packaged as jar files, which contain the class files for that application as well as other resource files required at runtime A jar Manifest file contains other information like name, version, vendor, icon, MIDlet class name etc. OTA Downloading of a MIDlet Steps of OTA downloading 1. 2. 3. 4. 5. 6. 7. Applications are found on the network by either the user browsing the web or by a discovery application checking dedicated servers. The descriptor URL is passed to the Application Management Software (AMS), usually developed by device manufacturer. The AMS retrieves the application descriptor from the server. In the application descriptor file, the AMS finds the URL to the MIDlets Jar file. The AMS downloads the Jar file. The AMS stores the Jar file on the device. The user selects the application to run and launches thus the KVM… …and finally the application starts running. MIDlets – Life Cycle The application must extend the class javax.microedition.midlet to allow the application management software to control the MIDlet and to be able to retrieve properties from the application descriptor, notify and request state changes. Constructor Paused startApp() pauseApp() destroyApp() Destroyed Active destroyApp() MIDP Packages Packages available for development of MIDP applications MIDP Packages javax.microedition.lcdui - The UI API provides a set of features for implementation of user interfaces for MIDP applications javax.microedition.rms - The MIDP provides a mechanism for MIDlets to persistently store data and later retrieve it. E.g. RecordStore javax.microedition.midlet - The MIDlet package defines MIDP applications and the interactions between the application and the environment in which the application runs javax.microedition.io - This includes networking support classes based on the GenericConnection framework from the CLDC e.g. HTTPConnection, DatagramConnection etc. MIDP Applications Designing User Interfaces MIDP User Interface MIDP User Interface (Contd.) Display is the primary class for any GUI – There is only one instance of Display per MIDlet. Display instantiated as : Display.getDisplay(MIDlet m) A Display displays the various Displayable objects, and also controls the sequence of the various Displayable objects. (setCurrent() API) Other classes – Command, Image, Font, Graphics, Ticker etc. The Item class is the abstract parent of many items. A Sample MIDlet import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; import org.kxml.*; import org.kxml.parser.*; /** Main MIDlet class */ public class MyMIDlet extends MIDlet implements CommandListener { private Command exitCommand; // The exit command private Command goCommand; private Display display; // The display for this MIDlet private final static String SERVLET_URL = 18. "http://127.0.0.1:8080/ServletXML/ServletXML"; private List list; private static String textBoxString = ""; public MyMIDlet() { display = Display.getDisplay( this ); exitCommand = new Command( "Exit", Command.EXIT, 2 ); goCommand = new Command( “GO", Command.SCREEN, 1 ); list = new List(“Commands List”, Choice.IMPLICIT); } /** Start up the MIDlet by associating list.with options, adding the commands and listener. */ public void startApp() { list.append(“First command”, null); list.append(“Second command”, null); list.addCommand( exitCommand ); list.addCommand( goCommand ); list.setCommandListener( this ); display.setCurrent( list ); } /** Pause is a no-op since there are no background activities or 43. record stores that need to be closed. */ public void pauseApp() { } /** Destroy must cleanup everything not handled by the garbage collector. */ public void destroyApp(boolean unconditional) { } /* Respond to commands*/ public void commandAction(Command c, Displayable d) { if ( c == exitCommand ) { destroyApp( false ); notifyDestroyed(); } else if ( c == goCommand ) { if (((List)d).getSelectedIndex() == 0) processCommandOne(); else if (((List)d).getSelectedIndex() == 1) processCommandTwo(); } Other GUI Components TextBox, TextField – For Text Inputs Ticker – To display a Scrolling message Alert – A dialog message for Alarms, info, confirmation, error and warnings. Can be user or timer driven. List – Displays a list of options to choose from Gauge – Progress bar Image – Any image to be associated with widgets. It is a .png file DateField – For representing date fields Form – A customizable screen which may contain many different components (like an HTML page). Command Class A Command is equivalent to a Button It can be classified into “OK”, “Back”, “Cancel”, “Exit”, “Screen” etc. To show commands, add them to a Displayable Register with a Displayable to receive notifications, and pass a listener To listen for command events, implement the CommandListener interface This has only one method, commandAction() Form A customizable screen which may contain many different components/items Use append() and insert() for adding items Use set() for modifying an item Use delete() to remove an item You can register an ItemStateListener with a Form Use the setItemStateListener() method The listener has a single callback: public void itemStateChanged(Item item) MIDP Applications Networking with External Entities Network Connections in MIDP CLDC specifies a generic connection mechanism, which can be customized by implementations. MIDP defines Connection and its subinterfaces for more specific types of connections Connector is a factory class which takes in a URL string and opens a Connection, which can be typecast to any of the sub-defined connection interfaces. HTTP Connections in MIDP GET: Connection con = (HttpConnection)Connector.open(url); InputStream is = con.openInputStream(); // Get the length and process the data int len = (int)con.getLength(); if (len > 0) { byte[] data = new byte[len]; int actual = is.read(data); } else{ int ch; while ((ch = is.read()) != -1) { doSomething(ch); } } is.close(); con.close(); POST: Connection con = (HttpConnection)Connector.open(url); // Set the request method and headers con.setRequestMethod(HttpConnection.POST); con.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31 GMT"); con.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); con.setRequestProperty("Content-Language", "en-US"); // Getting the output stream may flush the headers OutputStream os = con.openOutputStream(); os.write("LIST games\n".getBytes()); os.flush(); // Opening the InputStream will open the connection InputStream is = con.openInputStream(); // Get the length and process the data int len = (int)con.getLength(); if (len > 0) { byte[] data = new byte[len]; int actual = is.read(data); process(data); } else { int ch; while ((ch = is.read()) != -1) { process((byte)ch); } } MIDP Applications Storing Persistent Data J2ME Databases Persistent storage in MIDP is based on record stores A record store is a collection of records. Each record is an array of bytes with a unique identification number Actual storage of records depends on MIDP implementation. It could be hard disk on the device, a battery-backed RAM etc. The package javax.microedition.rms provides API for handling device datastores. The class RecordStore consists of APIs such as openRecordStore(), closeRecordStore(), deleteRecordStore(), listRecordStore() for RecordStore manipulation. It also consists of APIs such as addRecord(), deleteRecord(), get and setRecord() for record manipulation. J2ME Databases (Contd.) A RecordStore allows eventlistener to be registered with itself. This eventlistener is a class which implements a RecordListener interface to get notifications for addition, deletion and updating of records in that RecordStore. J2ME also provides interfaces such as RecordComparator, RecordEnumerator and RecordFilter for comparing, enumerating and filtering of records from a RecordStore, respectively. Mobile Databases File based storage PDB(Palm Database) Databases Sybase SQL Anywhere Studio 8.0 Oracle 9i Lite Relational database UltraLite from AppForge and iAnyWhere Pocket Access 2002 SQL Server CE J2ME Toolkit J2ME provides a toolkit for compiling and verifying the source files. It then creates the jar file for the compiled classes and also makes the .jad file. This toolkit provides 4 different device emulators to test the application. It provides a Panel where the debug statements of the application get printed. It provides a UI to specify the Application Properties, such as Servlet path etc. which are used by the application at runtime. Visto’s J2ME Sync Client A client meant for synchronizing Calendar, Contacts and Email. (Currently, having default implementation for Calendar/Contacts) Consists of its own GUI for Email (Calendar and Contacts in future) Creates and Opens up its own RecordStore for storing of Emails, Calendar, and Contacts. Provisions the device for Email synchronization. Synchronizes the data present in its record stores with the ones at the Corporate Server through the Sync Server, after comparisions. Maintains the state machine of the sync at the client. Sends the Sync data in WBXML format. Also contains code for performing encoding and Blowfish encryption algorithms on the data. Optional Profile Packages Other competing technologies BREW (Binary Runtime Environment for Wireless) designed by QualComm, based on C, C++ - It provides the device’s functionalities available to the application such as Memory Mgmt, Notifications, Networking, Display, UI etc. MExE – (Mobile Execution Environment) – created by ETSI, maintained by 3GPP) - provides a standardized environment for appln execution on Mobile Devices.It provides interoperability between devices by defining “Classmarks” which cater to different groups of devices, e.g. WAP Environment, PersonalJava Environment, J2ME CLDC Environment and an upcoming Microsoft .NET Environment. Personal Java and Embedded Java – These are subsets of J2ME, and target the devices which have smaller footprint than the J2ME devices Lets Think Small !! Thanks for Your Patience