内容观察者(一个简单的手机短信窃听器)
一丶内容观察者
* 在内容提供者中要通知内容发生了变化
getContext().getContentResolver().notifyChanges(uri,null) ; //null表示没有固定的接收者
* 在其他应用中写一个观察者,并注册一个实例
getContentResolver().registerContentObserver(uri,true,Observer) ; //uri观察的主机数据,true表示只要主机匹配即可,Observer表示具体的观察者
示例: 短信窃听器
1.先写一个MyObserver继承ContentObserver,重写onchange方法:publicclassMyObserverextendsContentObserver{privateContextcontext;publicMyObserver(Contextcontext,Handlerhandler){super(handler);this.context=context;}@OverridepublicvoidonChange(booleanselfChange,Uriuri){super.onChange(selfChange,uri);//短信表中的字段read:1代表已经读了,0代表的是未读//短信表中的字段type:2代表监测的机子发出去的信息,1代表的是监测的机子接收到的信息//拿到内容解析器ContentResolverrecolver=context.getContentResolver();//查询检测的机子的系统短信Cursorcursor=recolver.query(uri,newString[]{"address","body","type","date"},null,null,"datedesc");cursor.moveToFirst();//拿到短信信息Stringaddress=cursor.getString(0);Stringbody=cursor.getString(1);inttype=cursor.getInt(2);longdate=cursor.getLong(3);if(type==2){Stringd=newSimpleDateFormat("yyyy年MM月dd日HH:mm:ss").format(newDate(date));System.out.println("检测的机子发送了信息:地址:"+address+"内容:"+body+"时间:"+d);Toast.makeText(context,"检测的机子发送了信息:地址:"+address+"内容:"+body+"时间:"+d,0).show();}if(type==1){Stringd=newSimpleDateFormat("yyyy年MM月dd日HH:mm:ss").format(newDate(date));System.out.println("检测的机子接收信息:地址:"+address+"内容:"+body+"时间:"+d);Toast.makeText(context,"检测的机子接收了信息:地址:"+address+"内容:"+body+"时间:"+d,0).show();}}}
2.在其他应用中写一个观察者,并注册一个实例
Uri uri = Uri.parse("content://sms") ;//监测的主机
getContentResolver().registerContentObserver(uri, true, new MyObserver(this, new Handler())) ;
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。