Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 短信驗證碼自動填寫

Android 短信驗證碼自動填寫

編輯:關於Android編程

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);


感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved