Android 广播获取短信内容

 

一、创建广播监听短信接收器

public  BroadcastReceiver borad = new  BroadcastReceiver(){

   @Override
   public void onReceive(Context context, Intent intent) {
    //super.onReceive(context, intent);
    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
     Log.v(TAG, ">>>>>>>onReceive start");
     // 第一步、获取短信的内容和发件人
     StringBuilder body = new StringBuilder();// 短信内容
     StringBuilder number = new StringBuilder();// 短信发件人
     Bundle bundle = intent.getExtras();
     if (bundle != null) {
      Object[] _pdus = (Object[]) bundle.get("pdus");
      SmsMessage[] message = new SmsMessage[_pdus.length];
      for (int i = 0; i < _pdus.length; i++) {
       message[i] = SmsMessage
         .createFromPdu((byte[]) _pdus[i]);
      }
      for (SmsMessage currentMessage : message) {
       body.append(currentMessage.getDisplayMessageBody());
       String curNumber = number.toString();
       if (!curNumber.equals(currentMessage
         .getDisplayOriginatingAddress()))
        number.append(currentMessage
          .getDisplayOriginatingAddress());
      }
      String smsBody = body.toString();
      String smsNumber = number.toString();
      if (smsNumber.startsWith("+86")) {
       smsNumber = smsNumber.substring(3);
      }
      // 第二步:确认该短信内容是否满足过滤条件
      if (smsNumber.equals("11888") || smsNumber.equals("1069030011888")) 
       Log.v(TAG, "sms_number.equals(11888)" + smsBody);
       int index = smsBody.indexOf("您本次操作的验证码为:");
       if (index != -1){
        String smsCode = smsBody.substring(index + 11,index + 17);
        //authCode.setText(smsCode);
        Message msg = new Message();
        msg.what = SMSCODE_OK;
        msg.obj = smsCode;
        handler.sendMessage(msg);
       }     
      }
     }
     Log.v(TAG, ">>>>>>>onReceive end");

    }
   }
  };

二、注册广播

/**
 * 注册接收短信广播
 */
  
 private  void regeditBroad(Context context){
  IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
  intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
  context.registerReceiver(borad, intentFilter);
  
 }

 

三、Handler操作UI控件

private  Handler handler = new Handler(){
  
  public void handleMessage(Message msg) {
   
   switch (msg.what) {
   // 自动填充短信验证码
   case SMSCODE_OK:
    String sms = (String) msg.obj;
    System.out.println("截取到短信验证码: " + sms);
    if (sms != null && !sms.equals("")) {
     authCode.setText(sms);
     getSms.setEnabled(true);
     getSms.setText(mcontext.getString(R.string.m_hint_obtain));
    }
    //注销接收短信广播
    destoryBroad();
    break;

 

/**
 * 销毁短信广播
 */
  
 private void destoryBroad() {
  
  if (borad != null) {
   mcontext.unregisterReceiver(borad);
  }
 }

你可能感兴趣的:(android)