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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...