自动拦截短信实际上就是在系统注册一个BroadcastReceiver,然后通过设置拦截短信的:
1 filter.addAction("android.provider.Telephony.SMS_RECEIVED"); 2 filter.setPriority(Integer.MAX_VALUE);
即可拦截你所需要的短信了,拦截短信可能需要设置下最新的时间,这个问题我也考虑到了,下一步是重写onrecever方法:
1 smsReceiver = new BroadcastReceiver() { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 Object[] objs = (Object[]) intent.getExtras().get("pdus"); 5 for (Object obj : objs) { 6 byte[] pdu = (byte[]) obj; 7 SmsMessage sms = SmsMessage.createFromPdu(pdu); 8 String message = sms.getMessageBody(); 9 Log.d("短信内容", "message:" + message); 10 // 短息的手机号。。+86开头? 11 String from = sms.getOriginatingAddress(); 12 Log.d("短信来源", "from :" + from); 13 // Time time = new Time(); 14 // time.set(sms.getTimestampMillis()); 15 // String time2 = time.format3339(true); 16 // Log.d("logo", from + " " + message + " " + time2); 17 // strContent = from + " " + message; 18 // handler.sendEmptyMessage(1); 19 if (!TextUtils.isEmpty(from)) { 20 String code = patternCode(message); 21 if (!TextUtils.isEmpty(code)) { 22 Message msg=new Message(); 23 msg.what=1; 24 Bundle bundle=new Bundle(); 25 bundle.putString("messagecode", code); 26 msg.setData(bundle); 27 handler.sendMessage(msg); 28 } 29 } 30 } 31 } 32 };
最后注册下broadcastrecevier,注意我们怎么捕捉到短信的那个验证码呢,大家肯定想到了截取字符串,但是这种方式比较笨拙,我这里用的正则表达式截取,String patternCoder = "(?<!\d)\d{6}(?!\d)"。