Question

a. Download Manager Api b. Intent Service c. Asynctask

Please let me know which is the best practice. Is it possible to cancel the ongoing download using the above mentioned terms, If so please provide me the snippets.

Was it helpful?

Solution

A : Download Manager:

The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.

So if you do not want to take headache of HTTP connection error handling, and just want to pass source and destination of a file, then use DownloadManager.

And You can cancel downloads via DownloadManager by calling its remove(long...) method. For this you need the ID of the download

B: IntentService

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread.So mainly used to create queues.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

And you can bind to the intentservice and create a method to cancel or de-queue a download.

C: AsyncTasks

AsyncTasks 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. So not a preferable solution for long running downloads.

You can cancel downloading using AsyncTask too. For that you need to go for the cancel() method for asynctask. And in your loop where you are reading the response stream, keep checking using some flag whether the asynctask's cancel method is called or not.If cancel method is called stop the downloading else continue.

I hope you figured out the best possible way by this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top