View RSS Feed

My Java Tips

Writing MIDlet for SMS

Rate this Entry
by , 11-27-2011 at 05:53 PM (1473 Views)
SMS stands for Short Messaging Service and it is very common in mobile communication. J2ME provides an API for SMS which makes messaging very easy.


I will write a MIDlet to show how to create a messaging system using javax.wireless.messaging.
First step is to import all the required APIs:

Java Code:
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import java.io.IOException;
MIDlet class should extend MIDlet class. Since it will be a multithreaded application, we need to implement Runnable interface. To provide action listeners, we will also implement CommandListener and MessageListener interfaces.

Java Code:
public class SMSReceive extends MIDlet
implements CommandListener, Runnable, MessageListener {
Now we may declare the commands we want to have in our MIDlet.

Java Code:
/** user interface command for indicating Exit request. */
Command exitCommand = new Command("Exit", Command.EXIT, 2);
/** user interface command for indicating Reply request */
Command replyCommand = new Command("Reply", Command.OK, 1);
/** user interface text box for the contents of the fetched URL.
*/




will continue with writing the MIDlet.
Now we will declare other stuff (Thread, Alert, String arrays etc) as shown below:

Java Code:
Alert content;
/** current display. */
Display display;
/** instance of a thread for asynchronous networking and user interface. */
Thread thread;
/** Connections detected at start up. */
String[] connections;
/** Flag to signal end of processing. */
boolean done;
/** The port on which we listen for SMS messages */
String smsPort;
/** SMS message connection for inbound text messages. */
MessageConnection smsconn = null;
/** Current message read from the network. */
Message msg;
/** Address of the message's sender */
String senderAddress;
/** Alert that is displayed when replying */
Alert sendingMessageAlert;
/** Prompts for and sends the text reply */
SMSSender sender;
/** The screen to display when we return from being paused */
Displayable resumeScreen;
We need to initialize the MIDlet with the current display object and graphical components. I will do that in the SMSReceive method as shown below.

Java Code:
public SMSReceive() {
smsPort = getAppProperty("SMS-Port");

display = Display.getDisplay(this);

content = new Alert("SMS Receive");
content.setTimeout(Alert.FOREVER);
content.addCommand(exitCommand);
content.setCommandListener(this);
content.setString("Receiving...");

sendingMessageAlert = new Alert("SMS", null, null, AlertType.INFO);
sendingMessageAlert.setTimeout(5000);
sendingMessageAlert.setCommandListener(this);

sender = new SMSSender(smsPort, display, content, sendingMessageAlert);

resumeScreen = content;
}
I will write startApp() method. This is part of MIDlet lifecycle. Application Management System calls it after calling the constructor.

Java Code:
public void startApp() {
// SMS connection to be read.
String smsConnection = "sms://:" + smsPort;
content.setString(smsConnection);

// Open the message connection.

try {
smsconn = (MessageConnection)Connector.open(smsConnection, Connector.READ);
} catch (Throwable t) {
content.setString(t.toString());
}
display.setCurrent(resumeScreen);
}

For handling notification that a message arrived, we will write notifyIncomingMessage method that will take MessageConnection as argument.


public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
done = false;
thread = new Thread(this);
thread.start();
}
}
Do remember that we are writing a multi threaded SMS MIDLet. The MIDLet signature reads like:

Java Code:
public class SMSReceive extends MIDlet
implements CommandListener, Runnable, MessageListener {
...
}

Lets define the run method:


public void run() {

try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
content.setTitle("From: " + senderAddress);
if (msg instanceof TextMessage) {
content.setString(((TextMessage)msg).getPayloadText());
} else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage)msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int)data & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
content.setString(buf.toString());
}
content.addCommand(replyCommand);
display.setCurrent(content);
}
} catch (IOException e) {
 e.printStackTrace();
}
}
The method is used to read the SMS message. If the message is a text message then things are simple. In the other case we have to read the message in a byte array.
In this post, I will present pauseApp and destroyApp methods. You are supposed to write these in your application. Do revise MIDlet life cycle for better understanding.



Pause signals the thread to stop by clearing the thread field. If stopped before done with the iterations it will be restarted from scratch later.

Java Code:
public void pauseApp() {
done = true;
thread = null;
resumeScreen = display.getCurrent();
}
Destroy must cleanup everything. The thread is signaled to stop and no result is produced.

Java Code:
public void destroyApp(boolean unconditional) {
done = true;
thread = null;
if (smsconn != null) {
try {
smsconn.close();
} catch (IOException e) {
// Ignore any errors on shutdown
}
}
}
This is the final part of "Writing MIDlet for SMS ". This post presents commandAction method which is a command listener.
More...

The following methiod responds to commands for example exit, reply etc.
Java Code:
public void commandAction(Command c, Displayable s) {
try {
if (c == exitCommand || c == Alert.DISMISS_COMMAND) {
destroyApp(false);
notifyDestroyed();
} else if (c == replyCommand) {
reply();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
// Allow the user to reply to the received message
Java Code:
private void reply() {
// remove the leading "sms://" for diplaying the destination address
String address = senderAddress.substring(6);
String statusMessage = "Sending message to " + address + "...";
sendingMessageAlert.setString(statusMessage);
sender.promptAndSend(senderAddress);
}
I hope you have gone through all parts of "Writing MIDlet for SMS". Put the code together and try it yourself. Do some experiments and explore more. Remember, you will learn a lot while doing experiments.

Happy coding!!
Vivane likes this.

Submit "Writing MIDlet for SMS" to Facebook Submit "Writing MIDlet for SMS" to Digg Submit "Writing MIDlet for SMS" to del.icio.us Submit "Writing MIDlet for SMS" to StumbleUpon Submit "Writing MIDlet for SMS" to Google

Tags: api, midletj2me, sms Add / Edit Tags
Categories
Java ME

Comments