Contentobserver Onchange
Solution 1:
The Thread
that the ContentObserver.onChange()
method is executed on is the ContentObserver
constructor's Handler
's Looper
's Thead
.
For example, to have it run on the main UI thread, the code may look like this:
// returns the applications main looper (which runs on the application's // main UI thread)Looperlooper= Looper.getMainLooper();
// creates the handler using the passed looperHandlerhandler=newHandler(looper);
// creates the content observer which handles onChange on the UI threadContentObserverobserver=newMyContentObserver(handler);
Alternatively, to have it run on a new worker thread, the code may look like this:
// creates and starts a new thread set up as a looper
HandlerThread thread = newHandlerThread("MyHandlerThread");
thread.start();
// creates the handler using the passed looper
Handler handler = newHandler(thread.getLooper());
// creates the content observer which handles onChange on a worker thread
ContentObserver observer = newMyContentObserver(handler);
Or even to have it run on the current thread, the code may look like this. Generally this is not what you want because a Thread
that is looping can't do much else because Looper.loop()
is a blocking call. Nevertheless:
// prepares the looper of the current thread
Looper.prepare();
// creates a handler for the current thread's looper.Handlerhandler=newHandler();
// creates the content observer which handles onChange on this threadContentObserverobserver=newMyContentObserver(handler);
// starts the current thread's looper (blocking call because it's // looping, and handling messages forever). the content observer will// only execute the onChange method while the thread is looping; // interrupting Looper.loop() would "break" the content observer.
Looper.loop();
Solution 2:
In order to assure that the onChange is called on the UI thread, use the correct handler when registering to it:
Handlerhandler=newHandler(Looper.getMainLooper());
ContentObserverobserver=newMyContentObserver(handler);
...
Solution 3:
This old question seems to touch on your issue:
How to observe contentprovider change? android
Looks like you should create a new thread, running in its own Service, where the onChange method will be called.
Post a Comment for "Contentobserver Onchange"