Android - Alternative to async tasks?

﹥>﹥吖頭↗ 提交于 2019-12-22 18:11:28

问题


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?

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/19858296/android-alternative-to-async-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!