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.
  1. Import the required classes and interfaces.
    import net.rim.device.api.io.messaging.*;
    
    import java.io.IOException;
    import java.io.InputStream;
  2. Define a class that implements the MessageListener interface.
    public class MyMessageListener implements MessageListener {
  3. Implement onMessage().
        public void onMessage(Destination dest, Message incomingMessage)
        {
  4. Initialize a String variable to hold the response data.
            String payload = null;
  5. 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();
            }
  6. 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();
    1. 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
                  }
    2. If the conversion was successful, convert the byte array to a String and assign it to payload.
                  if(data != null)
                  {
                      payload = new String(data);
                  }
              }
  7. 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.