我有点困惑处理器,AsyncTask和线程之间的区别在Android。我在StackOverflow上读过不少博客和问题。

Handler是后台线程,为您提供与UI通信。例如,更新进度条应该通过Handler来完成。使用Handlers可以获得MessagingQueues的优势,因此如果您想调度消息或更新多个UI元素或有重复任务。

AsyncTask是类似的,事实上,他们利用Handler,但不运行在UI线程,所以它很适合抓取数据,例如抓取web服务。稍后您可以与UI交互。

然而,线程不能与UI交互,提供更多的“基本”线程,你错过了AsyncTask的所有抽象。

但是,我希望在服务中运行套接字连接。这应该运行在一个处理程序或线程,甚至一个AsyncTask?UI交互根本不需要。它对我使用的性能有影响吗?

同时,文档也得到了很大的改进。


当前回答

这取决于选择哪一个是基于需求的

Handler主要用于从其他线程切换到主线程,Handler附加到一个循环器,它在队列中发布其可运行任务。 所以如果你已经在其他线程和切换到主线程,那么你需要处理而不是异步任务或其他线程

如果在主线程之外创建的Handler不是一个looper,则不会在线程创建Handler时给出错误,该线程需要被创建为lopper

AsyncTask用于执行在后台线程上运行的代码,并将其结果传递给主线程 ** *异步任务限制 1. 异步任务不附加到活动的生命周期,即使它的活动被破坏,它也会继续运行,而加载器没有这个限制 2. 所有异步任务共享相同的后台线程执行,这也会影响应用程序的性能

线程在应用程序中用于后台工作,但它在主线程上没有任何回调。 如果要求适合一些线程,而不是一个线程,需要给任务很多次,那么线程池执行器是更好的选择。Eg要求图像加载从多个url像滑翔。

其他回答

public class RequestHandler {

    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;

        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                while ((response = br.readLine()) != null){
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

}

在我看来,线程并不是进行套接字连接的最有效的方式,但它们确实在运行线程方面提供了最多的功能。我这么说是因为根据经验,长时间运行线程会导致设备非常热且资源密集。即使是一个简单的while(正确)也会在几分钟内使手机发热。如果你说UI交互不重要,也许AsyncTask是好的,因为它们是为长期流程设计的。这只是我的看法。

更新

请忽略我以上的回答!早在2011年,我就回答了这个问题,当时我对Android的经验远不如现在。我上面的回答是误导性的,被认为是错误的。我把它留在那里,因为很多人在下面评论纠正我,我已经吸取了教训。

There are far better other answers on this thread, but I will at least give me more proper answer. There is nothing wrong with using a regular Java Thread; however, you should really be careful about how you implement it because doing it wrong can be very processor intensive (most notable symptom can be your device heating up). AsyncTasks are pretty ideal for most tasks that you want to run in the background (common examples are disk I/O, network calls, and database calls). However, AsyncTasks shouldn't be used for particularly long processes that may need to continue after the user has closed your app or put their device to standby. I would say for most cases, anything that doesn't belong in the UI thread, can be taken care of in an AsyncTask.

AsyncTask被设计为在后台执行不超过几秒的操作(不建议从服务器下载兆字节的文件或计算cpu密集型任务,如文件IO操作)。如果您需要执行一个长时间运行的操作,强烈建议您使用java本机线程。Java为您提供了各种与线程相关的类来完成您所需要的工作。使用Handler更新UI线程。

处理器——线程之间的通信媒介。在android中,它主要用于通过处理器创建和发送消息来与主线程通信

AsyncTask -用于在后台线程中执行长时间运行的应用程序。使用nAsyncTask,你可以在后台线程中执行操作,并在应用程序的主线程中获得结果。

Thread -是一个轻量级的进程,可以实现并发性和最大的cpu利用率。在android中,你可以使用线程来执行不触及应用程序UI的活动

就像Vogella网站上关于Android后台处理的教程,AsyncTask和Loaders一样:

Handler类可用于注册到线程,并提供一个简单的通道将数据发送到该线程。

AsyncTask类封装了后台进程的创建和与主线程的同步。它还支持报告正在运行的任务的进度。

线程基本上是多线程的核心元素,开发人员使用它有以下缺点:

如果您使用Java线程,则必须处理以下需求 在你自己的代码中: 如果将结果返回到用户界面,则与主线程同步 没有取消线程的默认值 没有默认线程池 Android中没有处理配置更改的默认值

关于AsyncTask,正如Android开发者参考所说:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

2015年5月更新:我找到了一个涵盖这个主题的优秀系列讲座。

这是谷歌搜索:道格拉斯施密特讲座android并发和同步 这是YouTube上第一节课的视频 所有这些都是来自范德堡大学的CS 282 (2013): Android系统编程的一部分。这是YouTube播放列表 道格拉斯·施密特似乎是个出色的讲师

重要提示:如果你正在考虑使用AsyncTask来解决线程问题,你应该首先检查ReactiveX/RxAndroid,以获得更合适的编程模式。有一个很好的资源可以让你得到一个概览,那就是学习RxJava 2 for Android的例子。