gpt4 book ai didi

android - ContentObserver 的 onChange

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:24 28 4
gpt4 key购买 nike

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

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

最佳答案

执行 ContentObserver.onChange() 方法的 ThreadContentObserver constructorHandlerLooperThead .

例如,要让它在主 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 - ContentObserver 的 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21380914/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com