您的位置:首页 > 移动开发 > Android开发

Android之监测database的改变--notifyChange

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

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

Java代码  


/** 

     * 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中注册:

Java代码  


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);  

.....}  

Java代码  


/** 

    * 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: