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