现在的位置: 首页 > 综合 > 正文

Android之监测database的改变–notifyChange

2013年09月18日 ⁄ 综合 ⁄ 共 1650字 ⁄ 字号 评论关闭

我们在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

抱歉!评论已关闭.