標籤:觀察者 提供者
一丶內容觀察者
* 在內容提供者中要通知內容發生了變化
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())) ;
本文出自 “android筆記” 部落格,請務必保留此出處http://2585211.blog.51cto.com/10044233/1665225
內容觀察者(一個簡單的手機簡訊竊聽器)