View RSS Feed

My Java Tips

Sending SMS (snippet)

Rate this Entry
by , 11-22-2011 at 06:22 PM (1573 Views)
This post presents a snippet for sending short text messages from J2Me applications.

The package provides an API for the Short Message Service Messaging system and allows MIDlet to access SMS functionality on a GSM mobile device. You need javax.wireless.messaging.sms.send premission to send SMS messages from your J2ME application. The sample code is presented below:

Java Code:
sender = (MessageConnection)"sms://");
TextMessage t = (TextMessage)sender.newMessage(MessageConnection.TEXT_MESSAGE);
t.setAddress("sms://" + contactNumber);
A TextMessage object is used to send a message containing a java.lang.String. It inherits from the Message interface and adds a text message body. This message type can be used to transport text-based messages, including those with XML content. (Source: Sun Java)

The server application will wait for the incoming messages. It should be able to read text and binary messages and should be able to store those. The following code segment will serve the purpose.

Java Code:
public void notifyIncomingMessage(MessageConnection conn) {

        Message msg = null;
        //  Try reading (maybe block for) a message
        try {
            msg = conn.receive();
        catch (Exception e) {
            // Handle reading errors
            System.out.println("processMessage.receive " + e);
        // Process the received message
        if (msg instanceof TextMessage) {
            TextMessage tmsg = (TextMessage)msg;
    		msgReceived = tmsg.getPayloadText();
            // process received message
            if (msg instanceof BinaryMessage) {
                BinaryMessage bmsg = (BinaryMessage)msg;
                byte[] data = bmsg.getPayloadData();
                //  Handle the binary message...
				msgReceived = data.toString();



Submit "Sending SMS (snippet)" to Facebook Submit "Sending SMS (snippet)" to Digg Submit "Sending SMS (snippet)" to Submit "Sending SMS (snippet)" to StumbleUpon Submit "Sending SMS (snippet)" to Google