Sending SMS (snippet)

29 April 2008

This post presents a snippet for sending short text messages from J2Me applications.

The com.sun.midp.io.j2me.sms 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:

sender = (MessageConnection)Connector.open("sms://"); 
TextMessage t = (TextMessage)sender.newMessage(MessageConnection.TEXT_MESSAGE); 
t.setPayloadText(message); 
t.setAddress("sms://" + contactNumber); 
sender.send(t);

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.

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();
        }
        else 
		{
            // process received message
            if (msg instanceof BinaryMessage) {
                BinaryMessage bmsg = (BinaryMessage)msg;
                byte[] data = bmsg.getPayloadData();
                //  Handle the binary message...
				msgReceived = data.toString();
 
       }
 
}

del.icio.us:Sending SMS (snippet)  digg:Sending SMS (snippet)  spurl:Sending SMS (snippet)  wists:Sending SMS (snippet)  simpy:Sending SMS (snippet)  newsvine:Sending SMS (snippet)  blinklist:Sending SMS (snippet)  furl:Sending SMS (snippet)  reddit:Sending SMS (snippet)  fark:Sending SMS (snippet)  blogmarks:Sending SMS (snippet)  Y!:Sending SMS (snippet)  smarking:Sending SMS (snippet)  magnolia:Sending SMS (snippet)  segnalo:Sending SMS (snippet)  gifttagging:Sending SMS (snippet)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Sending SMS (snippet)

One Response to “Sending SMS (snippet)”

  1. mobi yard Says:

    wow, that was great post.. thanx for sharing the same…
    Mobile Social networking

Leave a Reply