ContentObserver onChange

7 android contentobserver

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

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

Eri*_*ric 11

ThreadContentObserver.onChange()被执行方法上是ContentObserver构造HandlerLooperThead.

例如,要让它在主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);
Run Code Online (Sandbox Code Playgroud)

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

// 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);
Run Code Online (Sandbox Code Playgroud)

或者甚至让它在当前线程上运行,代码可能看起来像这样.通常这不是你想要的,因为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();
Run Code Online (Sandbox Code Playgroud)

  • 将“null”传递给构造函数的情况怎么样? (2认同)

小智 -1

这个老问题似乎涉及到你的问题:

如何观察contentprovider的变化?安卓

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