ContentObserver的使用与反复调用

来源:互联网 发布:网络教育哪所学校好 编辑:程序博客网 时间:2024/05/09 03:45

项目需求:

1    当联系人更新时,本地表可以获取到更新的通知

2    程序退出后,仍然可以更新


搜了网上很多文章,发现可以使用ContentObserver这个类实现需求1,对于需求2,当然是用Service实现了。

代码如下:

public class DBUpdateService extends Service {protected static final int LOCALCONTACTS_SYNC = 1;private final static int ELAPSE_TIME = 5000;// FIXME: Should remind this// time./* * Set an observer to listen the LocalContacts' change. As the DB of contact * would be change after make a call or send a message. We should listen the * LogDB too.If it change, we believe the contact is not changed. It's not * the best way,just is a temporary solution,but it can handle many cases. */public ContentObserver mObserver = new ContentObserver(new Handler()) {@Overridepublic void onChange(boolean selfChange) {super.onChange(selfChange);Log.i(TAG, "Contact onChange");mHandler.removeMessages(LOCALCONTACTS_SYNC);Log.v(TAG, "removeMessages finish.");mHandler.sendEmptyMessageDelayed(LOCALCONTACTS_SYNC, ELAPSE_TIME);}};protected Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);Log.v(TAG, "++++handleMessage " + msg);switch (msg.what) {case LOCALCONTACTS_SYNC://do what you want to dobreak;default:break;}}};@Overridepublic void onCreate() {super.onCreate();......getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, mObserver);---------注册ContentObserver}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    return START_STICKY;---------------这个可以使Service在需要运行时候自动运行,即使程序退出了}@Overridepublic void onDestroy() {getContentResolver().unregisterContentObserver(mObserver);-----------------------------------------------注销ContentObserver}}

参考:

http://stackoverflow.com/questions/10173996/content-observer-onchange-method-called-twice-after-1-change-in-cursor?answertab=votes#tab-top

http://stackoverflow.com/questions/10431881/how-to-know-the-contact-is-updated-in-android/10432259#10432259

http://blog.csdn.net/luoshengyang/article/details/6985171


更新:

对于问题2,只需要注册了contentobserver就可以实现了,因为系统有一个ContentService会管理注册的observer。

如果有数据修改,系统会自动向注册的observer发送通知。

代码中需要实现两个onChange

原创粉丝点击