自動擷取簡訊驗證碼,擷取簡訊驗證碼
1.自訂監聽類
/** * 簡訊監聽器,用於自動填滿驗證碼*/public class SMSContentObserver extends ContentObserver {public final String SMS_URI_INBOX = "content://sms/inbox";//收信箱private Activity activity = null;private String smsContent = "";//驗證碼private EditText verifyText = null;//驗證碼編輯框private String SMS_ADDRESS_PRNUMBER = "10690329013589";//短息發送供應商private String smsID = "";//簡訊觀察者 收到一條簡訊時 onchange方法會執行兩次,所以比較簡訊id,如果一致則不處理public SMSContentObserver(Activity activity, Handler handler, EditText verifyText) {super(handler);this.activity = activity;this.verifyText = verifyText;}@Overridepublic void onChange(boolean selfChange) {super.onChange(selfChange);Cursor cursor = null;// 游標// 讀取收件匣中指定號碼的簡訊cursor = activity.getContentResolver().query(Uri.parse(SMS_URI_INBOX),new String[]{"_id", "address", "body", "read"}, //要讀取的屬性"address=? and read=?", //查詢條件是什麼new String[]{SMS_ADDRESS_PRNUMBER, "0"},//查詢條件賦值"date desc");//排序if (cursor != null) {cursor.moveToFirst();if (cursor.moveToFirst()) {//比較和上次接收到簡訊的ID是否相等if (!smsID.equals(cursor.getString(cursor.getColumnIndex("_id")))) {String smsbody = cursor.getString(cursor.getColumnIndex("body"));//用Regex匹配驗證碼Pattern pattern = Pattern.compile("[0-9]{6}");Matcher matcher = pattern.matcher(smsbody);if (matcher.find()) {//匹配到6位的驗證碼smsContent = matcher.group();if (verifyText != null && null != smsContent && !"".equals(smsContent)) {verifyText.requestFocus();//擷取焦點verifyText.setText(smsContent);//設定文本verifyText.setSelection(smsContent.length());//設定游標位置}}smsID = cursor.getString(cursor.getColumnIndex("_id"));}}}}}
2.在登入頁面事件化監聽類
//執行個體化簡訊監聽器SMSContentObserver mObserver = new SMSContentObserver(getActivity(), new Handler(), mEt_auth_code);// 註冊簡訊變化監聽mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mObserver);
3.聲明讀取簡訊許可權
<uses-permission android:name="android.permission.RECEIVE_SMS" /><uses-permission android:name="android.permission.READ_SMS" /><uses-permission android:name="android.permission.WRITE_SMS" />
4.為了防止記憶體流失,記得登出監聽
@Overridepublic void onDestroy() {super.onDestroy(); //登出簡訊監聽 mContext.getContentResolver().unregisterContentObserver(mObserver);}
小結:
去簡訊庫擷取簡訊比較不容易被攔截