像 Android Market 一样下载文件
我将实现一个在后台下载大文件(大约 50MB)的功能。
我想像 Android Market 一样 - 我的意思是当用户开始下载文件时,它将显示在状态栏中,并带有所有进度栏,并在完成时通知我的应用程序。
你能给我一些提示吗?我知道我的问题质量不高,但我之前一直在做研究,只是我没有关键字来搜索任何解决方案。
I am going to implement a function that will download a large file (about 50MB) in background.
I would like to do it like Android Market - I mean when user will start downloading a file, it will appear in status bar with all that progress bar and notify my application when it will be finished.
Could you provide me some hints ? I know that my question is not a high quality but I have been doing research before and simply I have no keywords to search any solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是一个简短的概述,旨在为您提供一些关键字。
首先,如何创建通知应该非常简单并且有详细的文档记录。如果您不知道如何创建普通通知,请查看状态栏通知 。
下一步是使用包含
ProgressBar
的自定义布局创建通知(因为据此所知,没有预构建的布局),这也记录在 同一页面。一旦您为此创建了Notification
实例,您应该保留引用并使用它通过nm
更新您的ProgressBar
是 < code>NotificationManager 参考此处,另请参阅 RemoteViews.setProgressBar()这基本上就是 UI 方面的事情。要实际在后台下载文件,您应该使用 Service ,该服务利用 AsyncTask (因为服务在 UI 线程中运行 - 该名称经常会产生误导)。您可以使用
AsyncTask.publishProgress()
将下载进度更新发送到 UI 线程,并更新AsyncTask.onProgressUpdate()
内的进度条。This is just a small overview to give you a few keywords.
First of all, how to create a notification should be pretty straightforward and is well documented. If you don't know how to create a normal notification, check out Status Bar Notifications.
The next step is to create a notification with a custom layout that contains a
ProgressBar
(since there is no prebuilt layout for this afaik), which is also documented on the same page. Once you have createdNotification
instance for that, you should keep the reference and use it to update yourProgressBar
vianm
is aNotificationManager
reference here, also see RemoteViews.setProgressBar()That's basically the UI-side of things. To actually download a file in the background you should make use of a Service that utilizes an AsyncTask (since services run in the UI-thread - the name misleads often). You can use
AsyncTask.publishProgress()
to send download progress updates to the UI-thread and update your progress bar insideAsyncTask.onProgressUpdate()
.除了@alextsc的答案之外,如果您只支持API级别9及更高版本,您可以使用
DownloadManager
,它为您处理所有这些,包括连接更改等详细信息(例如,WiFi->3G)。但是,这仅适用于 Android 2.3+。In addition to @alextsc's answer, if you are only supporting API Level 9 and higher, you can use
DownloadManager
, which handles all of this for you, including details like connectivity changes (e.g., WiFi->3G). But, that's only available on Android 2.3+.