您的位置:首页 > 移动开发 > Android开发

Android:ContentObserver(内容监听者)之自动接收验证码

2017-02-18 16:37 351 查看
ContentObserver——内容监听者(内容观察者)。指的是监听某一指定路径里面的数据。目的是观察(捕捉)特定URI引起的数据库的变化,从而做一些相当应的处理。当数据一旦发生改变会通过调用onChange()方法,通过handler把数据发送出去。

   通过ContentObserver实现验证码自动填入的功能。首先我们需要在布局文件中写一个TextView控件。在主activity(ContentobserverActivity.java)中拿到文本框控件,然后通过handler、bundle接收消息以及拿到数据后接收验证码等操作。具体代码如下:

public class ContentobserviceActivity extends AppCompatActivity {
private TextView tv_contentobservice_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contentobservice);
tv_contentobservice_content = (TextView) findViewById(R.id.tv_contentobservice_content);//拿到文本框的控件
Handler handler=new Handler(){//实列化handler,用来更新UI
@Override
public void handleMessage(Message msg) {//这个方法是用来接收消息
super.handleMessage(msg);
Bundle bundle=msg.getData();//从消息中拿到bundle
tv_contentobservice_content.setText(bundle.getString("phone"));//在bundle中拿到数据
}
};
this.getContentResolver().registerContentObserver(Uri.parse("content://sms"),true,new Mycontent(handler));//拿到SMS中的内容监听者(SMS是所有的消息,包括发件箱与收件箱...)

}
class Mycontent extends ContentObserver{//写一个类继承ContentObserver,重写它的方法

private Handler handler;
public Mycontent(Handler handler) {
super(handler);
this.handler=handler;
}
//当信息发生改变时调用onChange()方法
@Override
public void onChange(boolean selfChange) {
Log.i("test", "onChange: 主人来信息啦~~~");
Cursor cursor=ContentobserviceActivity.this.getContentResolver().query(Uri.parse("content://sms/inbox"),null,null,null,null);//查询系统数据库中的收件箱
if (cursor.moveToNext()){//判断是否有值
if (cursor.getString(cursor.getColumnIndex("address")).equals("+86************")){//如果值的号码为你所固定的号码
String date=cursor.getString(cursor.getColumnIndex("body"));//拿到你所固定的号码发送的内容
String data[]=date.split(":");//根据冒号开始切割
String datas=data[1];//拿到冒号后的内容
String phone=datas.substring(0,4);//因为内容后的数字为验证码,所有直接截取后四位的数据
Message message=new Message();//实列化一个消息
Bundle b=new Bundle();//实列化一个bundle
b.putString("phone",phone);//把验证码放入bundle
message.setData(b);//把bundle放入消息中
handler.sendMessage(message);//通过handler发送消息
} }
super.onChange(selfChange);
}
}
}在清单文件中需要增加访问短息的权限。
<!--访问短信的权限-->
<uses-permission android:name="android.permission.READ_SMS"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: