android – ContentObserver onChange

前端之家收集整理的这篇文章主要介绍了android – ContentObserver onChange前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ContentObserver的文档对我来说并不清楚.
在哪个线程上调用ContentObserver的onChange?

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

解决方法

执行ContentObserver.onChange()方法的线程是 ContentObserver constructorHandlerLooper 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();
原文链接:https://www.f2er.com/android/308893.html

猜你在找的Android相关文章