I've found a sample to download a large data file at the following link, http://code.google.com/p/apps-for-android/source/browse/#svn/trunk/Samples/Downloader
It seems to be pretty nice (I haven't yet tested it). But I also have read some posts at the stackoverflow to do the same thing by using the AsyncTask class, not using the Thread class as the above sample.
What I want to know is, which should开发者_开发知识库 I use to achieve downloading a file? And if AsyncTask is better, would you point me to a sample code?
Disclaimer: i am not Android developer, answer comes from general experience.
Thread class is most suitable for long-running activities, not for asynchronous tasks. Except if you manage pool of workers, but still lifetime of thread is same or nearly same as application. Consider that creation of thread is expensive operation.
AsyncTasks and other helpers are usually for some single activities that you want to do in background so not to block the app. They are usually well managed by the platform and are cheap.
My opinion: use AsyncTask if you want to load pages occasionally. If your app will load pages all the time in the background consider thread.
For understanding what has to be used one must understand the nature of the task we are about to perform. Suppose we are going to download large file.... would you being a user want to see it or rather let it run in the background?? i guess i dont mind running that task in the background(unless it is game and some graphics are being downloaded).
Taking this thought in mind, if we use the Asyntask, the user must have to keep the App open until the download operation has been completed; as three out of four methods of AsyncTask runs on the UI thread. (check out the link : https://developer.android.com/reference/android/os/AsyncTask) In the other case where we are using the AsyncTask to download graphics file for a game, it would be completely fine to go for it.
So I believe it is better to go for Thread or even better to go for Service to download the content so that one may continue to work further on the app/ close the app or even run some other app.
These two options have an equal probability of being killed while download is in progress (when user switches to another app). Still, AsyncTask
is less mess. For downloading large files, consider using a Service
.
AsyncTasks in Android versions prior to 3.0 uses a pool of threads in background to execute the tasks, but in versions after 3.0, a single thread is used to execute the AsyncTasks.
If you need to make a lot of requests at the same time and your Android version is higher than 3.0, use a pool of threads, but if you only have to make a single download (not mind the Android version), use AsyncTask, it will be executed at a single background thread without problems, easier than manage a Thread by your own.
精彩评论