Java Reference
In-Depth Information
Creating an Independent Receive Thread
SMSMIDlet
actually uses a separate receive thread to process incoming messages. This thread
will also set the
ImageItem
of the GUI with a different
Image
depending on incoming SMS messages.
The
startReceive()
method in Listing 11-1 contains the code that starts the receive thread.
The
run()
method contains the logic of the receive thread. The blocking
receive()
call is used
in this case. The
mEndNow boolean
flag stops the thread when the application is destroyed; see
the
destroyApp()
implementation.
The receive thread opens a server mode
MessageConnection
on port
1234
. When there are
no incoming messages, the receive thread is blocked in one of the
receive()
methods. Upon
receipt of a message, the text payload is extracted and compared to “red” or “blue”. Then
Display.callSerially()
updates the image shown on the GUI. Two helper classes,
SetRed
and
SetBlue
, are used when calling this method.
Sending SMS Messages
Listing 11-2 shows the class, called
Sender
, that is used to send SMS messages.
SMSMIDlet
main-
tains an instance of this class called
mSender
. The instance is used to send SMS messages when
the user selects either
Send Red
or
Send Blue
from the menu.
Listing 11-2.
Sending SMS Message with Sender
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.io.IOException;
public class Sender implements Runnable {
private static Sender inst = new Sender();
private Sender() {
}
public static Sender getInstance() {
return inst;
}
private String mReceiver = null;
private String mPort = null;
private String msgString = null;
private boolean mSending = false;
public void sendMsg(String rcvr, String port, String msgText) {
if (mSending) return;
mReceiver = rcvr;
mPort = port;
msgString = msgText;
Thread th = new Thread(this);
th.start();
}
Search WWH ::
Custom Search