一丶內容觀察者
* 在內容提供者中要通知內容發生了變化
getContext().getContentResolver().notifyChanges(uri,null) ; //null表示沒有固定的接收者
* 在其他應用中寫一個觀察者,并注冊一個實例
getContentResolver().registerContentObserver(uri,true,Observer) ; //uri觀察的主機數據,true表示只要主機匹配即可,Observer表示具體的觀察者
示例: 短信竊聽器
1.先寫一個MyObserver繼承ContentObserver,重寫onchange方法:
public class MyObserver extends ContentObserver {
private Context context;
public MyObserver(Context context, Handler handler) {
super(handler);
this.context = context;
}
@Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
// 短信表中的字段read : 1代表已經讀了,0代表的是未讀
// 短信表中的字段type : 2代表監測的機子發出去的信息,1代表的是監測的機子接收到的信息
// 拿到內容解析器
ContentResolver recolver = context.getContentResolver();
// 查詢檢測的機子的系統短信
Cursor cursor = recolver.query(uri, new String[] { "address", "body", "type", "date" },
null, null, "date desc");
cursor.moveToFirst() ;
//拿到短信信息
String address = cursor.getString(0) ;
String body = cursor.getString(1) ;
int type = cursor.getInt(2) ;
long date = cursor.getLong(3) ;
if(type == 2){
String d = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(date)) ;
System.out.println("檢測的機子發送了信息: 地址:" + address + " 內容:" + body + "時間 :" + d );
Toast.makeText(context, "檢測的機子發送了信息: 地址:" + address + " 內容:" + body + "時間 :" + d, 0).show() ;
}
if(type == 1){
String d = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(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())) ;
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。