Different ways to listen for SMS messages

by Retired on ‎02-16-2010 01:30 PM - edited on ‎04-24-2013 10:34 AM by Retired (16,552 Views)

Summary

 

This article applies to the following:

  • BlackBerry® Device Software 4.0 and later
  • BlackBerry Java® Development Environment (JDE) 4.0 and later

 

Details

 

The following approaches can be used in applications to listen for all incoming Short Message Service (SMS) messages on the BlackBerry smartphone:

 

1. Use a DatagramConnection from the javax.microedition.io package

 

 

DatagramConnection _dc =
(DatagramConnection)Connector.open("sms://");
for(;;)
{
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
byte[] bytes = d.getData();
String address = d.getAddress();
String msg = new String(bytes);
System.out.println( "Received SMS text from " + address + " : " + msg);
}


 

 

2. a) Use a MessageConnection from the javax.wireless.messaging package

 

 

MessageConnection _mc = (MessageConnection)Connector.open("sms://:0"); 

for(;;)
{
Message m = _mc.receive();
String address = m.getAddress();
String msg = null;
if ( m instanceof TextMessage )
{
TextMessage tm = (TextMessage)m;
msg = tm.getPayloadText();
}
else if (m instance of BinaryMessage) {

StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) m).getPayloadData();
// convert Binary Data to Text
msg = new String(data, "UTF-8");
}
else
System.out.println("Invalid Message Format");
System.out.println("Received SMS text from " + address + " : " + msg);
}


 

 

b) Use a MessageConnection by implementing the javax.wireless.messaging.MessageListener interface.

 

 

MessageConnection _mc = (MessageConnection)Connector.open("sms://:0"); 
_mc.setMessageListener(this);



public void notifyIncomingMessage(MessageConnection conn) {
Message m = _mc.receive();
String address = m.getAddress();
String msg = null;
if ( m instanceof TextMessage )
{
TextMessage tm = (TextMessage)m;
msg = tm.getPayloadText();
}
else if (m instanceof BinaryMessage) {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) m).getPayloadData();

// convert Binary Data to Text
msg = new String(data, "UTF-8");
}
else
System.out.println("Invalid Message Format");
System.out.println("Received SMS text from " + address + " : " + msg);
}