监听SMS的三种方法

来源:互联网 发布:网络大专和函授区别 编辑:程序博客网 时间:2024/04/29 08:27

BlackBerry上接受SMS有几种方法:

  1. 使用 DatagramConnection (包:javax.microedition.io)

    DatagramConnection _dc =
         (DatagramConnection)Connector.open("sms://");
                for(;;)
            {
                   Datagram d = _dc.newDatagram(_dc.getMaximumLength());
                   _dc.receive(d);
                   byte[] bytes = d.getData();
                   String address = d.getAddress();
                   String msg = new String(bytes);
                   System.out.println( "Received SMS text from " + address + " : " + msg);
             }

  2. a) 使用MessageConnection(包javax.wireless.messaging)

    MessageConnection _mc = (MessageConnection)Connector.open("sms://:0");

    for(;;)
    {
    Message m = _mc.receive();
    String address = m.getAddress();
    String msg = null;
         if ( m instanceof TextMessage )
         {
              TextMessage tm = (TextMessage)m;
              msg = tm.getPayloadText();
         }
         else if (m instance of BinaryMessage) {

              StringBuffer buf = new StringBuffer();
              byte[] data = ((BinaryMessage) m).getPayloadData();
              // convert Binary Data to Text
              msg = new String(data, "UTF-8");
         }
         else
              System.out.println("Invalid Message Format");
              System.out.println("Received SMS text from " + address + " : " + msg);
    }

    b)使用 MessageConnection 的另一种方法:实现接口javax.wireless.messaging.MessageListener

    MessageConnection _mc = (MessageConnection)Connector.open("sms://:0");
    _mc.setMessageListener(this);



    public void notifyIncomingMessage(MessageConnection conn) {
         Message m = _mc.receive();
         String address = m.getAddress();
         String msg = null;
              if ( m instanceof TextMessage )
              {
                   TextMessage tm = (TextMessage)m;
                   msg = tm.getPayloadText();
              }
              else if (m instance of BinaryMessage) {
                   StringBuffer buf = new StringBuffer();
                   byte[] data = ((BinaryMessage) m).getPayloadData();

                   // convert Binary Data to Text
                   msg = new String(data, "UTF-8");
              }
              else
                   System.out.println("Invalid Message Format");
                   System.out.println("Received SMS text from " + address + " : " + msg);
    }