用到ContentObserver的觀察者模式
1端礼、創(chuàng)建短信觀察者
public class SmsObserver extends ContentObserver {
private Context mContext;
private Handler mHandler;
private String code = "";
public SmsObserver(Context context, Handler handler) {
super(handler);
this.mContext = context;
mHandler = handler;
}
/**
* 需要觀察的被觀察對(duì)象發(fā)生變化的時(shí)候會(huì)自動(dòng)調(diào)用的函數(shù)
*
* @param selfChange 本身是否發(fā)生變化
* @param uri 相應(yīng)的Uri
*/
@Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
//第一遍執(zhí)行時(shí)短信還未寫(xiě)到數(shù)據(jù)庫(kù)中,所以忽略第一遍
if (uri.toString().equals("content://sms/raw")) {
return;
}
//讀取短信
//收件箱的uri
Uri inboxUri = Uri.parse("content://sms/inbox");
//游標(biāo)查詢數(shù)據(jù)庫(kù) date desc按日期倒敘排列
Cursor cursor = mContext.getContentResolver().query(inboxUri, null, null, null, "date desc");
if (cursor != null) {
if (cursor.moveToFirst()) {//將游標(biāo)移動(dòng)到第一條(判斷數(shù)據(jù)庫(kù)里是否有數(shù)據(jù))
String address = cursor.getString(cursor.getColumnIndex("address"));//收件人
String body = cursor.getString(cursor.getColumnIndex("body"));//具體內(nèi)容
//使用正則表達(dá)式對(duì)驗(yàn)證碼進(jìn)行提取
Pattern pattern = Pattern.compile("(\\d{5})");//提取短信中連續(xù)6個(gè)數(shù)字的內(nèi)容
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {//匹配
code = matcher.group(0);
mHandler.obtainMessage(ContactStateActivity.MESSAGE_CODE, code).sendToTarget();
}
}
cursor.close();
}
}
}
2冯乘、注冊(cè)
smsObserver = new SmsObserver(this, handler);
//當(dāng)短信的收件洽胶、發(fā)件發(fā)生變化時(shí)都會(huì)反映到這個(gè)uri上
Uri uri = Uri.parse("content://sms");
//注冊(cè)
getContentResolver().registerContentObserver(uri, true, smsObserver);
3、解注冊(cè)
@Override
protected void onPause() {
super.onPause();
getContentResolver().unregisterContentObserver(smsObserver);
}
4裆馒、獲得值更新UI
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==MESSAGE_CODE){
String code = (String) msg.obj;
etCodeNum.setText(code);
}
}
};
5姊氓、記得申請(qǐng)短信讀取權(quán)限(6.0以上要?jiǎng)討B(tài)活獲蓉で印)
<uses-permission android:name="android.permission.READ_SMS"/>
目前華為等手機(jī)有對(duì)短信驗(yàn)證碼的保護(hù),防止第三方竊取等他膳,可以先在短信設(shè)置里面關(guān)掉再試試响逢。