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

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

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

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

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

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


当前回答

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

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

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

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

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

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

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

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

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

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

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

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