问题
Hi I am trying with the below code.The content resolver is not working with this.Can anyone give an idea
getContentResolver().registerContentObserver(MyContentProvider.CONTENT_URI,true, new ContentObserver(new Handler()){
@Override public void onChange( boolean selfChange){
showDialog();
}
@Override
public void onChange(boolean selfChange, Uri uri) {
// Handle change.
showDialog();
}
});
Thanks in advance
回答1:
A ContentObserver
only works with a ContentProvider
that calls one of the notifyChange() methods on a ContentResolver when the contents of the provider change. If the ContentProvider
does not call notifyChange()
, the ContentObserver
will not be notified about changes.
回答2:
Problem
The problem I experienced was that the ContentObserver.onChange()
method never got called because the ContentObserver
's Handler
's Looper
was initialized improperly. I forgot to call Looper.loop()
after calling Looper.prepare()
...this lead to the Looper
not consuming events and invoking ContentObserver.onChange()
.
Solution
The solution is to properly create and initialize a Handler
and Looper
for the ContentObserver
:
// creates and starts a new thread set up as a looper
HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
// creates the handler using the passed looper
Handler handler = new Handler(thread.getLooper());
// creates the content observer which handles onChange on a worker thread
ContentObserver observer = new MyContentObserver(handler);
useful SO post about controlling which thread ContentObserver.onChange() is executed on.
来源:https://stackoverflow.com/questions/29198375/contentobserver-not-working-in-android