Android自動填充簡訊驗證碼
阿新 • • 發佈:2018-12-12
前言
簡訊驗證碼獲取並自動填寫現在已經成為一個人性化App的標配了,這篇文章將實現一個簡訊驗證碼獲取並自動填寫的demo。其實就是讀取指定號碼的簡訊並提取出驗證碼,然後賦值給EditText顯示。
demo效果圖:
讀取簡訊
Android系統在接受到一條簡訊的時候會發出一條Action為android.provider.Telephony.SMS_RECEIVED的有序廣播,因此我們讀取簡訊的驗證碼只需要監聽這個廣播然後提取出簡訊中的驗證碼即可,如:
/** * Created by 程龍 on 2018/9/27. */ public class SMSBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "SMSBroadcastReceiver"; private OnReceiveSMSListener mOnReceiveSMSListener; public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(SMS_RECEIVED_ACTION)) { Object[] pdus = (Object[]) intent.getExtras().get("pdus"); for(Object pdu:pdus) { SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu); // 簡訊號碼 String sender = smsMessage.getDisplayOriginatingAddress(); Log.d(TAG,sender+""); //簡訊內容 String content = smsMessage.getDisplayMessageBody(); // 篩選 if ("簡訊傳送方號碼".equals(sender) && mOnReceiveSMSListener!= null) { Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(content); if(matcher.find()) { mOnReceiveSMSListener.onReceived(matcher.group()); } abortBroadcast(); } } } } /** * 回撥介面 */ public interface OnReceiveSMSListener { void onReceived(String message); } public void setOnReceiveSMSListener(OnReceiveSMSListener onReceiveSMSListener) { mOnReceiveSMSListener = onReceiveSMSListener; } }
程式碼註釋比較清楚,通過SmsMessage物件可以得到簡訊的傳送號碼,簡訊內容及相關資訊。當簡訊號碼為你要讀取的簡訊傳送方號碼時用正則表示式提取出簡訊內容的驗證碼,然後通過呼叫監聽器的回撥方法更新相應的UI。這裡只需將簡訊驗證傳送方號碼替換成相應的號碼即可,如“106903561008710”為騰訊雲註冊傳送的簡訊號碼。
通常,我們只會在註冊或登入頁面讀取簡訊驗證碼,所以,我們採用動態註冊廣播的方式註冊這個廣播,如:
// 註冊廣播 IntentFilter intentFilter = new IntentFilter(SMSBroadcastReceiver.SMS_RECEIVED_ACTION); // 設定優先順序 intentFilter.setPriority(Integer.MAX_VALUE); registerReceiver(mSMSBroadcastReceiver,intentFilter);
取消註冊
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mSMSBroadcastReceiver);
}
MainActivity.java的程式碼為:
public class MainActivity extends AppCompatActivity implements SMSBroadcastReceiver.OnReceiveSMSListener { private SMSBroadcastReceiver mSMSBroadcastReceiver = new SMSBroadcastReceiver(); private EditText mEt_code; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEt_code = (EditText) findViewById(R.id.et_code); mSMSBroadcastReceiver.setOnReceiveSMSListener(this); // 註冊廣播 IntentFilter intentFilter = new IntentFilter(SMSBroadcastReceiver.SMS_RECEIVED_ACTION); // 設定優先順序 intentFilter.setPriority(Integer.MAX_VALUE); registerReceiver(mSMSBroadcastReceiver,intentFilter); } @Override public void onReceived(String message) { mEt_code.setText(message+""); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mSMSBroadcastReceiver); } }
這個demo的程式碼實現比較簡單,就是監聽廣播,讀取收到的簡訊,然後過濾篩選出我們要的驗證碼簡訊,再用正則表示式提取到驗證碼設定給EditText顯示即可。大家下載或者自己編寫這個demo並更改傳送方簡訊號碼執行,然後可以找個註冊網址或是模擬驗證碼簡訊進行測試~