用ContentObserver内容观察者写了一个自动填写验证码

2/22/2017来源:ASP.NET技巧人气:3160

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"/>