首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ContentObserver onChange

ContentObserver onChange
EN

Stack Overflow用户
提问于 2014-01-27 20:27:58
回答 3查看 7.1K关注 0票数 10

ContentObserver的文档对我来说并不清楚。在哪个线程上调用ContentObserver的onChange?

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

EN

回答 3

Stack Overflow用户

发布于 2016-02-08 09:58:37

执行ContentObserver.onChange()方法的ThreadContentObserver构造函数(http://developer.android.com/reference/android/database/ContentObserver.html#ContentObserver(android.os.Handler%29)'sHandlerLooper(https://developer.android.com/reference/android/os/Handler.html#getLooper(%29)'s Thead.

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

代码语言:javascript
复制
// 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);

或者,要让它在新的工作线程运行,代码可能如下所示:

代码语言:javascript
复制
// 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()是阻塞调用。尽管如此:

代码语言:javascript
复制
// 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();
票数 15
EN

Stack Overflow用户

发布于 2014-03-03 04:51:26

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

代码语言:javascript
复制
Handler handler = new Handler(Looper.getMainLooper());
ContentObserver observer = new MyContentObserver(handler);
...
票数 1
EN

Stack Overflow用户

发布于 2014-03-03 04:36:15

这个老问题似乎触及了你的问题:

How to observe contentprovider change? android

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21380914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档