【问题标题】:ContentObserver onChangeContentObserver onChange
【发布时间】:2014-02-18 07:04:29
【问题描述】:

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

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

【问题讨论】:

    标签: android contentobserver


    【解决方案1】:

    执行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();
    

    【讨论】:

      【解决方案2】:

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

      Handler handler = new Handler(Looper.getMainLooper());
      ContentObserver observer = new MyContentObserver(handler);
      ...
      

      【讨论】:

        【解决方案3】:

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

        How to observe contentprovider change? android

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多