Wednesday, July 28, 2010

Receive SMS using J2ME push registry

Here is the sample code which i have posted in nokia wiki forum

http://wiki.forum.nokia.com/index.php/How_to_receive_SMS_using_Push_Registry

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import javax.microedition.io.*;

public class PushDemo extends MIDlet implements CommandListener
{
private Display display;
private Command cmExit;
private Alert alertIncomingMessage;
int incomingPortNum=6535;
MessageConnection incomingConnection = null;
Message incomingMessage;


public PushDemo ()
{
display = Display.getDisplay(this);
alertIncomingMessage = new Alert("Incoming Message");
alertIncomingMessage.setTimeout(Alert.FOREVER);

cmExit = new Command("Exit", Command.EXIT, 1);
alertIncomingMessage.addCommand(cmExit);
alertIncomingMessage.setCommandListener(this);
}

public void startApp()
{
String connectList[];
connectList = PushRegistry.listConnections(true);
if (connectList == null || connectList.length == 0) {
//Started by the user,exit
destroyApp(false);
notifyDestroyed();
}
else { //started from incoming connection...
try {
incomingConnection = (MessageConnection) Connector.open("sms://:" +
incomingPortNum);
// Recieve the message
incomingMessage = incomingConnection.receive();

//If it's a text message add it to the alert
if (incomingMessage != null && incomingMessage instanceof TextMessage) {
alertIncomingMessage.setTitle("From: " + incomingMessage.getAddress());
alertIncomingMessage.setString( ( (TextMessage) incomingMessage).
getPayloadText());
//Display the message
display.setCurrent(alertIncomingMessage);
}
}
catch (Exception e)
{
System.out.println("IO Exception!");
}
}
}

public void pauseApp()
{
System.out.println("The pauseApp method is invoked");
}

public void destroyApp(boolean cond)
{
System.out.println("The destroyApp method is invoked");
}

/**Handle command events*/
public void commandAction(Command command, Displayable displayable) {
/** @todo Add command handling code */
if (command.getCommandType() == Command.EXIT) {
// stop the MIDlet
destroyApp(true);
}
}



}