监听SMS的三种方法

BlackBerry上接受SMS有几种方法:

    • 使用 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);
               }

    • 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);
      }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值