ContentObserver onChange [英] ContentObserver onChange

查看:202
本文介绍了ContentObserver onChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不清楚ContentObserver的文档. 在哪个线程上调用ContentObserver的onChange?

The documentation of the ContentObserver is not clear to me. On which thread is the onChange of a ContentObserver called?

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

I checked and it is not the thread where you created the observer. It looks like it is the thread that sends the notification but I didn't find a documentation about it.

推荐答案

执行ContentObserver.onChange()方法的Thread Thead .

The Thread that the ContentObserver.onChange() method is executed on is the ContentObserver constructor's Handler's Looper's Thead.

例如,要使其在主UI线程上运行,代码可能如下所示:

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

或者,要使其在新的辅助线程上运行,代码可能如下所示:

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 = 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()是阻塞调用.不过:

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

这篇关于ContentObserver onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆