Is there any difference between AsyncSync being fired up from Activity or IntentService?
I'm building an app which downloads and uploads files via http. I use custom notification layout with progress bar for each transfer. I choose between doing transfers in parallel or putting them into queue (which option would you recommend?).
For the option with queue I use an IntentService, so Android framework takes care of putting tasks into a queue for me. For having them in parallel I use AsyncTasks. But I fire them up from IntentService (could be Service as well) - is there any point doing开发者_StackOverflow so? IntentService is terminated right after it executes AsyncTask, so the AsyncTask runs without any "parent".
What if I fired up those AsyncTask from Activity, go to the homescreen and system decided to close this Activity? Can it do that? Will the AsyncTask survive it?
What would be the preferred approach for this case?
AsyncTask isn't really appropriate for things where you're concerned about surviving outside the lifecycle of a component (if you need to message back to that component). If you're going to the extent of having a service, I wouldn't even bother with AsyncTasks. As far as parallel or queue, that really depends on a lot of different variables, but I certainly wouldn't make it completely parallel for any number of downloads/uploads. I'd set some limit on the max number of concurrent transfers.
There's no point in using IntentService for parallel exeuction--you've noted the problem with that already. You're getting into territory which is not really covered by the Android API. AsyncTask and IntentService are nice abstractions that make several scenarios easy, but parallel execution of many many tasks is not one of them. It's probably best to use some of the Java threading/concurrency classes. Take a look at ThreadPoolExecutor.
First your easy questions, an AsyncTask will survive being in the background as long as the parent application is not killed. Starting it from an Activity will tell the system that it can be killed if memory pressure requires it. The system also does not consider it having a long running process that may be interrupted.
The dev guide Services has a great info box under its "The Basics" heading about whether you should use a Service or Activity. Activities get none of the memory pressure consideration that Services get or a restart after a kill, when system resources become available again.
If you wanted me to make the call for you, use the IntentService. Whether to run the downloads in parallel or series or some combination is a tough call because you must consider the network (Wifi or Cellular), file size, and other system resources.
精彩评论