温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android 短信验证码自动填写

发布时间:2020-08-23 10:51:29 来源:脚本之家 阅读:167 作者:lqh 栏目:移动开发

Android 短信验证码自动填写

1.自定义Observer监听短信数据库变化(注意添加短信权限)

import android.app.Activity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 001 on 17/3/22.
 */

public class SmsObserver extends ContentObserver {

  public static final String SMS_URI_INBOX = "content://sms/inbox";
  private Activity activity = null;
  private String smsContent = "";
  private SmsListener listener;

  public SmsObserver(Activity activity, Handler handler, SmsListener listener) {
    super(handler);
    this.activity = activity;
    this.listener = listener;
  }

  @Override
  public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    Cursor cursor = null;
    // 读取收件箱中含有某关键词的短信
    ContentResolver contentResolver = activity.getContentResolver();
    cursor = contentResolver.query(Uri.parse(SMS_URI_INBOX), new String[] {
            "_id", "address", "body", "read" }, "body like ? and read=?",
        new String[] { "%关键词%", "0" }, "date desc");
    if (cursor != null) {
      cursor.moveToFirst();
      if (cursor.moveToFirst()) {
        String smsbody = cursor
            .getString(cursor.getColumnIndex("body"));
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(smsbody.toString());
        smsContent = m.replaceAll("").trim().toString();
        if (!TextUtils.isEmpty(smsContent)) {
          listener.onResult(smsContent);
        }

      }
    }
  }

  /*
   * 短信回调接口
   */
  public interface SmsListener {
    /**
     * 接受sms状态
     *
     * @Title: onResult
     */
    void onResult(String smsContent);
  }
}

2.使用:

SmsObserver smsObserver = new SmsObserver(this, new Handler(), new SmsObserver.SmsListener() {
      @Override
      public void onResult(String smsContent) {
 //根据需求写
 //如:editText.setText(smsContent);
      }    });this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI