完整项目短信验证码自动读取
地址:https://github.com/wangsijie0415/ReciiveSMSCode
调起系统短信接收广播
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);
}
// 短信的内容
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);
}
};