大家好,又见面了,我是你们的朋友全栈君。
一、前言:
这周项目做优化,为用户操作更加方便,注册、忘记密码、更换手机号、所需要的获取验证码操作,增加 获取短信验证码,然后自动填写到输入框中。思路简单,主要是监听短信的广播,然后正则短信中的验证码
二、具体代码:
package com.taikongdan.app.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by merbng on 2016/4/6.
*/
public class SMSReceiver extends BroadcastReceiver {
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
public static final String TAG = "ImiChatSMSReceiver";
public interface ISMSListener {
void onSmsReceiver(String verifyCode);
}
private static ISMSListener mSMSListener;
public SMSReceiver(ISMSListener mSMSListener) {
this.mSMSListener = mSMSListener;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
SmsMessage[] messages = getMessageFromIntent(intent);
for (SmsMessage message : messages
) {
// 在这里你可以对放松的号码进行判断,只接受目标号码的验证码
String msg = message.getDisplayMessageBody();
Pattern p = Pattern.compile("\\d{6}");//这里你可以更改数字来指定验证码的位数
Matcher m = p.matcher(msg);
String verifyCode = null;
while (m.find()) {
verifyCode = m.group();
break;
}
if (mSMSListener != null) {
mSMSListener.onSmsReceiver(verifyCode);
}
}
}
}
private SmsMessage[] getMessageFromIntent(Intent intent) {
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjes = new byte[messages.length][];
for (int i = 0; i < messages.length; i++) {
pduObjes[i] = ((byte[]) messages[i]);
}
byte[][] pdus = new byte[pduObjes.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++) {
pdus[i] = pduObjes[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
在Activity onCreate中,注册广播,
<pre name="code" class="java"> @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rememeberactivity);
mReceiver = new SMSReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mReceiver, filter);
}
在界面销毁的时候 解绑广播
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/160334.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...