Download queue in Android

前端 未结 4 595
一生所求
一生所求 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条回答
  •  不要未来只要你来
    2021-02-02 03:34

    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()
    

提交回复
热议问题