首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

监测database的改变-notifyChange

2012-09-06 
监测database的改变--notifyChange我们在ContentProvider的insert,update,delete等改变之后调用getContext

监测database的改变--notifyChange
我们在ContentProvider的insert,update,delete等改变之后调用getContext().getContentResolver().notifyChange(uri, null);这样就通知那些监测databases变化的observer了,而你的observer可以在一个service里面注册。

以Downloadmanger为例子:
定义ContentObserver,并且在onChange里做你想做的事情。

/**     * Receives notifications when the data in the content provider changes     */    private class DownloadManagerContentObserver extends ContentObserver {        public DownloadManagerContentObserver() {            super(new Handler());        }        /**         * Receives notification when the data in the observed content         * provider changes.         */        public void onChange(final boolean selfChange) {            if (Constants.LOGVV) {                Log.v(Constants.TAG, "Service ContentObserver received notification");            }            updateFromProvider();        }    }

在DownloadService的onCreate中注册:
 public void onCreate() {        super.onCreate();        if (Constants.LOGVV) {            Log.v(Constants.TAG, "Service onCreate");        }        mDownloads = Lists.newArrayList();        mObserver = new DownloadManagerContentObserver();        getContentResolver().registerContentObserver(Downloads.CONTENT_URI,                true, mObserver);......}


 /**     * Cleans up when the service is destroyed     */    public void onDestroy() {        getContentResolver().unregisterContentObserver(mObserver);        if (Constants.LOGVV) {            Log.v(Constants.TAG, "Service onDestroy");        }        super.onDestroy();    }


可以参考以下文章:
http://hi.baidu.com/lck0502/blog/item/a818258f304b61e0f01f3691.html

热点排行