2019独角兽企业重金招聘Python工程师标准>>>
我们在ContentProvider的insert,update,delete等改变之后调用getContext().getContentResolver().notifyChange(uri, null);这样就通知那些监测databases变化的observer了,而你的observer可以在一个service里面注册。
定义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中注册:
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中注销:
/**
* 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:
getContext().getContentResolver().notifyChange(uri, null);