Android中什么时候使用AsyncTask和什么时候使用Thread [英] When to use AsyncTask and When to use Thread in Android
问题描述
When to use AsyncTask
and When to use Thread
as both do work in background and both can manipulate controls in UI Thread
by some mechanism..
May this help you:
For long-running tasks, we use Java threads, and Android's native AsyncTask.
Basically Use AsyncTask for:
- Simple network operations which do not require downloading a lot of data
- Disk-bound tasks that might take more than a few milliseconds
And Use Java threads for:
- Network operations which involve moderate to large amounts of data (either uploading or downloading)
- High-CPU tasks which need to be run in the background
- Any task where you want to control the CPU usage relative to the GUI thread
For more information refer Mohit's answer Click Here
Edit:
Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service. Service is access to a Context object which has an independent life cycle. This allows for reuse of common code by many activities and, in the case of public or exposed services in many applications.
A Service runs on the main thread of the calling Component’s process by default (and hence can degrade responsiveness and cause ANRs), hence you should create a new Thread to perform long running operations.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this and stopping a thread sometime become problematic also. A thread is a mechanism for doing work without blocking other work...
A service does not imply a thread and a thread does not imply a service. Both are different from eachother..
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components.
这篇关于Android中什么时候使用AsyncTask和什么时候使用Thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!