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

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

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

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

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

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


当前回答

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

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

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

其他回答

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

AsyncTask用于执行一些后台计算并将结果发布到UI线程(带有可选的进度更新)。既然你不关心UI,那么处理器或线程似乎更合适。

您可以生成一个后台线程,并通过使用处理程序的post方法将消息传递回主线程。

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();
    }

}

就像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的例子。

线程

Android支持标准的Java线程。您可以使用标准线程和包“java.util”中的工具。并发”将操作放到后台。唯一的限制是您不能直接从后台进程更新UI。

如果你需要从后台任务更新UI,你需要使用一些Android特定的类。你可以使用类“android.os”。或者AsyncTask类

类“Handler”可以更新UI。句柄为接收消息和可运行对象提供方法。要使用处理程序,必须继承它的子类并重写handleMessage()来处理消息。要处理Runable,可以使用post()方法;您的活动中只需要一个处理程序实例。

线程可以通过sendMessage(Message msg)或sendEmptyMessage方法发布消息。

AsyncTask

如果你有一个Activity需要下载内容或执行可以在后台完成的操作,AsyncTask允许你维护一个响应式用户界面,并将这些操作的进度发布给用户。

要了解更多信息,你可以看看这些链接。

http://mobisys.in/blog/2012/01/android-threads-handlers-and-asynctask-tutorial/

http://www.slideshare.net/HoangNgoBuu/android-thread-handler-and-asynctask