Thursday, November 19, 2009

Fractional Number Conversion

To convert a fraction into binary, we can repeatedly multiply by 2, keeping the integer part.

After each multiplication, the integer part becomes the next binary digit (left to right), and
the fractional part gets multiplied by 2 again. We can continue until the fractional part is
zero, or until we have as many digits as we desire. For example, to convert 0.59375 (base 10)
into binary we multiply: .1 0 0 1 1 / / / / / .59375 * 2 = 1.1875 keep the 1 -----------+ / / / / \__/ / / / / /------------/ / / / / v / / / / .1875 * 2 = 0.375 keep the 0 ---------+ / / / \_/ / / / /-----------/ / / / v / / / .375 * 2 = 0.75 keep the 0 -------+ / / \/ / / /-----------/ / / v / / .75 * 2 = 1.5 keep the 1 -----+ / \/ / /------------/ / v / .5 * 2 = 1.0 keep the 1 ---+ Since the fractional part of the last multiplication is 0, we can stop and we have an exact
answer. (Any additional digits would simply be 0.) So our answer is 0.59375 (base 10) = 0.010011
(base 2). We can check this by converting the binary back to decimal. The fractional place values in
binary are: 1 1 1 1 1 . --- --- --- --- --- ... 2^1 2^2 2^3 2^4 2^5 or: 1 1 1 1 1 . - - - -- -- ... 2 4 8 16 32 or: . (.5) (.25) (.125) (.0625) (.03125) ... So 0.10011 (base 2) is: 1 * .5 = .5 + 0 * .25 = .0 + 0 * .125 = .0 + 1 * .0625 = .0625 + 1 * .03125 = .03125 -------- .59375 (base 10) So it double-checks. Notice that most fractions that terminate in a decimal will be
repeating fractions in binary. For example, let's convert the fraction 0.6 (base 10) to binary: .1 0 0 1 1 0 0 1 ... / / / / / / / / .6 * 2 = 1.2 keep the 1 ---+ / / / / / / / .2 * 2 = 0.4 keep the 0 ----+ / / / / / / .4 * 2 = 0.8 keep the 0 -----+ / / / / / .8 * 2 = 1.6 keep the 1 ------+ / / / / .6 * 2 = 1.2 keep the 1 -------+ / / / .2 * 2 = 0.4 keep the 0 --------+ / / .4 * 2 = 0.8 keep the 0 ---------+ / .8 * 2 = 1.6 keep the 1 ----------+ Notice that the second four lines repeat the first four, and the next four would repeat them,
and so on. Thus, our answer is: 0.6 (base 10) = 0.10011001... (base 2)

Binary Conversion

To convert a binary number to a decimal number you must first understand what each digit in the binary number means. To explain this let's look at the decimal number 247.

The '2' in 247 represents two hundred because it is a two in the hundreds position (two times a hundred is two hundred). In similar fashion, the '4' in 247 represents forty because it is a four in the tens position (four times ten is forty). Finally, the '7' represents seven because it is a seven in the units position (seven times one is seven). In a decimal number, the actual value represented by a digit in that number is determined by the numeral and the position of the numeral within the number.

It works the same way with a binary number. The right-most position in a binary number is units; moving to the left, the next position is twos; the next is fours; the next is eights; then sixteens; then thirty-twos ... Notice that these numbers are all powers of two - 2^0, 2^1, 2^2, 2^3, 2^4, 2^5. (The units, tens, hundreds, thousands, ten thousands of the decimal system are all powers of ten: 10^0, 10^1, 10^2, 10^3, 10^4).

So, to convert the binary number 1001 (don't read that as one thousand one - read it as one zero zero one) to decimal, you determine the actual value represented by each '1' and add them together. The right-most '1' has a decimal value of 1 (it is in the 2^0, or units, position) and the left-most '1' has a decimal value of 8 (it is in the 2^3, or eights, position). So the binary number 1001 is equal to
decimal 9. Here's another way to look at it:


1 0 0 1
^ ^ ^ ^
| | | |_________> 1 x 2^0 = 1 x 1 = 1
| | |___________> 0 x 2^1 = 0 x 2 = 0
| |_____________> 0 x 2^2 = 0 x 4 = 0
|_______________> 1 x 2^3 = 1 x 8 = 8
---
9

Both the decimal system and the binary system are positional number systems. The hexadecimal system is another positional number system. The binary system has only two numerals - 0 and 1; the decimal system has ten numerals: 0,1,2,3,4,5,6,7,8, and 9. In the hexadecimal (or hex) system there are sixteen numerals: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E, and F. Zero through nine have the same value as a decimal numeral, and A is ten, B is eleven, C is twelve, D is thirteen, E is fourteen, and F is fifteen. After a while you will get used to seeing "letters" used as numerals!

The decimal number system is also referred to as "base ten" since each position in a decimal number represents a power of ten - a number that can be written as 10^n, where n is an integer. The binary number system is also referred to as "base two" since each position in a binary number represents a power of two - a number that can be written as 2^n, where n is an integer. The hex number system is also referred to as "base sixteen" since each position in a hexadecimal number
represents a power of sixteen - a number that can be written as 16^n, where n is an integer.

The right-most position in a hexadecimal number is units; moving to the left, the next position is sixteens; the next is two hundred fifty-sixes; the next is four thousand ninety-sixes, and so on - all powers of sixteen - 16^0, 16^1, 16^2, 16^3.

To convert a binary number to a hex equivalent, notice that four binary digits together can have a value of from 0 to 15 (decimal) exactly the range of one hex digit. So four binary digits will always convert to one hex digit!

For example:

10110111 = B7 (hex)

The right-most four digits of the binary number (0111) equal seven, so the hex digit is '7'. The remaining left-most four digits of the binary number (1011) equal eleven, so the hex digit is 'B'. Here is another way of looking at it:

1 0 1 1 0 1 1 1 from right to left, make four-digit groups
\ /\ /
\ / \ /
eleven seven determine the decimal equivalent of each
| | group
V V
B 7 write the equivalent hexadecimal digit

What is the decimal equivalent of B7 hex?

B 7
^ ^
| |_________> 7 x 16^0 = 7 x 1 = 7
|___________> 11 x 16^1 = 11 x 16 = 176
---
183 decimal

Check that against the decimal equivalent of 10110111 binary:

1 0 1 1 0 1 1 1
^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | |_________> 1 x 2^0 = 1 x 1 = 1
| | | | | | |___________> 1 x 2^1 = 1 x 2 = 2
| | | | | |_____________> 1 x 2^2 = 1 x 4 = 4
| | | | |_______________> 0 x 2^3 = 0 x 8 = 0
| | | |_________________> 1 x 2^4 = 1 x 16 = 16
| | |___________________> 1 x 2^5 = 1 x 32 = 32
| |_____________________> 0 x 2^6 = 0 x 64 = 0
|_______________________> 1 x 2^7 = 1 x 128 = 128
---
183 decimal

Tuesday, November 17, 2009

J2ME - Game API - Introduction

There are only five classes in the javax.microedition.lcdui.game package:

GameCanvas
Layer
Sprite
TiledLayer
LayerManager.

These five classes are enough to provide a platform for the development of games with a wide range of capabilities.

The Layer class is the superclass of the Sprite and TiledLayer classes. This class abstracts the behavior of a visual element in a game. This element can be a sprite, which represents an independent graphic (or a collection of graphics for animation) that can be moved around the game screen, or a tiled layer, which represents a graphic that can be used to create vast game backgrounds with only a handful of images. You can use the Layer classes for positioning and visibility. The subclasses override the paint(Graphics g) method, which has the task of rendering the elements on the screen.

The LayerManager class provides a convenient mechanism to manage the various visual elements of a game (sprites and tiled layers) by rendering the proper layer in the proper order.

The GameCanvas class is made useful by extending the functionality of the Canvas class. It provides an off-screen buffer, to which all rendering operations are done before flushing them on the device screen. It also provides an easy-to-use mechanism to query the current keys being pressed by the user.
The best way to introduce you to these classes is with the help of a working game example, which we will build from the ground up, explaining the various facets of a game. This is helpful whether or not you have programmed a game before, if you are looking to learn how to do it for the wireless devices using J2ME's gaming API.

A quick view on Game development

A game or animation is built according to the principle of repetitively executing a piece of code. This piece of code tracks the value of instance variables and updates the game state accordingly. Based on the game state, the code then draws/paints/repaints the game screen with the elements that make up the game. The values of the instance variables may change because of either user interaction or internal game behavior.

The repetitive execution is effected by putting the repetitive code in an infinite loop. Before entering the loop, an instance variable may be checked to see if the game should still be running, and if not, the loop may be exited. The code in the loop should allow the current thread of execution to sleep every few milliseconds to control the rate at which the update to the instance variables is done (in effect, how fast the game screen should be refreshed).

Implementation of Game Canvas Class

A GameCanvas class is a specialized subclass of the Canvas class that you encountered in the previous installment of this series. GameCanvas is optimized for gaming because it provides a special off-screen buffer in which all painting operations are done. When all painting on this buffer is complete, the buffer is rendered on the device screen by calling the flushGraphics() method. This double buffering has the advantage of producing smooth transitions of moving elements on a screen to counter the flickering that might happen if no buffering were provided. The size of the buffer is equal to the size of the device screen, and there is only one buffer per GameCanvas instance.

The GameCanvas class provides a storage mechanism for the state of game keys, which is a useful way to query user interaction with the game. This provides a simple way of keeping track of the number of times the user has pressed a particular key. Calling the method getKeyStates() returns a bitwise representation of all of the physical game keys, expressed as 1 for pressed and 0 for unpressed, since the last time the method was called. Only the following game states are identified, which is what you would expect, keeping in mind the game keys defined by the Canvas class: DOWN_PRESSED, UP_PRESSED, RIGHT_PRESSED, LEFT_PRESSED, FIRE_PRESSED, GAME_A_PRESSED, GAME_B_PRESSED, GAME_C_PRESSED, and GAME_D_PRESSED.

Define Game Characteristics

On the screen, these constants help define the boundary of the game and its sole element (the couple), as shown in diagram below:


OTA (Over The Air) Provisioning

The term over-the-air provisioning (OTA) describes the ability to download and install content over a wireless network, typically on demand. From the mobile client's perspective, in concept OTA is simply a matter of finding an interesting application on the Web and initiating its download over the wireless network. In its simplest form, OTA is pretty straightforward, as we can see in the following diagram:



These are the components involves in OTA working:


  • Client device with a discovery application - The client device must have software that allows the user to locate applications at a particular provisioning portal on the network, and to choose which applications to download - this software is referred to as a discovery application (DA). The discovery application may be browser-based or a native application, so long as it shares a common provisioning protocol with the download server; for example, for MIDP OTA this protocol is HTTP.

  • The Network - This is any appropriate wireless network, which may include a radio network and a WAP gateway, for example.

  • The Download Server - Also called a provisioning portal, or server, or vending machine, this is a host, visible in the network, that typically runs a web server and has access to a content repository - in its simplest form any Web site can serve as a provisioning portal. It has two main functions: it provides properly formatted menus, often written in WML or HTML, that list the applications currently available for download, and it provides access (sometimes controlled) to the applications. A single download server might support one or many OTA protocols.

  • The Content Repository - As the name implies, this is the repository of all the application descriptors and applications that are available for download.


An OTA provisioning system typically encompasses content publication and management, access control, installation (and upgrading) of applications, and tracking the use of applications (content) for billing purposes. Below is the diagram which show the complexity involves in OTA:






  • A. Content Management - Server-side software manages the repository, typically a database, and supports content versioning, ways for third-party developers to drop their applications, and so on. Some carriers require applications be certified before making them available for OTA.

  • B. Content Discovery - As you've already seen, the user directs the discover application to a download portal, which accesses the application repository and provides a properly formatted menu of the available content and applications.

  • C. Authenticate - If the provisioning server supports an authentication module, the user is authenticated before gaining access to the repository.

  • D. Application retrieval and installation - Once any authentication is complete, downloading the application is a two-part operation, handled by the application management system (AMS), the software in the device that manages the download, installation, execution, and removal of applications and other resources on the device. If an application description (in the form of a JAD file) exists, the AMS downloads it from the provisioning server's repository. Based on information found in the downloaded application descriptor, the AMS automatically downloads the application (the MIDlet suite JAR) from the repository. If required, the user is re-authenticated. If the application is retrieved successfully, installation is automatic.

  • E. Confirmation - The AMS sends a confirmation status to indicate whether the installation succeeded or failed.

  • F. Tracking - The confirmation status can be used to track the use of the application, for example for billing purposes. A billing system is often integrated into the provisioning server.

In addition to the basic features described above, some OTA provisioning servers add value in the form of features such as:

  • Personalization - the ability to offer selected applications based on user preferences

  • Device-based classification - limiting offerings to only those applications that will run on the user's device

  • Security - strong user authentication and access control

  • Alerts - notices to users that new applications fitting their preferences are available

You now have a high-level perspective of OTA application provisioning.

Sunday, November 15, 2009

J2ME applications powered by wireless messaging have a platform-independent access to wireless communication resources like Short Message Service (SMS) and Cell Broadcast Service (CBS) for Global System for Mobile Communication (GSM) Networks.

Short Message Service (SMS)

SMS is the transmission of short text messages to and from a mobile phone, fax machine, and/or IP address in a GSM network. Messages must be no longer than 160 alphanumeric characters and contain no images or graphics. The main features of this service are speed, cheap rates, and the guarantee that the message will reach the target person, even if he is out of radio coverage or his phone is turned off.
Once a message is sent, it is received by a Short Message Service Center (SMSC), which must then get it to the appropriate mobile device. To do this, the SMSC sends a SMS request to the home location register (HLR) to find the roaming customer. Once the HLR receives the request, it will respond to the SMSC with the subscriber's status, as in 1) inactive or active, and 2) roaming location.
If the response is inactive, then the SMSC will hold onto the message for a period of time. When the subscriber accesses his device, the HLR sends a SMS notification to the SMSC, and the SMSC attempts delivery.
The SMSC transfers the message to a GSM message delivery system in a Short Message Delivery Point-to-Point format. The system pages the device and, if it responds, delivers the message.
The SMSC receives verification that the message was received by the end user, and then categorizes the message as sent and will not attempt to send it again. The SMS delivery mechanism is show in figure below



Cell Broadcast Service(CBS)

Cell Broadcast Service allows messages to be sent to every Mobile Station (MS), such as a mobile phone, fax machine, and/or IP address currently in a particular cell. Cell broadcast messages are repeated at intervals over a period of time, which allows an MS to receive the message even if entering the cell after the first transmission. The data can be sent either as binary data or ASCII text up to 15 pages in length, with a page being up to 93 characters in length; the test set only provides support for ASCII messages. Cell broadcast messages are classified by topic and allocated a channel number, message code, update number, and language:
A Channel Number is a header number identifying the message topic (such as 'Weather Report' or 'Traffic Information').
A Message Code identifies a particular message, so that an MS receiving a message with the same code as a previously received message will recognize that it is a repeat, and may not display it to the user.
An Update Number is used to identify a particular version of a message. This is useful for reporting a dynamic situation, where a message may be reporting one event (such as road construction ahead), but the details of which change periodically (the length of the traffic jam, for example). An MS that remains in one cell for a length of time will receive messages with the same message code, but update numbers as updated versions of the same message are received; however, an MS that enters the cell will receive only the most recent version of the message, followed by any subsequent versions.
Language indicates in what language the message is. Changing this parameter does not translate the text of a message.
While SMS is a one-to-one and one-to-few messaging system, CBS provides one-to-many messaging within a certain geographical area.

Workable model of Wireless Messaging System

This system can be viewed as a 3-tiered architecture, consisting of the Interface Layer, Implementation Layer and Transport Layer.
The Interface Layer constitutes a generic set of messaging interfaces, independent of any messaging protocol. These interfaces provide the basic definition of a message, define the basic functionality of sending and receiving it, and provide a mechanism for the MIDlet application to be notified of the incoming message.
The Implementation Layer contains classes which implement each Interface Layer to access wireless messaging like SMS or CBS functionalities on a GSM mobile device. For instance, from the SMS point of view, this layer provides an implementation of the message connection for SMS messages as well as an implementation of a SMS message with text or binary attributes. The Implementation Layer also performs segmentation and concatenation of messages for the underlying protocol. The MIDlet can then specify the number of segments a message should be broken into in a MessageConnection.
The Transport Layer contains classes that are the actual implementation of protocols that carry messages to the mobile device.



Wednesday, November 11, 2009

Java - Sand Box Security Model

Java platforms Security Model is known as the Sandbox model. Which was created to provide a very restricted environment to run untrusted code obtained from the open network. The need of the sandbox model is that local code is trusted to have full access to vital system resources (such as the file system) while downloaded remote code (an applet) is not trusted and can access only the limited resources provided inside the sandbox. The sandbox model was deployed through the Java Development Kit (JDK), and was generally adopted by applications built with JDK 1.0, including Java-enabled web browsers.

Overall security is enforced through a number of mechanisms. First of all, the language is designed to be type-safe and easy to use. The hope is that the burden on the programmer is such that the likelihood of making subtle mistakes is lessened compared with using other programming languages such as C or C++. Language features such as automatic memory management, garbage collection, and range checking on strings and arrays are examples of how the language helps the programmer to write safe code.

Second, compilers and a bytecode verifier ensure that only legitimate Java bytecodes are executed. The bytecode verifier, together with the Java Virtual Machine, guarantees language safety at run time.

Moreover, a classloader defines a local name space, which can be used to ensure that an untrusted applet cannot interfere with the running of other programs.

Finally, access to crucial system resources is mediated by the Java Virtual Machine and is checked in advance by a SecurityManager class that restricts the actions of a piece of untrusted code to the bare minimum.

JDK 1.1 introduced the concept of a "signed applet", as illustrated by the figure below. In that release, a correctly digitally signed applet is treated as if it is trusted local code if the signature key is recognized as trusted by the end system that receives the applet. Signed applets, together with their signatures, are delivered in the JAR (Java Archive) format. In JDK 1.1, unsigned applets still run in the sandbox.




The new Java 2 Platform Security Architecture.

Fine-grained access control

This capability existed in the JDK from the beginning, but to use it, the application writer had to do substantial programming (e.g., by subclassing and customizing the SecurityManager and ClassLoader classes). The HotJava browser 1.0 is such an application, as it allows the browser user to choose from a small number of different security levels.
However, such programming is extremely security-sensitive and requires sophisticated skills and in-depth knowledge of computer security. The new architecture will make this exercise simpler and safer.

Easily configurable security policy.

Once again, this capability existed previously in the JDK but was not easy to use. Moreover, writing security code is not straightforward, so it is desirable to allow application builders and users to configure security policies without having to program.
Easily extensible access control structure
Up to JDK 1.1, in order to create a new access permission, you had to add a new check method to the SecurityManager class. The new architecture allows typed permissions (each representing an access to a system resource) and automatic handling of all permissions (including yet-to-be-defined permissions) of the correct type. No new method in the SecurityManager class needs to be created in most cases. (In fact, we have so far not encountered a situation where a new method must be created.)
Extension of security checks to all Java programs, including applications as well as applets.

There is no longer a built-in concept that all local code is trusted. Instead, local code (e.g., non-system code, application packages installed on the local file system) is subjected to the same security control as applets, although it is possible, if desired, to declare that the policy on local code (or remote code) be the most liberal, thus enabling such code to effectively run as totally trusted. The same principle applies to signed applets and any Java application.

Finally, an implicit goal is to make internal adjustment to the design of security classes (including the SecurityManager and ClassLoader classes) to reduce the risks of creating subtle security holes in future programming.


Tuesday, November 10, 2009

J2ME - Generic Connection Framework (GCF)

GCF was originally defined to rely on the J2ME platform's Connected Limited Device Configuration (CLDC), version 1.0, because the familiar J2SE java.net and java.io APIs were considered too large to fit into the constrained memory available in mobile devices.

Today you can find the GCF not only in CLDC-based profiles, such as the Mobile Information Device Profile (MIDP) and the Information Module Profile (IMP), but also in Connected Device Configuration (CDC)-based profiles. You can also find the GCF in an increasing number of optional packages, including those that provide Bluetooth support and access to files and smart cards.

A Generic Approach to Connectivity

As the name suggests, the GCF provides a generic approach to connectivity. It is generic because it provides a common foundation API for all the basic onnection types - for packet-based (data blocks) and stream-based (contiguous or sequence of data) input and output.

This generalization is possible through the use of:

  • An interface hierarchy that is extensible
  • A connection factory
  • Standard Uniform Resource Locators (URLs) to indicate the connection types to create


A total of seven interfaces are defined in GCF, with Connection at the top. Importantly we have to look that both datagram (packet) and stream connections are supported. As we will move down in the hierarchy, connections become more complex and functional.

For packet-based I/O the GCF defines DatagramConnection, and for stream-based I/O InputConnection, OutputConnection, StreamConnection, and ContentConnection.

The GCF is so practical and flexible that it is used across J2ME profiles and optional packages, and now on the J2SE platform as well.

Monday, November 9, 2009

J2ME - Record Management System (RMS)

Persistent storage is a non-volatile place for storing the state of objects. For some applications, you might need objects to exist even after the application that created those objects quits. Without persistent storage, objects and their states are destroyed when an application closes. If you save objects to persistent storage, their lifetime is longer than the program that created them, and later you can read their state and continue to work with them.

The MIDP provides a mechanism for MIDlets to persistently store data and retrieve it later. This mechanism is a simple record-oriented database called the Record Management System (RMS). A MIDP database (or a record store) consists of a collection of records that remain persistent after the MIDlet exits. When you invoke the MIDlet again, it can retrieve data from the persistent record store.


The J2ME record management system (RMS) provides a mechanism through which MIDlets can persistently store data and retrieve it later. In a record oriented approach, J2ME RMS comprises multiple record stores.

To use the RMS, import the javax.microedition.rms package.

Each record store can be visualized as a collection of records, which will remain persistent across multiple invocations of the MIDlet. The device platform is responsible for making its best effort to maintain the integrity of the MIDlet's record stores throughout the normal use of the platform, including reboots, battery changes, etc.

Record stores (binary files) are platform-dependent because they are created in platform-dependent locations. MIDlets within a single application (a MIDlet suite) can create multiple record stores (database files) with different names. The RMS APIs provide the following functionality:

  • Allow MIDlets to manipulate (add and remove) records within a record store.

  • Allow MIDlets in the same application to share records (access one another's record store directly).

  • Do not provide a mechanism for sharing records between MIDlets in different applications.

Record store implementations ensure that all individual record store operations are atomic, synchronous, and serialized, so no corruption of data will occur with multiple accesses. The record store is timestamped to denote the last time it was modified. The record store also maintains a version, which is an integer that is incremented for each operation that modifies the contents of the record store. Versions and timestamps are useful for synchronization purposes.

When a MIDlet uses multiple threads to access a record store, it is the MIDlet's responsibility to coordinate this access; if it fails to do so, unintended consequences may result. Similarly, if a platform performs a synchronization of a record store with multiple threads trying to access the record store simultaneously, it is the platform's responsibility to enforce exclusive access to the record store between the MIDlet and its synchronization engine.

Each record in a record store is an array of bytes and has a unique integer identifier.

Record Id Data

1 Array of Bytes

2 Array of Bytes

3 Array of Bytes

.. ....

.. ....

Record stores are identified by name. A name may consist of up to 32 characters, and all characters are case sensitive. No two record stores within a MIDlet suite (that is, a collection of one or more MIDlets packaged together) may contain the same name.

Each record store has a version number as well as a date/time stamp. Both values are updated whenever a record is added, replaced, or deleted.

Creating a Record Store

No constructor exists for creating a record store. Here, we use a set of three dual-purpose methods to create and/or open record stores.

RecordStore openRecordStore(String recordStoreName,boolean createIfNecessary)

RecordStore openRecordStore(String recordStoreName,boolean createIfNecessary,int authmode,boolean writable)
RecordStore openRecordStore(String recordStoreName,String vendorName,String suiteName)

The RecordStore API

In this API you will find the methods which enables you to work with a record store. These range from adding, deleting, and replacing record contents to enumerating through a record store.

Following are the list of methods:

void closeRecordStore()

void deleteRecordStore(String recordStoreName)
String[] listRecordStores()
int addRecord(byte[] data, int offset, int numBytes)
void setRecord(int recordId, byte[] newData, int offset, int numBytes)
void deleteRecord (int recordId)
byte[] getRecord (int recordId)
int getRecord (int recordId, byte[] buffer, int offset)
int getRecordSize (int recordId)
int getNextRecordID()
int getNumRecords()
long getLastModified()
int getVersion()
String getName()
int getSize()
int getSizeAvailable()
RecordEnumeration enumerateRecords(RecordFilter filter,RecordComparator comparator,boolean keepUpdated)
void addRecordListener (RecordListener listener)
void removeRecordListener (RecordListener listener)
void setMode(int authmode, boolean writable)

The RecordEnumeration API

The primary benefits of incorporating a record enumerator into your code is that it includes options

for searching the record store,and for retrieving records in sorted order.
Another point that we've
been traversing the record store with a simple for loop. Although this technique has been sufficient
to our needs so far,we'll see in this section what happens when we extend our code to include a
record enumerator. One of the primary benefits of incorporating a record enumerator into your code
is that it includes options for searching the record store, and for retrieving records insorted order.

Method available in RecordEnumeration API as follows:

int numRecords()
byte[] nextRecord()
int nextRecordId()
byte[] previousRecord()
int previousRecordId()
boolean hasNextElement()
boolean hasPreviousElement()
void keepUpdated(boolean keepUpdated)
boolean isKeptUpdated()
void rebuild()
void reset()
void destroy()

The RecordComparator API

The RecordEnumeration API provides the foundation for working with enumerations, allowing us to cycle through entries in the RMS. But it's the RecordComparator interface that lets us actually retrieve records from the record store in sorted order.

The RecordComparator API consists of one method and three pre-defined return values. The sole method in this interface accepts two parameters, and both are byte arrays.
Methods/Static Data Fields for RecordComparator API


int compare(byte[] rec1, byte[] rec2)

static int EQUIVALENT
static int FOLLOWS
static int PRECEDES

The RecordFilter API

Sorting with a comparator is one option when working with an enumerator, searching with a filter is the other. A minor difference between a comparator and a filter is that a comparator returns the entire record store in sorted order, whereas a filter returns only those records that match a specified criteria. If you apply both a comparator and a filter, records that match the search criteria will be returned in sorted order.

Like the RecordComparator, the RecordFilter is implemented by the addition of a single method, matches(), to the enumerator code. The enumerator calls thematches() method for each record in the store. Based on the boolean return value, the record either becomes a member of the result set or is tossed aside as a record that does not meet the search criteria.

Method for RecordFilter API

boolean matches(byte[] candidate)


















Sunday, November 8, 2009

J2ME - Low Level UI

MIDP also gives you a low level component called Canvas for pixel level access. Low level components can be used to create basic drawings and create custom components. Canvas class should be extended for low level access. This class provides paint() method which has to be implemented for drawing on to the Canvas.

Method paint() takes a Graphics instance as parameter. With Graphics we can draw items like arc, rectangle, line, image, triangle, circle etc. Different parameters like fonts, colors, anchors can also be specified.

Determine Screen Size

To determine the screen size call methods getWidth() and getHeight().

Co-ordinate System

As the following picture shows pixel based coordinate system starts from upper left corner.

Anchor Points

Text and Images can also is drawn using anchor points using Anchor Points. Anchor points are used to decrease the calculations required when drawing a String/Image on a Canvas.

Anchor points are defined with two constants

Horizontal constants: LEFT, HCENTER, RIGHT. Vertical constants: TOP, BASELINE, BOTTOM.

The following figure shows various anchor points.


The image or text is drawn at X co-ordinate and Y Co-ordinate and the alignment of the image will be based on Horizontal and Vertical anchor constants.
Color

Color can be manipulated using Method setGrayScale() which gives you black and white colors and setColor() to set RGB Colours. When setColor() is called all subsequent operations are rendered in this color unless setColor() is called with another color. This method takes three parameters representing Red, Blue and Green hues to construct a color. Each of these parameters can have a value between 0 and 225.

Fonts

The Font class represents fonts and font metrics. You cannot create a Font Object by calling a Font constructor. The Font object is returned by the device when Graphics.getFont() and Font.getFont() is called. The system will return a handle to a compatible Font available with the system.

Then call Graphics.setFont(font) to set the font for all subsequent text operations.Method getFont() takes three parameters

  • Face: Font face defines the font type. Example: FACE_MONOSPACE, FACE_PROPORTIONAL, FACE_SYSTEM
  • Style: Decorations for the fonts. Example: STYLE_BOLD, STYLE_ITALIC, STYLE_PLAIN, STYLE_UNDERLINED
  • Size: Size of the font. Example: SIZE_LARGE, SIZE_MEDIUM, SIZE_SMALL

Text Does not wrap on a Canvas

When you write a multiple line sentence on the canvas using Graphics.drawString(). The sentence will not wrap on a canvas and an algorithm has to be written to wrap the text using following procedure.

  1. Find the Canvas height using Canvas.getWidth()
  2. Find the Font width for each character using Font.charWidth()
  3. As you parse through the sentence and wrap the text.

Images

The Image class is used to do all image manipulations. Images are of two types

Mutable Images: These are the new images created by the applications and on creation have a plain white background and your application has to draw on this background. These images are created as off-screen drawing and then can be displayed on to the canvas, form or alert.

Images can be placed on Alert, Choice, Form, or ImageItem objects. An immutable image can be converted to a mutable image by drawing the immutable image on to a mutable image.

Low level Event Handling

Following Canvas methods have to be implemented for event handling

Key Pressed: keyPressed(int keyCode)
Key Released: keyReleased(int keyCode)
Key Held Down: keyRepeated(int keyCode)

When a user presses a key on the mobile keypad. These event are passed to keyPressed() method. We can recognize the pressed key by analyzing the keyCode.MIDP defines the following key codes:

  • KEY_NUM0
  • KEY_NUM1
  • KEY_NUM2
  • KEY_NUM3
  • KEY_NUM4
  • KEY_NUM5
  • KEY_NUM6
  • KEY_NUM7
  • KEY_NUM8
  • KEY_NUM9
  • KEY_STAR
  • KEY_POUND

There may be other keys on the keyboard. These keys can be known by printing the keyCode in keyPressed() method. You can also use getKeyName() method to find the string printed on the pressed key. The keyCodes listed above are standard keys. Make sure you use only these keys for better portability.

Game Actions

MIDP has standard gaming related actions mapped to the keys.MIDP defines the following game actions:

  • UP
  • DOWN
  • LEFT
  • RIGHT
  • FIRE
  • GAME_A
  • GAME_B
  • GAME_C
  • GAME_D











Tuesday, November 3, 2009

J2ME -Mobile Development


J2ME can be divided into three parts.

A Configuration: A configuration contains the JVM (not the traditional JVM, but the cut-down version) and some class libraries.

A Profile: a profile builds on top of these base class libraries by providing a useful set of APIs

Optional Packages: An Optional set of APIs that you may or may not use when creating your applications. Optional packages are traditionally not packaged by the device manufacturers, and you have to package and distribute them with your application.

The configuration and profile are supplied by the device manufacturers and they embedded them in the devices.


The most popular profile and configuration that Sun provides are the Mobile Information Device Profile (MIDP) and Connected Limited Device Configuration (CLDC), respectively. As the name suggests, CLDC is for devices with limited configurations; for example, devices that have only 128 to 512KB of memory available for Java applications. Consequently, the JVM that it provides is very limited and supports only a small number of traditional Java classes. (This limited JVM is actually called the KVM.) Its counterpart, the Connected Device Configuration (CDC) is for devices with at least 2MB of memory available and supports a more feature-rich JVM (but still not a standard JVM).

The MID profile complements the CLDC configuration very well because it minimizes both the memory and power required for limited devices. It provides the basic API that is used for creating application for these devices. For example, it provides the javax.microedition.lcdui package that allows us to create the GUI elements that can be shown on a (limited) device running the MID profile on top of a CLDC configuration. Note that MIDP cannot be used with CDC devices. CDC devices get their own set of profiles, like the Foundation and Personal profiles. However, I will not cover these profiles or the CDC here, and will concentrate on using MIDP and CLDC only.

The MIDlet Lifecycle

Mobile devices, whether emulators or real, interact with a MIDlet using their own software, which is called Application Management Software (AMS). The AMS is responsible for initializing, starting, pausing, resuming, and destroying a MIDlet. (Besides these services, AMS may be responsible for installing and removing a MIDlet, as well.) To facilitate this management, a MIDlet can be in one of three states which is controlled via the MIDlet class methods, that every MIDlet extends and overrides. These states are active, paused and destroyed.