Java Reference
In-Depth Information
A Nonblocking Approach to Receiving
SMS Messages
MessageConnection
supports a nonblocking, event listener-based way for receiving SMS
messages. To use this, you will need to do the following:
Register a
MessageListener
with the
MessageConnection
.
1.
Handle the callback on the
notifyIncomingMessage()
method of the
MessageListener
interface.
2.
First, add a
MessageListener
using the
setMessageListener()
method on the
MessageConnection
:
public void setMessageListener(MessageListener lis) throws IOException;
The object that you register as a listener must implement the
MessageListener
interface.
Only one listener can be registered at a time for a connection; any new registration will displace
the old one. The
MessageListener
interface has a single callback method:
public notifyIncomingMessage(MessageConnection conn);
The callback is performed by WMA on a system thread, and the
notifyIncomingMessage()
method must return as soon as possible. This means that any work should be performed by
another thread. In fact, WMA mandates that even the call to the
receive()
method (to pick up
the incoming message) must be performed in another thread. This will require careful concurrent
programming using Java's synchronization primitives. In addition, the WMA implementation
may perform simultaneous callback on multiple threads if messages are arriving concurrently.
This means that you need to be careful to synchronize access to any variables outside of your
thread's
run()
method.
Even though this nonblocking approach is attractive conceptually, it is often simpler to
use the blocking receive call alternative. The final example in this chapter (see Listing 11-3)
shows some code using this nonblocking approach.
Examining Message Headers
In addition to the binary or text payload, other interesting information appears in the message
header.
You can get access to the address information using the following methods on the
Message
interface:
public String getAddress();
public void setAddress(String addr);
Search WWH ::
Custom Search