关键词搜索

源码搜索 ×
×

Android之监测database的改变--notifyChange

发布2015-09-09浏览5117次

详情内容

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

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

Java代码   收藏代码
  1. /** 
  2.      * Receives notifications when the data in the content provider changes 
  3.      */  
  4.     private class DownloadManagerContentObserver extends ContentObserver {  
  5.   
  6.         public DownloadManagerContentObserver() {  
  7.             super(new Handler());  
  8.         }  
  9.   
  10.         /** 
  11.          * Receives notification when the data in the observed content 
  12.          * provider changes. 
  13.          */  
  14.         public void onChange(final boolean selfChange) {  
  15.             if (Constants.LOGVV) {  
  16.                 Log.v(Constants.TAG, "Service ContentObserver received notification");  
  17.             }  
  18.             updateFromProvider();  
  19.         }  
  20.   
  21.     }  
在DownloadService的onCreate中注册:

Java代码   收藏代码
  1. public void onCreate() {  
  2.        super.onCreate();  
  3.        if (Constants.LOGVV) {  
  4.            Log.v(Constants.TAG, "Service onCreate");  
  5.        }  
  6.   
  7.        mDownloads = Lists.newArrayList();  
  8.   
  9.        mObserver = new DownloadManagerContentObserver();  
  10.        getContentResolver().registerContentObserver(Downloads.CONTENT_URI,  
  11.                true, mObserver);  
  12. .....}  

Java代码   收藏代码
  1. /** 
  2.     * Cleans up when the service is destroyed 
  3.     */  
  4.    public void onDestroy() {  
  5.        getContentResolver().unregisterContentObserver(mObserver);  
  6.        if (Constants.LOGVV) {  
  7.            Log.v(Constants.TAG, "Service onDestroy");  
  8.        }  
  9.        super.onDestroy();  
  10.    }  
可以参考以下文章:

http://hi.baidu.com/lck0502/blog/item/a818258f304b61e0f01f3691.html


相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载