July 16, 2007
Short Message Service (SMS), commonly referred to as Text Messaging, allows cell phone users to send short, plain-text messages to each other. The Wireless Messaging API (WMA) is an optional Java ME package that provides programmatic support for messaging technologies such as SMS. In this article we will look at how to use WMA to send SMS messages.
The Wireless Messaging API can be found in the javax.wireless.messaging package. Sending of messages is handled by the MessageConnection class. MessageConnection objects are obtained by calling the open() method of the javax.microedition.io.Connector class with a URL string in the format:
protocol://address:port
For example:
sms://+12125551212:5000
For SMS, the address part represents the MSISDN of the destination; typically this is a telephone number with country code. The port number is application specific. If you want the default messaging application of the destination device to open the message, simply leave off the port number.
Below is sample code for sending a text message. Note that in a production application, you may want to spawn a new thread for running this code, as it involves a network call that could potentially block the user interface. Also, exception handling has been ommitted from this example for clarity.
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import javax.microedition.io.Connector;
import java.io.IOException;
public class SMSUtility {
public static void sendMessage(String msisdn, String text)
throws IOException {
// Open connection
MessageConnection con = (MessageConnection)
Connector.open("sms://+" + msisdn);
// Create new message
TextMessage message = (TextMessage)
con.newMessage(MessageConnection.TEXT_MESSAGE);
// Set text
message.setPayloadText(text);
// Send message
con.send(message);
// Close connection
con.close();
}
}
For more information about WMA, including other uses such as opening server connections, check out the following links:
Wireless Messaging API (WMA); JSR 120, JSR 205
Sun Java Wireless Toolkit: Using the Wireless Messaging API
Java ME Technical Articles: WMA
Filed under Java ME Development