Chinaunix首页 | 论坛 | 博客
  • 博客访问: 285752
  • 博文数量: 68
  • 博客积分: 1474
  • 博客等级: 上尉
  • 技术积分: 616
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-12 12:07
文章分类

全部博文(68)

文章存档

2011年(68)

分类: 嵌入式

2011-07-16 11:55:07

这里有一个观察者模式的例子,使用 ContentObserver 监听数据库变化

如何接受指定号码的短信,并且不让系统截取到通知用户

  1. public class ScreenTest extends Activity {

  2. class SmsContent extends ContentObserver{

  3. private Cursor cursor = null;

  4. public SmsContent(Handler handler) {

  5. super(handler);

  6. }

//检查与观察函数 deliverSelfNotifications()。(它将返回 false 默认情况下)
  1. @Override
  2. public boolean deliverSelfNotifications() {
  3.      return true;
  4. }
  1. /**

  2. * @Description 当短信表发送改变时,调用该方法

  3. * 需要两种权限

  4. * android.permission.READ_SMS 读取短信

  5. * android.permission.WRITE_SMS 写短信

  6. */
  7. @Override

  8. public void onChange(boolean selfChange) {

  9. // TODO Auto-generated method stub

  10. super.onChange(selfChange);

  11. //读取收件箱中指定号码的短信

  12. cursor = managedQuery(Uri.parse("content://sms/inbox"), new String[]{"_id", "address", "read"}, " address=? and read=?", new String[]{"12345678901", "0"}, "date desc");

  13. if (cursor != null){

  14. ContentValues values = new ContentValues();

  15. values.put("read", "1"); //修改短信为已读模式

  16. cursor.moveToFirst();

  17. while (cursor.isLast()){

  18. //更新当前未读短信状态为已读

  19. getContentResolver().update(Uri.parse("content://sms/inbox"), values, " _id=?", new String[]{""+cursor.getInt(0)});

  20. cursor.moveToNext();

  21. }

  22. }

  23. }

  24. }

  25. /** Called when the activity is first created. */

  26. @Override

  27. public void onCreate(Bundle savedInstanceState) {

  28. super.onCreate(savedInstanceState);

  29. setContentView(R.layout.main);

  30. SmsContent content = new SmsContent(new Handler());

  31. //注册短信变化监听

  32. this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"),true, content);

    }

    }


阅读(1970) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~