安卓:什么时候应该使用一个处理程序(),当我应该使用一个线程? [英] Android: When should I use a Handler() and when should I use a Thread?

查看:197
本文介绍了安卓:什么时候应该使用一个处理程序(),当我应该使用一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我需要一些东西来执行异步,如长时间运行的任务或逻辑使用网络,或者因为种种原因, 启动新帖并运行它工作正常。 创建一个处理并运行它的工作原理也是如此。 有什么不同?什么时候应该使用每个人? 有什么优势/理由使用处理程序,而不是

When I need something to run asynchronously, such as a long running task or a logic that uses the network, or for whatever reason, Starting a new Thread and running it works fine. Creating a handler and running it works as well. What's the difference? When should I use each one? What are the advantages / reasons to use a Handler and not a Thread?

PS。 - 对于这个问题的缘故,让我们忽略的AsyncTask 。 - 处理程序()postDelayed 使用的情况下,我很清楚,对于这个问题的缘故,让我们假设我所需要的任务立即启动

PS. - For this question's sake, let's ignore AsyncTask. - Handler().postDelayed use case is clear to me, for this question's sake let's assume I need the task to start immediately.

推荐答案

如果无论你正在做的是重你应该做它在一个线程。如果你不明确启动它在自己的线程,那么它将运行主(UI)线程,可能会出现明显的抖动或缓慢通过你的用户响应接口。

If whatever you are doing is "heavy" you should be doing it in a Thread. If you do not explicitly start it in its own thread, then it will run on the main (UI) thread which may be noticeable as jittery or slow to respond interface by your users.

有趣的是,当你使用一个线程中,经常需要还使用一个处理程序作为你开始工作线程和主线程间的通信手段。

Interestingly when you are using a thread it is often useful to also use a Handler as a means of communication between the work thread that you are starting and the main thread.

一个典型的线程/处理器的交互看起来是这样的:

A typical Thread/Handler interaction might look something like this:

Handler h = new Handler(){
    @Override
    public void handleMessage(Message msg){
        if(msg.what == 0){
            updateUI();
        }else{
            showErrorDialog();
        }
    }
};

Thread t = new Thread() {
    @Override
    public void run(){
        doSomeWork();
        if(succeed){
            //we can't update the UI from here so we'll signal our handler and it will do it for us.
            h.sendEmptyMessage(0);
        }else{
            h.sendEmptyMessage(1);
        }
    }   
};

在一般虽然,带回家的是,你应该使用一个线程任何你正在做一些工作,可能是长时间运行或时间非常密集(即任何网络,文件IO,重算术,等等)。

In general though, the take home is that you should use a Thread any time you are doing some work that could be long running or very intensive (i.e. anything network, file IO, heavy arithmatic, etc).

这篇关于安卓:什么时候应该使用一个处理程序(),当我应该使用一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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