设为首页 加入收藏

TOP

Android使用ContentObserver监听数据库变化
2014-11-24 14:41:21 来源: 作者: 【 】 浏览:9
Tags:Android 使用 ContentObserver 监听 数据库 变化

最近有个朋友问了我如何接受指定号码的短信,并且不让系统截取到通知用户。真好前端时间看天朝group,也有个朋友问了这个问题,而且通过 ContentObserver方式解决了。我这里就把我实现的代码贴出来,以便需要的朋友参考,最近Google-groups上不去,很是郁闷啊。
Java 代码
public class ScreenTest extends Activity {
class SmsContent extends ContentObserver{
private Cursor cursor = null;
public SmsContent(Handler handler) {
super(handler);
}



/** 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);
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android 中管理短信 下一篇Android系统的进程,任务,服务的信..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: