完整項目短信驗證碼自動讀取
地址:https://github.com/wangsijie0415/ReciiveSMSCode
調(diào)起系統(tǒng)短信接收廣播
intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(Integer.MAX_VALUE);
registerReceiver(receiver, intentFilter);
廣播接收處理
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Object[] objs = (Object[]) intent.getExtras().get("pdus");
String format = intent.getStringExtra("format");//23以后需要的
if(format != null){
Log.e("format", format);
}
for (Object obj : objs) {
byte[] pdu = (byte[]) obj;
SmsMessage sms = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
sms = SmsMessage.createFromPdu(pdu,format);//API23以后修改成這個
}else{
sms = SmsMessage.createFromPdu(pdu);
}
// 短信的內(nèi)容
String message = sms.getMessageBody();
Log.e("logo", "message " + message); // 短息的手機號。握联。+86頭罗洗?
String from = sms.getOriginatingAddress();
Log.e("logo", "from " + from);
if (!TextUtils.isEmpty(from)) {
String code = patternCode(message);
if (!TextUtils.isEmpty(code)) {
smsContent = code;
handler.sendEmptyMessage(1);
}
}
}
}};
設置驗證碼:
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
code.setText(smsContent);
}
};