歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android使用ContentObserver監聽數據庫變化

Android使用ContentObserver監聽數據庫變化

日期:2017/3/1 10:35:06   编辑:Linux編程

最近有個朋友問了我如何接受指定號碼的短信,並且不讓系統截取到通知用戶。真好前端時間看天朝group,也有個朋友問了這個問題,而且通過 ContentObserver方式解決了。我這裡就把我實現的代碼貼出來,以便需要的朋友參考,最近Google-groups上不去,很是郁悶啊。
Java 代碼
public class ScreenTest extends Activity {
class SmsContent extends ContentObserver{
private Cursor cursor = null;
public SmsContent(Handler handler) {
super(handler);
}


/**
* @Description 當短信表發送改變時,調用該方法
* 需要兩種權限
* Android.permission.READ_SMS 讀取短信
* android.permission.WRITE_SMS 寫短信
* @Author Snake
* @Date 2010-1-12
*/
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
//讀取收件箱中指定號碼的短信
cursor = managedQuery(Uri.parse("content://sms/inbox"), new String[]{"_id", "address", "read"}, " address=? and read=?", new String[]{"12345678901", "0"}, "date desc");
if (cursor != null){
ContentValues values = new ContentValues();
values.put("read", "1"); //修改短信為已讀模式
cursor.moveToFirst();
while (cursor.isLast()){
//更新當前未讀短信狀態為已讀
getContentResolver().update(Uri.parse("content://sms/inbox"), values, " _id=?", new String[]{""+cursor.getInt(0)});
cursor.moveToNext();
}
}
}
}


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SmsContent content = new SmsContent(new Handler());
//注冊短信變化監聽
this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);
}
}


public class ScreenTest extends Activity {
class SmsContent extends ContentObserver{
private Cursor cursor = null;
public SmsContent(Handler handler) {
super(handler);
}


/**
* @Description 當短信表發送改變時,調用該方法
* 需要兩種權限
* android.permission.READ_SMS讀取短信
* android.permission.WRITE_SMS寫短信
* @Author Snake
* @Date 2010-1-12
*/
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
//讀取收件箱中指定號碼的短信
cursor = managedQuery(Uri.parse("content://sms/inbox"), new String[]{"_id", "address", "read"}, " address=? and read=?", new String[]{"12345678901", "0"}, "date desc");
if (cursor != null){
ContentValues values = new ContentValues();
values.put("read", "1"); //修改短信為已讀模式
cursor.moveToFirst();
while (cursor.isLast()){
//更新當前未讀短信狀態為已讀
getContentResolver().update(Uri.parse("content://sms/inbox"), values, " _id=?", new String[]{""+cursor.getInt(0)});
cursor.moveToNext();
}
}
}
}


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SmsContent content = new SmsContent(new Handler());
//注冊短信變化監聽
this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);
}
}

Copyright © Linux教程網 All Rights Reserved