Sending SMS (snippet)
by , 11-22-2011 at 05:22 PM (724 Views)
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:
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)Java Code:sender = (MessageConnection)Connector.open("sms://"); TextMessage t = (TextMessage)sender.newMessage(MessageConnection.TEXT_MESSAGE); t.setPayloadText(message); t.setAddress("sms://" + contactNumber); sender.send(t);
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(); } else { // process received message if (msg instanceof BinaryMessage) { BinaryMessage bmsg = (BinaryMessage)msg; byte[] data = bmsg.getPayloadData(); // Handle the binary message... msgReceived = data.toString(); } }









Email Blog Entry
License4J 4.0
05-22-2013, 12:23 AM in Java Software