如何起動一個應用程序在收到短信時

How to cell phone automatically active a J2ME application when receives a special message? WMA(Wireless message API) and Push Registry of MIDP 2.0 had provided all available methods.

Firstly, you must specify a port number in a J2ME application to receive message. For example:
String smsPort = "7777";
String smsConnection = "sms://:" + smsPort;
MessageConnection smsconn;

try {
 smsconn = (MessageConnection) Connector.open(conn);
} catch (IOException x) {
 //...
}

And, you need to know the format of message specified port number either. It is a text message included a UDH header. The UDH header is "060504<Destinating Port>(octets)<Originating Port>(octets)". If you have a NowSMS gateway(http://www.nowsms.com), you can easily use a URL of NowSMS to send out this message. The URL is http://<NowSMS gateway IP address>:<Port Number>/?phone=<Cell Phone Number>&udh=0605041E611E61&text=<Message content>. For detail of message PDU, you can use a tool of port monitor to catch them. After you send out this message, if the J2ME application of destinating cell phone is running, it will can receive this message.
 
To automatically active a J2ME application when it isn't running, you have to use PushRegistry method to register this event in J2ME program. I will provide a complete code for your reference.

Currently, this J2ME application isn't supported by all cell phone. It need Midlet 2.0 and WMAPI. You can find a available device list on http://www.j2mepolish.org/devices/midp2.html
 
Informative Reference:
"The MIDP 2.0 Push Registry" URL: http://developers.sun.com/techtopics/mobility/midp/articles/pushreg/
"Wireless Messaging API (WMA); JSR 120, JSR 205" URL: http://java.sun.com/products/wma/index.jsp
"The Wireless Messaging API" URL: http://developers.sun.com/techtopics/mobility/midp/articles/wma/index.html
 
A complete message receiver of J2ME, for Example: (BTW, when this program is launched again in J2ME wireless Toolkit 2.2, it will catch an IOException. I ignored it. If u know why, pls tell me. Thanks)
package SMSReceiver;
/**
 * <p>Title: SMS receiver</p>
 *
 * <p>Description: </p>
 *
 * </p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * [email protected]
 * @version 1.0
 */

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;

import java.io.IOException;

public class SMSReceiver extends MIDlet
    implements CommandListener, Runnable, MessageListener{

  /** user interface command for indicating Exit request. */
  Command exitCommand  = new Command("Exit", Command.EXIT, 2);
  /** user interface text box for the contents of the fetched URL. */
  Alert content;
  /** current display. */
  Display display;
  /** instance of a thread for asynchronous networking and user interface. */
  Thread thread;
  /** Flag to signal end of processing. */
  boolean done;
  /** The port on which we listen for SMS messages */
  String smsPort;
  /** SMS message connection for inbound text messages. */
  MessageConnection smsconn;
  /** Current message read from the network. */
  Message msg;
  /** Address of the message's sender */
  String senderAddress;
  /** The screen to display when we return from being paused */
  Displayable resumeScreen;

  private boolean readMessages = true;

  private int pendingMessages;

  String smsConnection;

  String []connections;

  public SMSReceiver() {
    smsPort = "7777"; //getAppProperty("SMS-Port");

    display = Display.getDisplay(this);

    content = new Alert("SMS Receive");
    content.setTimeout(Alert.FOREVER);
    content.addCommand(exitCommand);
    content.setCommandListener(this);
    //content.setString("Receiving...");
    content.setString("Waiting for SMS on port " + smsPort + "...");

    resumeScreen = content;

    smsConnection = "sms://:" + smsPort;

    connections = PushRegistry.listConnections(true);
    int n = connections.length;
    if( n == 0 ) {
      if(!openAndregisterConn(smsConnection))
        return;
    } else {
      boolean isFound = false;

      for(int ccnt=0; ccnt < connections.length; ccnt++) {
        if(connections[ccnt].indexOf(smsConnection) >= 0) {
          isFound = true;
          break;
        }
      }

      if(!isFound) {
        if(!openAndregisterConn(smsConnection))
          return;
      }
    }

  }

  public boolean openAndregisterConn(String conn)
  {
    try {
      smsconn = (MessageConnection) Connector.open(conn);
      PushRegistry.registerConnection(conn, "SMSReceiver.SMSReceiver", "*");
    } catch (IOException x) {
      x.printStackTrace();
      return false;
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
      return false;
    }
    return true;
  }

  /**
   * Start creates the thread to do the MessageConnection receive
   * text.
   * It should return immediately to keep the dispatcher
   * from hanging.
   */
  public void startApp() {
    /** SMS connection to be read. */

    /** Open the message connection. */
    if (smsconn == null) {
      connections = PushRegistry.listConnections(true);
      if (connections.length > 0) {
        // There is a pending datagram that can be received.
        for(int ccnt=0; ccnt < connections.length; ccnt++) {
          if(connections[ccnt].indexOf(smsConnection) >= 0)
            try {
              smsconn = (MessageConnection)
                  Connector.open(connections[ccnt]);
            } catch (IOException ioe) {
              ioe.printStackTrace();
            }
            break;
        }
      } else {
        // There are not any pending datagrams, but open
        // the connection for later use.
        connections = PushRegistry.listConnections(false);
        if (connections.length > 0) {
          for(int ccnt=0; ccnt < connections.length; ccnt++) {
            if(connections[ccnt].indexOf(smsConnection) >= 0) {
              try {
                smsconn = (MessageConnection)Connector.open(connections[ccnt]);
              } catch (IOException ioe) {
                ioe.printStackTrace();
              }
              break;
            }
          }
        }
      }
    }

    done = false;
    thread = new Thread(this);
    thread.start();
    content.setString("Waiting for SMS on port " + smsPort + "...");
    display.setCurrent(resumeScreen);
  }

  /**
   * Notification that a message arrived.
   * @param conn the connection with messages available
   */
  public void notifyIncomingMessage(MessageConnection conn) {
    if (thread == null) {
      done = false;
      thread = new Thread(this);
      thread.start();
    }
  }

  /** Message reading thread. */
  public void run() {
      /** Check for sms connection. */
    try {
      msg = smsconn.receive();
      if (msg != null) {
        senderAddress = msg.getAddress();
        content.setTitle("From: " + senderAddress);

        if (msg instanceof TextMessage) {
          content.setString( ( (TextMessage) msg).getPayloadText());
        } else {
          StringBuffer buf = new StringBuffer();
          byte[] data = ( (BinaryMessage) msg).getPayloadData();

          for (int i = 0; i < data.length; i++) {
            int intData = (int) data[i] & 0xFF;

            if (intData < 0x10) {
              buf.append("0");
            }

            buf.append(Integer.toHexString(intData));
            buf.append(' ');
          }

          content.setString(buf.toString());
        }
        //content.addCommand(replyCommand);
        display.setCurrent(content);
      }
    } catch (IOException e) {
      // e.printStackTrace();
    }

  }

  /**
   * Pause signals the thread to stop by clearing the thread field.
   * If stopped before done with the iterations it will
   * be restarted from scratch later.
   */
  public void pauseApp() {
    done = true;
    thread = null;
    resumeScreen = display.getCurrent();
  }

  /**
   * Destroy must cleanup everything.  The thread is signaled
   * to stop and no result is produced.
   * @param unconditional true if a forced shutdown was requested
   */
  public void destroyApp(boolean unconditional) {
    done = true;
    thread = null;
    if (smsconn != null) {
      try {
          smsconn.close();
      } catch (IOException e) {
          // Ignore any errors on shutdown
      }
    }
  }

  /**
   * Respond to commands, including exit
   * @param c user interface command requested
   * @param s screen object initiating the request
   */
  public void commandAction(Command c, Displayable s) {
    try {
      if (c == exitCommand || c == Alert.DISMISS_COMMAND) {
        destroyApp(false);
        notifyDestroyed();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章