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

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

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

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

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

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


当前回答

线程

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

其他回答

线程

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

深入观察之后,事情就一目了然了。

AsyncTask:

这是一种使用线程的简单方法,无需了解任何java线程模型。 AsyncTask给出了各个工作线程和主线程的回调。

用于小的等待操作,如下所示:

从web服务中获取一些数据并在布局中显示。 数据库查询。 当你意识到运行的操作永远不会被嵌套。

处理程序:

当我们在android中安装一个应用程序时,它会为该应用程序创建一个名为MAIN UI thread的线程。所有活动都在该线程中运行。根据android单线程模型规则,我们不能访问UI元素(位图,textview等)直接为另一个线程内定义的活动。

Handler允许你从其他后台线程与UI线程通信。这在android中很有用,因为android不允许其他线程直接与UI线程通信。处理程序可以发送和处理与线程的MessageQueue关联的Message和Runnable对象。每个Handler实例都与单个线程和该线程的消息队列相关联。创建新的Handler时,它将绑定到创建它的线程的线程/消息队列。

它最适合:

它允许您进行消息排队。 消息调度。

线程:

现在是讨论线程的时候了。

线程是AsyncTask和Handler的父线程。它们都在内部使用线程,这意味着您也可以创建自己的线程模型,如AsyncTask和Handler,但这需要对Java的多线程实现有很好的了解。

让我试着用一个例子来回答这个问题:)- MyImageSearch[请参考这里的主活动屏幕的图像-包含编辑文本/搜索按钮/网格视图]

MyImageSearch -一旦用户在编辑文本字段输入详细信息并单击搜索按钮,我们将通过flickr提供的web服务在互联网上搜索图像(您只需要在那里注册以获得密钥/秘密令牌)-对于搜索,我们发送一个HTTP请求和get JSON数据返回响应,其中包含个人图像的url,然后我们将使用它来加载网格视图。

My Implementation - In the main activity I will define a inner class which extends the AsyncTask to send the HTTP Request in doInBackGround Method and fetch the JSON Response and update my local ArrayList of FlickrItems which I am going to use to update my GridView via the FlickrAdapter (extends the BaseAdapter) and call the adapter.notifyDataSetChanged() in the onPostExecute() of AsyncTask to reload the grid view. Note that here the HTTP Request is a blocking call because of which I have done it via the AsyncTask. And, I can cache the items in adapter to increase the performance or store them on SDCard. The grid that I will be inflating in the FlickrAdapter contains in my implementation a progressbar and image view. Below you can find the code for mainActivity which I used.

现在回答问题- 因此,一旦我们获得了用于获取单个图像的JSON数据,我们就可以实现通过Handlers或线程或AsyncTask在后台获取图像的逻辑。我们应该注意到,由于我的图像一旦下载就必须显示在UI/主线程上,我们不能简单地使用线程,因为它们不能访问上下文。 在FlickrAdapter中,我能想到的选择:

Choice 1: Create a LooperThread [extends thread] - and keep on downloading images sequentially in one thread by keeping this thread open [looper.loop()] Choice 2: Make use of a Thread Pool and post the runnable via myHandler which contains reference to my ImageView, but since the views in Grid View are recycled, again the problem might arise where image at index 4 is displayed at index 9 [download may take more time] Choice 3 [I used this]: Make use of a Thread Pool and send a message to myHandler, which contains data related to ImageView's index and ImageView itself, so while doing handleMessage() we will update the ImageView only if currentIndex matches the index of the Image we tried to download. Choice 4: Make use of AsyncTask to download the images in background, but here I will not have access to the number of threads I want in the thread pool and it varies with different android version, but in Choice 3 I can make of conscious decision of the size of thread pool depending on device configuration being used.

以下是源代码:

public class MainActivity extends ActionBarActivity {

    GridView imageGridView;
    ArrayList<FlickrItem> items = new ArrayList<FlickrItem>();
    FlickrAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageGridView = (GridView) findViewById(R.id.gridView1);
        adapter = new FlickrAdapter(this, items);
        imageGridView.setAdapter(adapter);
    }

    // To avoid a memory leak on configuration change making it a inner class
    class FlickrDownloader extends AsyncTask<Void, Void, Void> {



        @Override
        protected Void doInBackground(Void... params) {
            FlickrGetter getter = new FlickrGetter();

            ArrayList<FlickrItem> newItems = getter.fetchItems();

            // clear the existing array
            items.clear();

            // add the new items to the array
            items.addAll(newItems);

            // is this correct ? - Wrong rebuilding the list view and should not be done in background
            //adapter.notifyDataSetChanged();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            adapter.notifyDataSetChanged();
        }

    }

    public void search(View view) {
        // get the flickr data
        FlickrDownloader downloader = new FlickrDownloader();
        downloader.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我希望我的回答虽然很长,但将有助于理解一些更精细的细节。

就像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中,它主要用于通过处理器创建和发送消息来与主线程通信

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

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