http://www-128.ibm.com/developerworks/wireless/library/wi-p2pmsg/
Send SMS messages
Sending messages with the WMA is very simple. You can send a message to an arbitrary phone number and/or an SMS port through a MessageConnection constructed for that destination, as shown in Listing 1.
Listing 1. Sending an SMS message
1 2 3 4 5 6 7 8 9 |
String addr = "sms://+123456789"; // Or: String addr = "sms://+123456789:1234"; MessageConnection conn = (MessageConnection) Connector.open(addr); TextMessage msg = (TextMessage) conn.newMessage( MessageConnection.TEXT_MESSAGE); msg.setPayloadText( "Hello World" ); conn.send(msg); |
We can also send out messages through a server connection, as shown in Listing 2.
Listing 2. Sending an SMS message via a server connection
1 2 3 4 5 6 7 8 |
MessageConnection sconn = (MessageConnection) Connector.open("sms://:3333"); TextMessage msg = (TextMessage) sconn.newMessage( MessageConnection.TEXT_MESSAGE); msg.setAddress("sms://+123456789:1234"); msg.setPayloadText( "Hello World" ); sconn.send(msg); |
If you choose to use a server connection to send your message, you gain a number of benefits:
The connection can be reused again and again.
The message contains the sender’s port number and phone number. Hence, it gives the recipient peer the opportunity to respond.
Receive SMS messages
To receive SMS messages in a Java application, we need to have a server MessageConnection listening at the message’s target port. The MessageConnection.receive() method blocks until a message is received or the connection is closed. We can loop the receive() method to automatically handle incoming messages when they arrive. Listing 3 illustrates a server loop that listens, receives, and replies to incoming SMS messages.
Listing 3. Receiving an SMS message and replying to it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
MessageConnection sconn = (MessageConnection) Connector.open("sms://:3333"); while (true) { Message msg = sconn.receive(); if (msg instanceof TextMessage) { TextMessage tmsg = (TextMessage) msg; String msgText = tmsg.getPayloadText(); // Construct the return message TextMessage rmsg = (TextMessage) sconn.newMessage( MessageConnection.TEXT_MESSAGE); rmsg.setAddress ( tmsg.getAddress() ); rmsg.setPayloadText( "Thanks!" ); sconn.send(rmsg); } else { // process the non-text message // maybe a BinaryMessage? } } |