咱們在ContentProvider的insert,update,delete等改變以後調用getContext().getContentResolver().notifyChange(uri, null);這樣就通知那些監測databases變化的observer了,而你的observer能夠在一個service裏面註冊。java
定義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(); } }
onCreate中註冊:ide
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); .....}
onDestroy中註銷:spa
/** * Cleans up when the service is destroyed */ public void onDestroy() { getContentResolver().unregisterContentObserver(mObserver); if (Constants.LOGVV) { Log.v(Constants.TAG, "Service onDestroy"); } super.onDestroy(); }
實際操做數據庫的地,通知前面註冊的Observer:code
getContext().getContentResolver().notifyChange(uri, null);