张贴到处理程序绑定到当前线程 [英] Posting to Handler tied to current thread

查看:172
本文介绍了张贴到处理程序绑定到当前线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理程序, mHandler ,绑在主线程。 mHandler 驻留在服务。说我现在发布的Runnable mHandler 从主线程像这样:

 公共类SomeService延伸服务{
    //处理程序是在主线程创建
    //(因此它是联系在一起的主线程)
    私人处理程序mHandler =新的处理程序();    @覆盖
    公共无效的onDestroy(){
        //运行的onDestroy在主线程
        //将是code在这个Runnable的处理,对吗?
        mHandler.post(新的Runnable(){
            //(有些code语句是要在主线程上运行)
            ...
        });
        super.onDestroy();
    }
}

我知道的例子是有点傻的处理程序是不必要的。然而,正是因为这个问题一个很好的例子。

现在我的问题是:


  1. 将在code语句的的Runnable 马上为线程处理该职位的Runnable 也就是处理的Runnable 线程?或者它的工作方式不同,作为处理程序内部使用的MessageQueue ,因此有可能是的Runnable 取值发布到处理程序其他地方?的Runnable 前到达) >
  2. 此外,是有可能的语句将永远为后运行(Runnable接口R)是一个异步调用,因此的onDestroy()将完成和服务将系统中的处理程序之前被杀死获取运行code。

感谢您提前。


解决方案

  1. 由于服务并不意味着一个独立的线程,您可运行将在主尺蠖年底发布的队列,所以是的,有可能是邮件/可运行之前,你的计划。


  2. 同样,因为服务并不意味着不同的线程,一个呼叫的onDestroy 并不意味着该处理程序的线程被终止。在这个例子中,你正在发布到主尺蠖,而线程处于活动状态,直到应用程序终止。


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. 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.

这篇关于张贴到处理程序绑定到当前线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆