用ContentObserver內容觀察者寫了一個自動填寫驗證碼

1.主界面代碼(activity_main.xml):

  <TextView
        android:id="@+id/et_validateCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="請輸入驗證碼"
        android:textSize="30dp"

        />

2.這裏面寫了在你指定的號碼發來的短信截取驗證碼(MainActivity.java):

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.et_validateCode);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle=msg.getData();
                textView.setText(bundle.getString("number"));

            }
        };
        this.getContentResolver().registerContentObserver(Uri.parse("content://sms"),true,new MyObserver(handler));
    }

//繼承ContentObserver 必須重載一個onChange去處理回調
    class MyObserver extends ContentObserver{

        public MyObserver(Handler handler) {
            super(handler);

        }
        @Override
        public void onChange(boolean selfChange) {
            Cursor cursor=MainActivity.this.getContentResolver().query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
            if(cursor!=null) {
                if (cursor.moveToNext()) {
                //我在這裏寫的一個死的電話號,判斷是否是這個手機號,然後在判斷是有否有(驗證碼)
                    if (cursor.getString(cursor.getColumnIndex("address")).equals("+8615074833565") && cursor.getString(cursor.getColumnIndex("body")).contains("驗證碼")) {
                        String date = cursor.getString(cursor.getColumnIndex("body"));
                        int star = date.indexOf(":");
                       //在這裏判斷要截取多少位
                        String data = date.substring(star + 1, star + 5);
                        Message ms = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("number", data);
                        ms.setData(bundle);
                        handler.sendMessage(ms);
                    }
                }

            }
        }
    }

3.記得要加短信的權限:

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_SMS"/>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章