Download queue in Android

前端 未结 4 511
一生所求
一生所求 2021-02-02 03:22

What\'s the best way to implement a download queue in Android?

I suspect there might be some platform classes that might do most of the work.

相关标签:
4条回答
  • From API 11 up, a good approach is to use a FixedThreadPool with async tasks. Do once:

    ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(3);
    

    Where 3 is the number of downloads you want to run at the same time. It will queueu the task if there are already 3 downloads running, and automatically handle the task later. Launch your async tasks with:

    yourAsynTask.executeOnExecutor(threadPoolExecutor, params);
    

    Params is probably the url you wish to connect to. You can read it out in the onPostExecute of your asynctask, and connect to the server using a HttpURLConnection.

    Make sure you call down this on shutdown:

    threadPoolExecutor.shutdown()
    
    0 讨论(0)
  • 2021-02-02 03:36

    What's the best way to implement a download queue in Android?

    Use an IntentService. It supplies the queue and the background thread for you, so all you have to do is put your download logic in onHandleIntent(). See here for a sample project demonstrating this.

    0 讨论(0)
  • 2021-02-02 03:36

    Using an IntentService will make it quite difficult to support cancellation. It's just something you need to be aware of. If you can, it's API Level 9, you will be better of using http://developer.android.com/reference/android/app/DownloadManager.html

    0 讨论(0)
  • 2021-02-02 03:51

    I would suggest looking at the java.util.concurrent package and more specifically read up on Executors

    You can create an ExecutorService which would only run 'n' number of Runnable objects at a time and would automatically queue up the rest of the tasks. Once one of the threads being executed finishes execution it picks up the next Runnable object in queue for execution.

    0 讨论(0)
提交回复
热议问题