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();

相关文章

这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,...
本文小编为大家详细介绍“Android数据压缩的方法是什么”,内...