Surya
Surya

Reputation: 173

Android - Alternative to async tasks?

So I have an app in which I use an async task to fetch in data from a Django backend using rest API. This will be used the first time when the device needs to be synced with the site. So this sync task fetches in quite a lot of data (2 GB). And I have read in many places that async tasks really should be used when the process takes not more than 2-3 seconds. Definitely gonna take longer in my case.

  1. So what is my alternative here? Handlers? Can someone point to a tutorial or article explaining how to?
  2. During the sync process, my device turns off the display to save power. Hence the activity gets destroyed. Now after the sync is complete I show a dialog box, using "AlertDialog" class, informing the user of the same. This causes an error: Activity has leaked a window. Is it a serious issue? What can be done to avoid that? Use fragments to show dialog boxes?

Upvotes: 2

Views: 4554

Answers (2)

Ramapati Maurya
Ramapati Maurya

Reputation: 664

Better you use IntentService for performing long running task in background. It will also finished automatically after completing the job.

Upvotes: 0

Tauno
Tauno

Reputation: 66

Use a Service.
It's meant for long-running tasks and is not tied to your Activity lifecycle.
It would be especially helpful for the user if you'd also associate a notification with the download, showing the progress (as 2GB can take a huge amount of time to fetch, especially on a mobile connection. Speaking of that - please don't fetch 2GB of data on a mobile connection without making it really clear to the user that you're going to do that or enabling them to opt-out of this or do it only when connected over WiFi. Data-limited users will thank you ;)
Here's a tutorial about services

Or you can let the OS take care of all of this and use DownloadManager to fetch the file. It takes care of device restarts, connection issues etc.
Sample project, Tutorial

Upvotes: 3

Related Questions