ContentObserver onChange

时间:2014-01-27 12:27:58

标签: android contentobserver

ContentObserver的文档对我来说并不清楚。 哪个线程是ContentObserver的onChange?

我检查过,它不是你创建观察者的线程。看起来它是发送通知的线程,但我没有找到有关它的文档。

3 个答案:

答案 0 :(得分:11)

执行Thread方法的ContentObserver.onChange()ContentObserver constructor' s Handler' Looper&#39 ; 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();

答案 1 :(得分:0)

为了确保在UI线程上调用onChange,请在注册时使用正确的处理程序:

Handler handler = new Handler(Looper.getMainLooper());
ContentObserver observer = new MyContentObserver(handler);
...

答案 2 :(得分:-1)

这个老问题似乎涉及到你的问题:

How to observe contentprovider change? android

看起来你应该创建一个新的线程,在自己的服务中运行,其中将调用onChange方法。