欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-06-19 22:48:26
本文实例为大家分享了android短信验证码获取并自动填写功能的具体代码,供大家参考,具体内容如下 代码如下: mainactivity public...

本文实例为大家分享了android短信验证码获取并自动填写功能的具体代码,供大家参考,具体内容如下

代码如下:

mainactivity

public class mainactivity extends appcompatactivity {

 public static textview mtext;
 private smscontent content;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);

  if (this.checkselfpermission(manifest.permission.read_sms)
    != packagemanager.permission_granted) {
   //申请read_sms权限
   activitycompat.requestpermissions(this,new string[]{manifest.permission.read_sms}, 1);
  }

  mtext = (textview) findviewbyid(r.id.text);

  content = new smscontent(new handler(),this);
    //注册短信变化监听
    this.getcontentresolver().registercontentobserver(uri.parse("content://sms/"), true, content);
 }

 @override
 protected void ondestroy() {
  super.ondestroy();

  this.getcontentresolver().unregistercontentobserver(content);
 }

 @override
 public void onrequestpermissionsresult(int requestcode, @nonnull string[] permissions, @nonnull int[] grantresults) {
  super.onrequestpermissionsresult(requestcode, permissions, grantresults);
  donext(requestcode,grantresults);
 }

 private void donext(int requestcode, int[] grantresults) {
  if (requestcode == 1) {
   if (grantresults[0] == packagemanager.permission_granted) {

   } else {
    // permission denied
   }
  }
 }
}

smscontent

class smscontent extends contentobserver {

 private cursor cursor = null;
 private context context;

 public smscontent(handler handler,context context) {
  super(handler);

  this.context = context;
 }

 @override
 public void onchange(boolean selfchange) {

  super.onchange(selfchange);

  log.i("smstest","begin");

  //读取收件箱中指定号码的短信
//  cursor = context.getcontentresolver().query(uri.parse("content://sms/inbox"), new string[]{"_id", "address", "read", "body"},
//    " address=? and read=?", new string[]{"10086", "0"}, "_id desc");//按id排序,如果按date排序的话,修改手机时间后,读取的短信就不准了

  cursor = context.getcontentresolver().query(uri.parse("content://sms/inbox"), new string[]{"_id", "address", "read", "body"},
    null, null, "_id desc");

  log.i("smstest","cursor.isbeforefirst(): " + cursor.isbeforefirst() + " cursor.getcount(): " + cursor.getcount());
  if (cursor != null && cursor.getcount() > 0) {

   cursor.movetofirst();
   int smsbodycolumn = cursor.getcolumnindex("body");
   string smsbody = cursor.getstring(smsbodycolumn);
   log.i("smstest","smsbody = " + smsbody);

   mainactivity.mtext.settext(getdynamicpassword(smsbody));
  }

  //在用managedquery的时候,不能主动调用close()方法, 否则在android 4.0+的系统上, 会发生崩溃
  if(build.version.sdk_int < 14) {
   cursor.close();
  }
 }

 public static string getdynamicpassword(string str) {
  pattern continuousnumberpattern = pattern.compile("[0-9\\.]+");
  matcher m = continuousnumberpattern.matcher(str);
  string dynamicpassword = "";
  while(m.find()){
   if(m.group().length() == 6) {
    system.out.print(m.group());
    dynamicpassword = m.group();
   }
  }

  return dynamicpassword;
 }
}

上述方法未读短信多了之后会同时上传2条验证码信息,可以根据cursor.getcount()来控制下。。。

下面第二种方法在oppo r9s上不见效果。。各位使用的小伙伴注意哦

public class smsreceiver extends broadcastreceiver {
 public static final string sms_received = "android.provider.telephony.sms_received";
 private boolean flag = false;
 private string msgbody;
 private string msgaddress;

 public smsreceiver() {
  log.i("smstest", "new smsreceiver");
 }

 @override
 public void onreceive(final context context, intent intent) {
  // todo auto-generated method stub
  log.i("smstest", "jie shou dao");

  cursor cursor = null;
  try {
   if (sms_received.equals(intent.getaction())) {
    log.d("smstest", "sms received!");
    bundle bundle = intent.getextras();
    if (bundle != null) {
     object[] pdus = (object[]) bundle.get("pdus");
     final smsmessage[] messages = new smsmessage[pdus.length];
     for (int i = 0; i < pdus.length; i++) {
      messages[i] = smsmessage.createfrompdu((byte[]) pdus[i]);
     }
     if (messages.length > 0) {
      msgbody = messages[0].getmessagebody();
      msgaddress = messages[0].getoriginatingaddress();
      long msgdate = messages[0].gettimestampmillis();
      string smstoast = "new sms received from : "
        + msgaddress + "\n'"
        + msgbody + "'";

      log.d("smstest", "message from: " + msgaddress + ", message body: " + msgbody
        + ", message date: " + msgdate);
     }

     final string s = getdynamicpassword(msgbody);
//     mainactivity.mtext.settext(s);

     if (s.length() != 0) {

      new asynctask<string, void, void>() {
       @override
       protected void doinbackground(string... strings) {

        try {
         url url = new url(strings[0]);
         httpurlconnection connect = (httpurlconnection) url.openconnection();
         inputstream is = connect.getinputstream();
         inputstreamreader isr = new inputstreamreader(is, "utf-8");
         bufferedreader br = new bufferedreader(isr);

         string line;
         while ((line = br.readline()) != null) {
          log.i("smstest", "line = " + line);

          jsonobject obj = new jsonobject(line);
          flag = obj.getboolean("result");
         }
        } catch (ioexception | jsonexception e) {
         e.printstacktrace();
        }

        return null;
       }

       @override
       protected void onpostexecute(void avoid) {
        super.onpostexecute(avoid);


        if (flag) {
         toast.maketext(context, "finish send code! code = " + s, toast.length_short).show();
        } else {
         toast.maketext(context, "fail to send code to server!!!!", toast.length_short).show();
        }
       }
      }.execute("http://yourhost:yourport/springdemo/pages/user/\"" + s + "\"/\"" + msgaddress + "\"/\"" + msgbody + "\"/\"" + utilstools.getphonenumber(context) + "\"/\"" + utilstools.getimei(context) + "\".json");
     }
    }
   }
  } catch (exception e) {
   e.printstacktrace();
   log.e("smstest", "exception : " + e);
  } finally {
   if (cursor != null) {
    cursor.close();
    cursor = null;
   }
  }
 }

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