Implement the MessageListener interface
You can use the
MessageListener interface to receive messages that are
sent by a
NonBlockingSenderDestination object, or push messages
that are sent from a push initiator.
-
Import the required classes and interfaces.
import net.rim.device.api.io.messaging.*;
import java.io.IOException;
import java.io.InputStream;
-
Define a class that implements the
MessageListener interface.
public class MyMessageListener implements MessageListener {
-
Implement
onMessage().
public void onMessage(Destination dest, Message incomingMessage)
{
-
Initialize a
String variable to hold the response data.
String payload = null;
-
If the response is a
ByteMessage object, retrieve the response as a
String and assign it to
payload.
if (incomingMessage instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) incomingMessage;
payload = (String) reply.getStringPayload();
}
-
If the response is a
StreamMessage, retrieve the response as an
InputStream object.
else if(incomingMessage instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) incomingMessage;
InputStream is = reply.getStreamPayload();
-
If the response is small, convert the contents of the stream
into a
byte array.
byte[] data = null;
try
{
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e)
{
// process the error
}
-
If the conversion was successful, convert the
byte array to a
String and assign it to
payload.
if(data != null)
{
payload = new String(data);
}
}
-
If
payload contains data, display it.
if(payload!=null)
{
synchronized(Application.getEventLock())
{
UiApplication.getUiApplication().pushScreen
(new HTTPOutputScreen(payload));
}
}
After you finish:
Implement
onMessageCancelled() and
onMessageFailed() to process other notifications.
For a complete code sample, see "Code sample:
Request data using a NonBlockingSenderDestination object"
Was this information helpful? Send us your comments.