Wednesday, April 9, 2008

Brew application development - Get Started

Creating and selling applications using the BREW® platform follows this simple four step process:
  1. Download the BREW SDK®
    Download the FREE BREW SDK and start developing BREW applications today!
    The next three steps apply to developers writing applications for BREW Operators using the standard BREW business model.
  2. Become a BREW Developer/Authentication
    Authenticated BREW Developers receive the benefits of the Alliance Program.
  3. Application Development
    Authenticated developers are given access to the BREW Developer Extranet, which contains the tools and information necessary to develop applications for specific BREW devices.
  4. Application Testing and Distribution
    Application testing is performed by an independent third party. Application distribution is managed by the developer via the BREW Developer Extranet.

Getting the IMSI number from mobile devices

An International Mobile Subscriber Identity, or IMSI [im-zee], is a unique number associated with all GSM and Universal Mobile Telecommunications System (UMTS) network mobile phone users. It is stored in the Subscriber Identity Module (SIM) inside the phone and is sent by the phone to the network. It is also used to acquire other details of the mobile in the Home Location Register (HLR) or as locally copied in the Visitor Location Register. In order to avoid the subscriber being identified and tracked by eavesdroppers on the radio interface, the IMSI is sent as rarely as possible and a randomly generated TMSI is sent instead.

The IMSI is used in any mobile network that interconnects with other networks, in particular CDMA and EVDO networks as well as GSM nets. This number is provisioned in the phone directly or in the R-UIM card (a CDMA analogue equivalent to a SIM card in GSM)

An IMSI is usually 15 digits long, but can be shorter (for example MTN South Africa's IMSIs are 14 digits). The first 3 digits are the Mobile Country Code, and is followed by the Mobile Network Code (MNC), either 2 digits (European standard) or 3 digits (North American standard). The remaining digits are the mobile subscriber identification number (MSIN) within the network's customer base.

The IMSI conforms to the International Telecommunication Union (ITU) E.212 numbering standard.

Example

IMSI:404400021281732

MCC 404 India
MNC 40 Airtel
MSIN 0021281732


Code:

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class MobileProperties extends MIDlet implements CommandListener {
Form f = null;
Display dis = null;
Command ok = null;
Command exit = null;

public MobileProperties () {
dis=Display.getDisplay(this);
f = new Form(" Mobile Details ");
ok =new Command(" Ok",Command.OK,1);
exit =new Command(" Exit",Command.EXIT,2);
f.addCommand(ok);
f.addCommand(exit);
f.setCommandListener(this);
}

public void startApp(){
try {
f.append(" Nokia IMSI : " + System.getProperty("com.nokia.mid.imsi")+"\n");
f.append(" IMSI : " + System.getProperty("IMSI")+"\n");

} catch(Exception e) {
f.append("Exception :"+e);
}
dis.setCurrent(f);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s) {
if (c == ok) {
destroyApp(true);
notifyDestroyed();
} else if (c==exit) {
destroyApp(true);
notifyDestroyed();
}
}
}

Getting the IMEI number from mobile devices of different manufacturers

International Mobile Equipment Identity (IMEI) is used to identify valid devices connected to GSM and UMTS network. This number can be accessed from a mobile phone by dialing *#06# on the keypad. IMEI is commonly use by software developers as part of software protection scheme to prevent it from being pirated.

JavaME developers however suffers from a drawback because MIDP/CLDC specification does not include an API to obtain IMEI from mobile devices. However there are few phone manufacturers included this functionality through System.getPropery() calls. Here's how to get IMEI number from mobile devices of different manufacturers

Manufacturer Argument
Nokia Mobiles System.getProperty("com.nokia.mid.imei”);
Sony-Ericsson Mobiles System.getProperty("com.sonyericsson.imei");
Motorola Mobile System.getProperty("IMEI");
Motorola Mobile System.getProperty("com.motorola.IMEI");
Samsung Mobiles System.getProperty("com.samsung.imei");
Siemens Mobiles System.getProperty("com.siemens.imei");


Code:

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class MobileProperties extends MIDlet implements CommandListener {
Form f = null;
Display dis = null;
Command ok = null;
Command exit = null;
String s1= null;

public MobileProperties () {
dis=Display.getDisplay(this);
f = new Form(" Mobile Details ");
ok =new Command(" Ok",Command.OK,1);
exit =new Command(" Exit",Command.EXIT,2);
f.addCommand(ok);
f.addCommand(exit);
f.setCommandListener(this);
}

public void startApp(){
try {
if ((s1 = System.getProperty("phone.imei")) == null || s1.equals("")) {
s1 = System.getProperty("com.nokia.mid.imei");
}
if (s1 == null || s1.equals("")) {
s1 = System.getProperty("com.sonyericsson.imei");
}
} catch(Exception e) {
f.append("Exception :"+e);
}
dis.setCurrent(f);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s) {
if (c == ok) {
destroyApp(true);
notifyDestroyed();
} else if (c==exit) {
destroyApp(true);
notifyDestroyed();
}
}
}

Getting a random number from range


If you need to get a random number between X and Y, you should use some mathematical pattern using the Math Class and some calculus.

You can use this quick method to get the random number:

public int getRandomNumber(int min, int max) {
Random rnd;
rnd = new Random();
return min + Math.abs(rnd.nextInt()) % (max - min);
}


Another Method

Using the below code you can generate a 4 digit random integer.
int random4Digit = (int) (9 * Math.random())
+ (int) (9 * Math.random())
+ (int) (9 * Math.random())
+ (int) (9 * Math.random());

You can generate a 5 digit random int, by adding one more '(int) (9 * Math.random())'

Installing an application on the Phone's Game menu

By default in Nokia mobiles, when a user install a Java ME application, it is installed in the default folder on in "Applications" folder. If you want to suggest a Nokia device to install the JAR file in the Game menu of the mobile device, you have to insert this property in the JAD file of your game:
Nokia-MIDlet-Category: Game

Detecting if a Class/Package is available on the phone

You know Java ME has many optional packages that phones must have preinstalled over MIDP and CLDC. So, how can you compile one only code that detects on the fly if some class or API is available?

We can use the dynamic instantiation method, like this:

Code:
boolean MMAPIAvailable;
try {
// Try to instantiate a class using a string as the Class name
// so, the SDK without the API can compile the application
Class.forName("javax.microedition.media.Player").newInstance();
// If the next code is executed, then the API is available
MMAPIAvailable = true;
} catch ( ClassNotFoundException e) {
MMAPIAvailable = false;
}

Blocking the screen saver using J2Me

If your application doesn't demand constant key presses, after a while the screen saver on a J2ME phone will start automatically.

To make sure that the display light is turned on, the setLights method should be called before the screen saver is started and this must be done in a loop since the screen saver is not disabled just interrupted.

BacklightWorkaround.java
import com.nokia.mid.ui.DeviceControl;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class BacklightWorkaround extends MIDlet {

private SimpleCanvas canvas;

/**
* Keeps the backlight on by repeatedly setting
*/

class LightThread extends Thread {
public void run() {
while(true){

DeviceControl.setLights(0, 100);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

private class SimpleCanvas extends Canvas implements CommandListener{
private Command exitCmd;
private MIDlet midlet;

public SimpleCanvas(MIDlet midlet) {
this.midlet = midlet;
exitCmd = new Command("Exit",Command.EXIT, 1);
addCommand(exitCmd);
setCommandListener(this);
}
public void paint(Graphics g) {
g.drawString("Let there be light.", 0, 0, Graphics.LEFT|Graphics.TOP);
}

public void commandAction(Command command, Displayable displayable) {
if(command == exitCmd){
midlet.notifyDestroyed();
}
}
}

public void startApp() {
if(canvas == null){
canvas = new SimpleCanvas(this);
new LightThread().start();
}

Display.getDisplay(this).setCurrent(canvas);
}

public void pauseApp() { }

public void destroyApp(boolean unconditional) { }
}

Adding contacts using JSR 75

Following code snippets show how to add contacts using JSR 75.

PIMWrite class
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class PIMWrite extends MIDlet implements CommandListener
{
private Command PIMWriteCmd,exitCommand,generateName;
PIMImpl pimImpl;
private static Random random = new Random();
static String[] names;

public static Display display;
public static Form result;
private String sp,si,s1;
private String[] strJSR = new String[12];
private long l;
int noOfContacts;

TextField textfield = new TextField("Enter No of Contacts: ","",3,TextField.NUMERIC);


/*Constructs an Object
*/

public PIMWrite() {

display = Display.getDisplay(this);

PIMWriteCmd = new Command("PIMWrite", Command.SCREEN, 0);


exitCommand = new Command("Exit", Command.SCREEN, 0);

result=new Form("Write Contacts To PIM");
result.append(textfield);
System.out.println(" noOfContacts: "+noOfContacts);

result.addCommand(PIMWriteCmd);
result.addCommand(exitCommand);
result.setCommandListener(this);

}

public void startApp() throws MIDletStateChangeException {
display.setCurrent(result);

}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s)
{
if (c == exitCommand)
{
destroyApp(false);
notifyDestroyed();
}

else if(c == PIMWriteCmd)
{
noOfContacts = Integer.parseInt(textfield.getString());
createConatactName();
System.out.println(" noOfContacts: "+noOfContacts);
//Start the PIM thread and write contacts .
pimImpl = new PIMImpl();
pimImpl.start();


}
}

public void createConatactName()
{
names = new String[noOfContacts];
for (int i = 0; i < style="color: rgb(102, 204, 102);">){
names[i] = PIMWrite.generateName()+" "+PIMWrite.generateName();
System.out.println(" Names :"+ names[i]+ " i "+i);
}
}


public static String generateName()
{
return generateName(4, 7, true);
}


/** This method generates the random names
*
* @param minLength Minimum length of name
* @param maxLength Max length of name
* @param capitalize Captilize
* @return name
*/

public static String generateName(int minLength, int maxLength, boolean capitalize)
{

int limit = (random.nextInt(maxLength - minLength + 1)) + minLength;
StringBuffer s = new StringBuffer(limit);
for (int i = 0; i < style="color: rgb(102, 204, 102);">)
{
char c = (char)((random.nextInt(26)) + 'a');
s.append(c);
}
if (capitalize && (s.length() > 0)) s.setCharAt(0, Character.toUpperCase(s.charAt(0)));
return s.toString();
}
}
PIM Implementation class

/**
* PIM Implementation class
*/

import javax.microedition.pim.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Command;

public class PIMImpl extends Thread
{
static Alert check;

StringItem si;
//----------------------------------------Phone Book---------------------------------

int noOfRecords;
public static boolean pimTemp = false;
Random randPh = new Random();


public PIMImpl()
{

}

public void run()
{
writeData();
}



public synchronized void writeData()
{

String ph[] = new String[PIMWrite.names.length];
for (int i=0;inames.length ;i++ )
{

String r = Long.toString(randPh.nextLong());
if(r.startsWith("-"))
{
r = r.replace('-','9');
}
ph[i] =(r.length()>10)?(r.substring(0,10)):(r);



// System.out.println(" PH :"+ph[i] +"i:"+i);
}


int tc = 0;
PIM pim;
try{

ContactList contacts = null;
ContactList conT = null;
pim = PIM.getInstance();
try {

contacts = (ContactList) pim.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// An error occurred
return;
}
for(int i=0;inames.length;i++)
{

Contact contact = contacts.createContact();
String[] name = new String[contacts.stringArraySize(Contact.NAME)];

// System.out.println("i = "+i);
if (contacts.isSupportedField(Contact.TEL))
{
contact.addString(Contact.TEL, Contact.ATTR_MOBILE, ph[i]);
}

if (contacts.isSupportedArrayElement(Contact.NAME, Contact.NAME_GIVEN))
name[Contact.NAME_GIVEN] = PIMWrite.names[i];
contact.addStringArray(Contact.NAME, PIMItem.ATTR_NONE, name);


try {
contact.commit();
} catch (PIMException e) {
// An error occured
}
PIMWrite.result.deleteAll();
String msg=" Contacts Adding :"+i;
si = new StringItem("",msg);
PIMWrite.result.append(si);

}
check = new Alert("Added","Added ",null,AlertType.CONFIRMATION);
check.setTimeout(Alert.FOREVER);
PIMWrite.display.setCurrent(check);

try {
contacts.close();
} catch (PIMException e) {
}

}catch(Exception e){
String er = e+" ; tc="+tc;
check = new Alert( "Response",er,null,AlertType.CONFIRMATION );
check.setTimeout(Alert.FOREVER);

PIMWrite.display.setCurrent(check);
}
// return true;

}

}

Tuesday, April 8, 2008

Reading contacts from Mobile using JSR 75

The below Midlet explains how to read the contact names and numbers from the Phonebook using JSR 75
PIMMidelt.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class PIMMidelt extends MIDlet
{
ReadPIM readPim;
Display display;

public void startApp()
{
display = Display.getDisplay(this);
readPim = new ReadPIM(this);
display.setCurrent(readPim);
}
public void pauseApp()
{
}
public void destroyApp(boolean uc)
{
}
}
ReadPIM.java
import javax.microedition.lcdui.*;
import javax.microedition.pim.*;
import java.util.*;
import java.io.*;
public class ReadPIM extends Form implements Runnable,CommandListener
{
PIM pim;
PIMList pimlist;
Contact contact=null;
Enumeration enumeration;
PIMMidelt midlet;

String contactName="";
String contactNo="";


StringItem name;
StringItem telno;
Thread thread=null;
Command exitCmd = new Command("Exit",Command.EXIT,1);

public ReadPIM(PIMMidelt midlet)
{
super("Reading contacts");
this.midlet = midlet;

pim = PIM.getInstance();

thread = new Thread(this);
thread.start();
addCommand(exitCmd);
setCommandListener(this);

}

public void run()
{
readContacts();
}

public void readContacts()
{
String[] lists = pim.listPIMLists(pim.CONTACT_LIST);
for (int i = 0; i < style="color: rgb(0, 102, 0);">length; i++)
{
try{
pimlist = pim.openPIMList(pim.CONTACT_LIST,pim.READ_WRITE);
}catch(Exception e){}


try{
enumeration = pimlist.items();
}catch(Exception e){}

while (enumeration.hasMoreElements())
{
contact = (Contact)enumeration.nextElement();

try{
if(pimlist.isSupportedField(Contact.FORMATTED_NAME)&& (contact.countValues(Contact.FORMATTED_NAME) >0))
{
contactName += contact.getString(Contact.FORMATTED_NAME,0) +"\r\n";;
System.out.println("COntact name:"+contactName);
}
}catch( Exception e){}

int phoneNos = contact.countValues(Contact.TEL);
try{
if(pimlist.isSupportedField(Contact.TEL) &&(contact.countValues(Contact.TEL) >0))
contactNo += contact.getString(contact.TEL,0) +"\r\n";
System.out.println("contact No :"+contactNo);
}catch( Exception e){}

}

name = new StringItem("Name",contactName);
telno = new StringItem("No",contactNo);
append(name);
append(telno);

}
}

public void commandAction(Command c , Displayable d) {
if(c == exitCmd) {
midlet.destroyApp(true);
midlet.notifyDestroyed();
}
}
}

Monday, April 7, 2008

Getting the IMEI Number of a Mobiles Using J2ME

International Mobile Equipment Identity (IMEI) is used to identify valid devices connected to GSM and UMTS network. This number can be accessed from a mobile phone by dialing *#06# on the keypad. IMEI is commonly use by software developers as part of software protection scheme to prevent it from being pirated. JavaME developers however suffers from a drawback because MIDP/CLDC specification does not include an API to obtain IMEI from mobile devices. However there are few phone manufacturers included this functionality through System.getPropery() calls. Here's how to get IMEI number from mobile devices of different manufacturers

Manufacturer Argument
Nokia Mobiles System.getProperty("com.nokia.mid.imei”);
Sony-Ericsson Mobiles System.getProperty("com.sonyericsson.imei");
Motorola Mobile System.getProperty("IMEI");
Motorola Mobile System.getProperty("com.motorola.IMEI");
Samsung Mobiles System.getProperty("com.samsung.imei");
Siemens Mobiles System.getProperty("com.siemens.imei");

System properties

The table below defines the generic system properties used by the S60 platform.

Generic system properties

System property Description Value
microedition.platform Name of the host platform or device. Defined in CLDC 1.0 and CLDC 1.1.
microedition.encoding Character encoding. Always returns ISO-8859-1.
microedition.configuration Name and version of the supported configuration value is either “CLDC-1.0” or “CLDC-1.1”, depending on which configuration is implemented. Defined in CLDC 1.0 and CLDC 1.1.
microedition.profiles Names of the supported profile as specified in the MIDP 2.1 API specification. Devices that implement other profiles will also return names of those profiles. Defined in MIDP 2.1 (java.lang package documentation).
microedition.locale* The value is determined according to the language settings of the device. Defined in MIDP 2.1 (java.lang package documentation).
microedition.commports
Defined in MIDP 2.1 javax.microedition.io.CommConnection.
microedition.hostname Returns the local host localhost
microedition.jtwi.version
Defined in Java Technology for the Wireless Industry API specification, version 1.0.

(* - The set of locales supported by the device depends on the languages and region.)

The table below defines the S60 specific system properties used by S60 platform. These system properties are available to the application by calling method java.lang.System.getProperty

Nokia system properties

The table below defines the S60 specific system properties used by S60 platform. These system properties are available to the application by calling method java.lang.System.getProperty

System property Description Value
com.nokia.network.access Returns the networking access point type. pd.GSM - Packet data in GSM network

pd.EDGE - Packet data in EDGE network pd.3G - Packet data in 3G network csd - Circuit switched data, for example GSM CSD/HSCSD data call bt_pan - Bluetooth PAN network wlan - Wireless network, for example 802.11b, 802.11G or WiMaX hsdpa - High speed downlink packet access for 3G networks na - Not applicable, the implementation can’t determine the type

com.nokia.mid.dateformat The preferred date format indicated as a string pattern, which is formatted according to the rules defined in Java 2, Standard Edition, version 1.4.1, java.text.SimpleDateFormat class documentation for date patterns.

Only subset of SimpleDateFormat defined pattern letters are used in this system property.


com.nokia.mid.timeformat The preferred time format indicated as a string pattern, which is formatted according to the rules defined in Java Standard Edition, version 1.4.1, java.text.SimpleDateFormat class documentation for time patterns.

Only subset of SimpleDateFormat defined pattern letters are used in this system property.

hh:mm a
com.nokia.memoryramfree This can be used to query the available RAM in the operating system.

This is a more realistic estimate of available RAM on the device than what is returned by Runtime.getRuntime().freeMemory(), which returns only free memory in the Java virtual machine. Note: This property is not available on all S60 3rd Edition devices.


com.nokia.mid.batterylevel The battery charge level of device. Returns the percentage value of battery level.
com.nokia.mid.countrycode Current network country code. Returns the two-letter country code defined in ISO-3361.
com.nokia.mid.networkavailability Network availability. The property return value can contain "available" or "unavailable". available or unavailable
com.nokia.mid.networkid Network identification parameters, such as network ID (NID in CDMA and MNC in GSM) and network short name. Returns two values:

network ID network short name

com.nokia.mid.networksignal Current (GSM/CDMA) network signal strength. Returns two values:

the number of bars the phone should display the signal strength in dBm

com.nokia.mid.imei The IMEI (International Mobile Equipment Identity) of the device. Returns a 14 digit decimal number that uniquely identifies the device.
com.nokia.mid.imsi The IMSI (International Mobile Subscriber Identity) stored in the SIM card. Note that the access to this system property is limited with com.nokia.mid.mobinfo.IMSI permission. By default this permission is available only in manufacturer and operator domain. Returns the subscriber number associated with the device. The IMSI number is usually 14 decimal digits long, but it may be shorter.

The com.nokia.mid.timeformat and com.nokia.mid.dateformat system properties indicate the user preferences of date and time formats. For example, in many devices there are settings available for user to indicate the date and time formatting settings: ordering of date, month and year components of date strings, separators used between components of date and time strings, whether 12 or 24 hour clock is used, and so on. The values of above system properties indicate the currently active user preferences for these settings. MIDlets can use these values to format date and time strings they, for example, need to display in user interfaces.