import java.io.IOException; import javax.microedition.io.Connector; import javax.microedition.io.PushRegistry; import javax.wireless.messaging.Message; import javax.wireless.messaging.MessageConnection; import javax.wireless.messaging.MessageListener; import javax.wireless.messaging.TextMessage; import com.tim.util.DeployVar; public class MessageMonitor implements MessageListener, Runnable { public boolean ready = false; private MessageConnection msgConnection; private final String connection = "sms://:2365"; // 没啥大用 private MessageHandler msgHandler; private Thread thread; public MessageMonitor() { init(); } public void setMsgHandler(MessageHandler msgHandler) { this.msgHandler = msgHandler; } private void init() { String[] connections = PushRegistry.listConnections(true); int len = connections.length; if (len == 0) { if (!openAndregisterConn(connection)) { DeployVar.Log("openAndregisterConn Failed"); return; } } else { boolean isFound = false; for (int i = 0; i < connections.length; i++) { if (connections[i].indexOf(connection) >= 0) { isFound = true; break; } } if (!isFound) { if (!openAndregisterConn(connection)) { DeployVar.Log("openAndregisterConn Failed"); return; } } } DeployVar.Log("openAndregisterConn OK"); } public boolean openAndregisterConn(String connection) { try { msgConnection = (MessageConnection) Connector.open(connection); msgConnection.setMessageListener(this); } catch (IOException x) { DeployVar.Log("openAndregisterConn:" + x.getMessage()); x.printStackTrace(); return false; } try { PushRegistry.registerConnection(connection, "com.snda.page.MainMIDlet", "*"); } catch (Exception x) { DeployVar.Log("openAndregisterConn:" + x.getMessage()); x.printStackTrace(); return false; } return true; } public void notifyIncomingMessage(MessageConnection conn) { DeployVar.Log("notifyIncomingMessage rece"); thread = new Thread(this); thread.start(); } /** Message reading thread. */ public void run() { try { Message msg = msgConnection.receive(); if (msg != null) { String addr = msg.getAddress(); if (msg instanceof TextMessage) { // 只处理普通短信 String content = ((TextMessage) msg).getPayloadText(); msgHandler.handleMessage(addr, content); } } } catch (IOException e) { e.printStackTrace(); } } }