Android开发

Android实现自动填写获取验证码功能

本文主要是介绍Android实现自动填写获取验证码功能,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文实例讲解了Android自动提取短信验证码解决方案,分享给大家供大家参考,具体内容如下

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>

package com.dongdongsongcan.app;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
 
import com.su.dolphin.utils.LogUtil;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class SMSReceiver extends BroadcastReceiver
 
{
 
  public interface ISMSListener {
    public void onSmsReceive(String verifyCode);
  }
 
  private static ISMSListener mSMSListener;
 
  public SMSReceiver(ISMSListener ismsListener) {
    mSMSListener = ismsListener;
  }
 
  public static final String TAG = "ImiChatSMSReceiver";
 
  //android.provider.Telephony.Sms.Intents
 
  public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
 
 
  @Override
 
  public void onReceive(Context context, Intent intent)
 
  {
    LogUtil.d(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    if (intent.getAction().equals(SMS_RECEIVED_ACTION))
 
    {
 
      SmsMessage[] messages = getMessagesFromIntent(intent);
 
      for (SmsMessage message : messages)
 
      {
 
//        LogUtil.d(message.getOriginatingAddress() + " : " +
//
//            message.getDisplayOriginatingAddress() + " : " +
//
//            message.getDisplayMessageBody() + " : " +
//
//            message.getTimestampMillis());
 
 
        String msg = message.getDisplayMessageBody();
        LogUtil.d("MSG: " + msg);
        String verifyCode = null;
        Pattern p = Pattern.compile("\\d{4}");
        Matcher m = p.matcher(msg);
        while (m.find()) {
          verifyCode = m.group();
          break;
        }
        LogUtil.d("verifyCode " + verifyCode);
        if (mSMSListener != null) {
          mSMSListener.onSmsReceive(verifyCode);
        }
      }
 
    }
 
  }
 
 
  public final SmsMessage[] getMessagesFromIntent(Intent intent)
 
  {
 
    Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
 
    byte[][] pduObjs = new byte[messages.length][];
 
 
    for (int i = 0; i < messages.length; i++)
 
    {
 
      pduObjs[i] = (byte[]) messages[i];
 
    }
 
    byte[][] pdus = new byte[pduObjs.length][];
 
    int pduCount = pdus.length;
 
    SmsMessage[] msgs = new SmsMessage[pduCount];
 
    for (int i = 0; i < pduCount; i++)
 
    {
 
      pdus[i] = pduObjs[i];
 
      msgs[i] = SmsMessage.createFromPdu(pdus[i]);
 
    }
 
    return msgs;
 
  }
 
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助。

这篇关于Android实现自动填写获取验证码功能的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!