Handler vs AsyncTask vs Thread

2018-12-31 06:36发布

I got slightly confused about the differences between Handlers, AsyncTask and Threads in Android. I've read quite a few blogs and questions here in stackoverflow.

Handler are background threads that provide you to communicate with the UI. Updating a progressbar for instance should be done via Handler. Using Handlers you have the advantage of MessagingQueues, so if you want to schedule messages or update multiple UI elements or have repeating tasks.

AsyncTask are similar, infact they make use of Handler, but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services. Later you can interact with the UI.

Thread however can't interact with the UI, provide more "basic" threading and you miss all the abstractions of AsyncTask.

However I would like to have a socket connection run in a service. Should this be run in a handler or a thread, or even an AsyncTask? UI interaction is not necessary at all. Does it make a difference in terms of performance which I use?

Meanwhile the documentation has been majorly improved.

12条回答
残风、尘缘若梦
2楼-- · 2018-12-31 07:13

After looking in depth, it's straight forward.

AsyncTask:

It's a simple way to use a thread without knowing anything about java thread model. AsyncTask gives various callbacks respective to the worker thread and main thread.

Use for small waiting operations like the following:

  1. Fetching some data from web services and display over layout.
  2. Database query.
  3. When you realize that running operation will never, ever be nested.

Handler:

When we install an application in android, then it creates a thread for that application called MAIN UI Thread. All activities run inside that thread. By the android single thread model rule, we can not access UI elements (bitmap , textview etc..) directly for another thread defined inside that activity.

A Handler allows you communicate back with the UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread. Handler can send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When a new Handler is created, it is bound to the thread/message queue of the thread that is creating it.

It's the best fit for:

  1. It allows you to do message queuing.
  2. Message scheduling.

Thread:

Now it's time to talk about thread.

Thread is the parent of both AsyncTask and Handler. They both internally use thread, which means you can also create your own thread model like AsyncTask and Handler, but that requires a good knowledge of Java's Multi-Threading Implementation.

查看更多
不流泪的眼
3楼-- · 2018-12-31 07:13

An AsyncTask is used to do some background computation and publish the result to the UI thread (with optional progress updates). Since you're not concerned with UI, then a Handler or Thread seems more appropriate.

You can spawn a background Thread and pass messages back to your main thread by using the Handler's post method.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 07:15

Handler - is communication medium between threads. In android it is mostly used to communicate with main thread by creating and sending messages through handler

AsyncTask - is used to perform long running applications in a background thread. With nAsyncTask you get can do the operation in a background thread and get the result in the main thread of the application.

Thread - is a light weight process, to achieve concurrency and maximum cpu utilization. In android you can use thread to perform activities which does not touch UI of the app

查看更多
泪湿衣
5楼-- · 2018-12-31 07:22

Thread

Android supports standard Java Threads. You can use standard Threads and the tools from the package “java.util.concurrent” to put actions into the background. The only limitation is that you cannot directly update the UI from the a background process.

If you need to update the UI from a background task you need to use some Android specific classes. You can use the class “android.os.Handler” for this or the class “AsyncTask

Handler

The class “Handler” can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and override handleMessage() to process messages. To process Runable, you can use the method post(); You only need one instance of a handler in your activity.

You thread can post messages via the method sendMessage(Message msg) or sendEmptyMessage.

AsyncTask

If you have an Activity which needs to download content or perform operations that can be done in the background AsyncTask allows you to maintain a responsive user interface and publish progress for those operations to the user.

For more information you can have a look at these links.

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

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

查看更多
零度萤火
6楼-- · 2018-12-31 07:22

Thread

When you start an app, a process is created to execute the code. To efficiently use computing resource, threads can be started within the process so that multiple tasks can be executed at the time. So threads allow you to build efficient apps by utilizing cpu efficiently without idle time.

In Android, all components execute on a single called main thread. Android system queue tasks and execute them one by one on the main thread. When long running tasks are executed, app become unresponsive.

To prevent this, you can create worker threads and run background or long running tasks.

Handler

Since android uses single thread model, UI components are created non-thread safe meaning only the thread it created should access them that means UI component should be updated on main thread only. As UI component run on the main thread, tasks which run on worker threads can not modify UI components. This is where Handler comes into picture. Handler with the help of Looper can connect to new thread or existing thread and run code it contains on the connected thread.

Handler makes it possible for inter thread communication. Using Handler, background thread can send results to it and the handler which is connected to main thread can update the UI components on the main thread.

AsyncTask

AsyncTask provided by android uses both thread and handler to make running simple tasks in the background and updating results from background thread to main thread easy.

Please see android thread, handler, asynctask and thread pools for examples.

查看更多
深知你不懂我心
7楼-- · 2018-12-31 07:26

In my opinion threads aren't the most efficient way of doing socket connections but they do provide the most functionality in terms of running threads. I say that because from experience, running threads for a long time causes devices to be very hot and resource intensive. Even a simple while(true) will heat a phone in minutes. If you say that UI interaction is not important, perhaps an AsyncTask is good because they are designed for long-term processes. This is just my opinion on it.

UPDATE

Please disregard my above answer! I answered this question back in 2011 when I was far less experienced in Android than I am now. My answer above is misleading and is considered wrong. I'm leaving it there because many people commented on it below correcting me, and I've learned my lesson.

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.

查看更多
登录 后发表回答