今天博主带给小伙伴们一个小功能,就是利用广播接收器实现自动填充短信验证码,话不多说,我们先看看如何去实现这个小功能。
首先我们需要新建一个名为SMSBroadcastReceiver的广播接收器,代码如下:
public class SMSBroadcastReceiver extends BroadcastReceiver { private static MessageListener mMessageListener; public SMSBroadcastReceiver() { super(); } @Override public void onReceive(Context context, Intent intent) { public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; 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(); //短信内容 String content = smsMessage.getDisplayMessageBody(); long date = smsMessage.getTimestampMillis(); Date tiemDate = new Date(date); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = simpleDateFormat.format(tiemDate); //过滤不需要读取的短信的发送号码,博主这里用的是关键词过滤,小伙伴们也可以用电话号去过滤 if (content.contains("***")&&content.contains("****") &&content.contains("***")) { //从短信内容中获取验证码 String code=getCode(content,6); //回调数据 mMessageListener.onReceived(code); abortBroadcast(); } } } } //回调接口 public interface MessageListener { public void onReceived(String message); } public void setOnReceivedMessageListener(MessageListener messageListener) { this.mMessageListener = messageListener; } public static String getCode(String body, int YZMLENGTH) { // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的YZMLENGTH位数字字母组合 // (?
本文名称:Android利用广播接收器实现自动填充短信验证码-创新互联
浏览地址:http://cdkjz.cn/article/dpgocp.html