19.5 Receiving Messages
To receive messages, create a MessageConnection using a messaging connection string without a destination address. For example, to receive SMS messages on port 50,000, use this connection string:
To receive MMS messages for the com.jonathanknudsen.Hermes application identifier, use this connection string:
Of course, you won't catch most messages with a live MessageConnection. Instead, you will put your MIDlet in the push registry, most likely with a static registration in the MIDlet suite descriptor. If this all sounds like gobbledygook, go back to Chapter 6 and read slower.
Picking up incoming messages is a lot like retrieving incoming datagrams or incoming socket connections. There are two ways to do this, both of which involve an additional thread that listens for incoming messages.
The first method is to create a thread that loops on calling MessageConnection's receive() method. This works pretty well, except that your thread is blocked at receive() until something comes in.
The second method is to use a MessageListener. You supply the listener and register it with the MessageConnection. Whenever a message arrives, your listener's notifyIncomingMessage() is called. Then you go ahead and call receive(), knowing full well that there really is a message waiting.
Unfortunately, it's not quite that simple, because you should not call receive() from the same system thread that calls notifyIncomingMessage(). Remember, when the system invokes one of your callback methods, you should respect its thread and do your own work in your own threads.
It's possible to set up a MessageListener in a rational way using wait() and notify(), but it's not trivial. The example later in this chapter includes such a listener.
MessageConnection gives you a Message when you call receive(), so you might have to do instanceof tests and casts if you're not sure what kind of message you are expecting.