从 URL 下载 android 2.2 中 5-40 MB 的数据文件。使用哪些类进行开发?
我正在开发一个应用程序,我需要下载一个大小为 5 到 50 MB 的文件(.zip / .txt / .jpg 等)。基于 Android 2.2 的应用程序。
用户提供URL并触发下载,但下载过程会在后台运行直至完成。
流媒体应用于下载文件。
我想知道如何使用 HTTP 连接来完成此操作。
哪些类可以用于此目的?
android 2.2是否为此提供了API?
任何形式的帮助表示赞赏......
I am developing an application in which i need to download a file(.zip / .txt / .jpg etc) size- 5 to 50 MB.. Application based on Android 2.2.
The user provides the URL and triggers the download but then the downloading process runs in background until complete.
streaming should be used for downloading file.
I want to know how can this be done using HTTP connections.
what classes can be used for this?
Does android 2.2 provides an API for this?
Any kind of help is appreciated....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Android 确实为此目的包含了一个名为
DownloadManager
的 API...但它是在 2.3 中发布的;因此,虽然它在面向 2.2 的应用程序中没有用处,但它仍然可能是您研究实现的良好资源。我推荐的一个简单实现是这样的:
HttpURLConnection
来连接和下载数据。这将需要在清单中声明 INTERNET 权限,AsyncTask
的 doInBackground() 方法中。这是一个长时间运行的操作,因此您需要将其放入 AsyncTask 为您管理的后台线程中。Service
中实现此操作,以便操作可以在受保护的情况下运行,而无需用户将 Activity 保留在前台。NotificationManager
通知用户,这会向用户的状态栏发布一条消息。为了进一步简化事情,如果您使用
IntentService
,它将为您处理线程(onHandleIntent
中的所有内容都在后台线程上调用),并且您可以对多个下载进行排队只需向其发送多个 Intent 即可一次处理一个。这是我所说的一个框架示例:然后您可以使用要在 Activity 中的任何位置下载的 URL 来调用此服务,如下所示:
希望这有帮助!
编辑:我正在修复此示例,以便为以后遇到此问题的任何人删除不必要的双线程。
Android did include an API called
DownloadManager
for just this purpose...but it was release in 2.3; so while it won't be useful in your application targeting 2.2, it might still be a good resource for you to research the implementation.A simple implementation I would recommend is something like this:
HttpURLConnection
to connect and download the data. This will require the INTERNET permission to be declared in your manifestAsyncTask
. This is a long-running operation, so you need to put it into a background thread, which AsyncTask manages for you.Service
so the operation can run protected without the user keeping the an Activity in the foreground.NotificationManager
to notify the user when the download is complete, which will post a message to their status bar.To simplify things further, if you use
IntentService
, it will handle the threading for you (everything inonHandleIntent
gets called on a background thread) and you can queue up multiple downloads for it to handle one at a time by simply sending multiple Intents to it. Here's a skeleton example of what I'm saying:Then you can call this service with the URL you want to download anywhere in an Activity like this:
Hope that is helpful!
EDIT: I'm fixing this example to remove the unnecessary double-threading for anyone who comes upon this later.