Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use AsyncTask or Service to upload a file in background?

I have a requirement where a user is able to upload a video to Amazon S3. I have achieved this using the java high-level api in amazon sdk. During the upload process if the user clicks the home button the upload must continue in the background.

What would be a better approach :?

*1 Using AsyncTask: I have tried using AsyncTask and it works fine. But if the uploading process continues for long interval at the background, the OS kills the app to free memory. Is there any way that i can handle this situation, and let my app complete the upload process.

*2 Using Service: Someone suggested me to use a Service + ui notification. I feel like using AsyncTask, because it works fine for me. Is there any advantage of using a Service over AsyncTask.

like image 980
Rojil Thomas Avatar asked Dec 04 '12 15:12

Rojil Thomas


People also ask

When to use AsyncTask Android?

Generally it is convenient to use AsyncTask when you must "skip back" to UI thread when the background task is done or when you have to give some feedback to UI thread during task execution.

What is difference between thread and AsyncTask in Android?

Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread. Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once. Long task in general.

What are background services in Android?

A Background Service is a service that runs only when the app is running so it'll get terminated when the app is terminated. A Foreground Service is a service that stays alive even when the app is terminated. And a Bound Service is a service that runs only if the component it is bound to is still active.

Is Async task a service?

AsyncTask s are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed. Service s are designed to be continually running in the background.


1 Answers

Most of the time an AsyncTask is coupled to your UI, the Activity that started it etc. Those will stay in memory until the task is finished.

This upload scenario of yours begs for implementation through an IntentService. This will decouple the uploading from a specific activity and make your App a good Android citizen in regard to the Android life cycle.

You can now create a Notification that is periodically updated from the Service that shows the status of the upload and lets the user cancel the upload from his status bar.

like image 190
Janusz Avatar answered Sep 20 '22 10:09

Janusz