ContentObserver的文档对我来说并不清楚。在哪个线程上调用ContentObserver的onChange?
我检查过了,它不是你创建观察者的线程。它看起来像是发送通知的线程,但我没有找到有关它的文档。
发布于 2016-02-08 09:58:37
执行ContentObserver.onChange()方法的Thread是ContentObserver构造函数(http://developer.android.com/reference/android/database/ContentObserver.html#ContentObserver(android.os.Handler%29)'sHandler的Looper(https://developer.android.com/reference/android/os/Handler.html#getLooper(%29)'s Thead.
例如,要让它在主UI线程上运行,代码可能如下所示:
// returns the applications main looper (which runs on the application's
// main UI thread)
Looper looper = Looper.getMainLooper();
// creates the handler using the passed looper
Handler handler = new Handler(looper);
// creates the content observer which handles onChange on the UI thread
ContentObserver observer = new MyContentObserver(handler);或者,要让它在新的工作线程上运行,代码可能如下所示:
// 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);或者甚至让它在当前线程上运行,代码可能如下所示。通常,这不是您想要的,因为循环的Thread不能做更多的事情,因为Looper.loop()是阻塞调用。尽管如此:
// prepares the looper of the current thread
Looper.prepare();
// creates a handler for the current thread's looper.
Handler handler = new Handler();
// creates the content observer which handles onChange on this thread
ContentObserver observer = new MyContentObserver(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();发布于 2014-03-03 04:51:26
为了确保在UI线程上调用onChange,请在注册时使用正确的处理程序:
Handler handler = new Handler(Looper.getMainLooper());
ContentObserver observer = new MyContentObserver(handler);
...发布于 2014-03-03 04:36:15
这个老问题似乎触及了你的问题:
How to observe contentprovider change? android
看起来您应该创建一个新线程,在它自己的服务中运行,其中将调用onChange方法。
https://stackoverflow.com/questions/21380914
复制相似问题