This class was working great fro sending sms messages until I added a message listener, know it throws an IOException every time I start the thread. Any Ideas, how to fix this ?
Below is the class and the message listener:
Code:
private static final class SmsMessage
{
private String _address;
private String _msg;
public SmsMessage(String address, String msg)
{
_address = address;
_msg = msg;
}
public Message toMessage(MessageConnection mc)
{
TextMessage m = (TextMessage)mc.newMessage(MessageConnection.TEXT_MESSAGE,"sms://" + _address);
m.setPayloadText(_msg);
return m;
}
} // SmsMessage
private final class SendThread extends Thread
{
private static final int TIMEOUT = 500; // ms
private Vector _msgs = new Vector(10); // Queue of 10
private volatile boolean _start = false;
// queue requests
public synchronized void send(String address, String msg)
{
_start = true;
_msgs.addElement(new SmsMessage(address, msg));
}
public synchronized void stop()
{
_stop = true;
try {
if ( _mc != null ){
_mc.close();
}
} // catch (IOException e ) {
catch (Throwable t) {
t.printStackTrace();
System.exit(0);
}
}
public void run()
{
try {
//closed by the stop() method
_mc = (MessageConnection)Connector.open("sms://");
if (_mc != null)
{
// set a listener to trap outgoing sms messages
_mc.setMessageListener(new OutboundSMSListener());
}
for(;;)
{
while( !_start && !_stop)
{
try {
sleep(TIMEOUT);
} // catch (InterruptedException e) {
catch (Throwable t) {
t.printStackTrace();
System.exit(0);
}
}
if ( _stop )
{
return;
}
while(true)
{
try {
SmsMessage sms = null;
synchronized (this)
{
if ( !_msgs.isEmpty() )
{
sms = (SmsMessage)_msgs.firstElement();
// take it out of the queue once we sent it
_msgs.removeElement(sms);
}
else
{
_start = false;
break;
}
}
_mc.send(sms.toMessage(_mc));
} // catch (IOException e) {
catch (Throwable t) {
t.printStackTrace();
System.exit(0);
}
}
}
} // catch (IOException e)
catch (Throwable t) {
t.printStackTrace();
System.exit(0);
}
}
} // SendThread
private static final class OutboundSMSListener implements OutboundMessageListener
{
public void notifyIncomingMessage(MessageConnection messageconnection)
{
// we don't care about incoming sms messages right now
}
public void notifyOutgoingMessage(Message message)
{
Dialog.alert("Detected An Outgoing SMS Event");
}
}