简体   繁体   English

在Android中后台下载多个文件

[英]Download multiple files in background in Android

Basically I'm trying to make a little app for watching offline content. 基本上,我正在尝试制作一个用于观看离线内容的小应用程序。 So there's a moment where the user selects to download the contents (and the app should download about 300 small files and images). 因此,有一段时间用户选择下载内容(应用程序应下载约300个小文件和图像)。

I'd like to show the user how does the process go if he enters the proper activity. 我想向用户展示如果他输入适当的活动,过程将如何进行。 Showing a list of all the files, telling what has been already downloaded, in progress or waiting for download. 显示所有文件的列表,告知已下载,正在下载或正在等待下载的文件。

My problem is that I really don't know what approach to take for achieve this. 我的问题是我真的不知道该采用哪种方法。 Since the download should last until finished I imagine the solution is an Service , but whats best? 由于下载应该持续到完成,所以我认为解决方案是Service ,但是什么是最好的? an IntentService, a Bound Service or an Standard Service calling a startService() for each download? 每次下载都调用startService()的IntentService,绑定服务或标准服务? And how can I keep my objects updated for displaying them later? 以及如何保持对象更新以便以后显示? should I use a database or objects in memory? 我应该在内存中使用数据库还是对象?

Thanks 谢谢

I would suggest using AsyncTask class, it allows you to easily move time consuming code(like downloading files) to a different thread. 我建议使用AsyncTask类,它使您可以轻松地将耗时的代码(如下载文件)移动到其他线程。 This will keep your app responsive, while giving you the ability to update your UI in the process. 这将使您的应用程序保持响应速度,同时使您能够在此过程中更新UI。

It's hard to be more specific without having more details about how exactly you want your app to behave. 如果没有更多有关您的应用程序如何表现的详细信息,很难做到更加具体。 Are the downloads only going to happen when the app is running or in the background as well? 下载是否仅在应用程序运行时或在后台运行?

You could use Asynctask or implement a ExecutorService with custom policies and send to it the download threads. 您可以使用Asynctask或使用自定义策略实现ExecutorService并将下载线程发送给它。
You need to keep a reference to the AsyncTask or a Future object respectively inside of a collection if you want to give the oportunity to the user to stop downloads. 如果要给用户机会停止下载,则需要在集合内部分别保留对AsyncTask或Future对象的引用。 Of course, you need to call startService each time you want to download a new file. 当然,每次要下载新文件时,都需要调用startService。 Service onCreate only is called if service is not running and onStartCommand run each time you call startService. 仅当服务未运行且每次调用startService时onStartCommand运行时,才调用服务onCreate。 In onStartCommand you run a new thread for download a new file. 在onStartCommand中,您运行一个新线程以下载新文件。 You can bind service with an activity and each time that your downloadsActivity is created you show the state of downloads implementing a custom Adapter. 您可以将服务与活动绑定,并且每次创建downloadsActivity时,都会显示实现自定义适配器的下载状态。 Service only finishes when you call activity.stopService or service.stopSelf 服务仅在您调用activity.stopService或service.stopSelf时完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM