Sending SMS (snippet)
29 April 2008This 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(); } }
Related Posts:
- Writing MIDlet for SMS - VI
- Accessing Resources in a JAR File
- GPS location / Cell id / Placing a call
- The Intercepting Filter (I)
- Record Management System (III)
- Working with the DOM parser
- Reading RSS using Informa API
- Transformations API for XML - IV
- Prepared statement pooling (JDBC 3.0)
- Java Compiler API (brief intro)
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)