Posting to Handler tied to current thread

折月煮酒 提交于 2019-12-11 13:34:40

问题


I have a Handler, mHandler, tied to the main thread. mHandler resides in a Service. Say I now post a Runnable to mHandler from the main thread like so:

public class SomeService extends Service {
    // Handler is created on the main thread
    // (and hence it is tied to the main thread)
    private Handler mHandler = new Handler();

    @Override
    public void onDestroy() {
        // onDestroy runs on the main thread
        // Is the code in this Runnable processed right away?
        mHandler.post(new Runnable() {
            // (Some code statements that are to be run on the main thread)
            ...
        });
        super.onDestroy();
    }
}

I know the example is a little silly as the Handler is unnecessary. However, it is a good example for this question.

Now my questions are:

  1. Will the code statements in the Runnable be processed right away as the thread that posts the Runnable is also the thread that is to process the Runnable? Or does it work differently as the Handler internally uses a MessageQueue and hence there might be Runnables posted to the Handler elsewhere (which arrive before my Runnable)?
  2. Moreover, is it possible that the statements will never run as the post(Runnable r) is an async call and hence onDestroy() will finish and the Service will be killed by the system before the Handler gets to run the code.

Thank you in advance.


回答1:


  1. Since a Service does not imply a separate thread, your runnable will be posted at the end of the main Looper's queue, so yes, there may be messages/runnables scheduled before yours.

  2. Again, since Service does not imply a distinct thread, a call to onDestroy does not mean that the Handler's thread has been terminated. In this example, you are posting to the main looper, and that thread is active until the application process terminates.



来源:https://stackoverflow.com/questions/28618685/posting-to-handler-tied-to-current-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!