实现方式思路:
1、系统有一个ContentObserver,可以在onChange(boolean selfChange, Uri uri)里过滤处理短信
2、必须要调用getContentResolver().registerContentObserver(uri, true, mObserver),注册之后才可以监听(ContentObserver才会生效)
实现步骤:目前是在Activity中实现
1、先知道系统短信url:Uri uri = Uri.parse("content://sms")
2、这里可以继承ContentObserver,重新一个SmsObserver类处理短信
3、创建一个内容观察对象:SmsObserver mObserver = new SmsObserver(this, mHandler, MSG_RECEIVED_CODE);这里只是用了Hnader进行处理接收验证码,也可以使用EventBus等进行处理消息传递
4、注册getContentResolver().registerContentObserver(uri, true, mObserver)
5、在opause()或onDestroy()中反注册getContentResolver().unregisterContentObserver(mObserver)
实现的关键源码:
1、Activity
private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == MSG_RECEIVED_CODE) { String code = (String) msg.obj; mEtUserVerificationCode.setText(code); } } };
mObserver = new SmsObserver(this, mHandler, MSG_RECEIVED_CODE); Uri uri = Uri.parse("content://sms"); getContentResolver().registerContentObserver(uri, true, mObserver);
2、SmsObserver类
public class SmsObserver extends ContentObserver { private Context mContext; private Handler mHandler; private int mReceivedCode = 1; public SmsObserver(Context context, Handler handler, int received_code) { super(handler); mContext = context; mHandler = handler; mReceivedCode = received_code; } @Override public void onChange(boolean selfChange, Uri uri) { super.onChange(selfChange, uri); String code = ""; if (uri.toString().equals("content://sms/raw")) { return; } Uri inboxUri = Uri.parse("content://sms/inbox"); Cursor c = mContext.getContentResolver().query(inboxUri, null, null, null, "date desc"); if (c != null) { if (c.moveToFirst()) { String address = c.getString(c.getColumnIndex("address")); String body = c.getString(c.getColumnIndex("body")); LogUtils.e("发件人为:" + address + "》》》》短信内容为:" + body); Pattern pattern = Pattern.compile("(\\d{4,6})"); Matcher matcher = pattern.matcher(body); if (matcher.find()) { code = matcher.group(0); LogUtils.e("验证码》》》" + code); ClipboardManager cmb = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); cmb.setText(code); mHandler.obtainMessage(mReceivedCode, code).sendToTarget(); } } c.close(); } } }
参考:https://blog.csdn.net/qq_31939617/article/details/77430688