coo*_*eep 0 streaming android download progressive-download android-2.2-froyo
我正在开发一个应用程序,我需要下载一个大小为5到50 MB的文件(.zip/.txt/.jpg等).基于Android 2.2的应用程序.
用户提供URL并触发下载,然后下载过程在后台运行直到完成.
应该使用流式传输来下载文件.
我想知道如何使用HTTP连接完成此操作.可以使用
哪些类?
android 2.2是否为此提供了API?
任何形式的帮助表示赞赏....
Android确实包含了一个DownloadManager专门用于此目的的API ......但它是在2.3中发布的; 因此,虽然它在您的应用程序目标2.2中没有用,但它仍然是您研究实现的一个很好的资源.
我建议的一个简单实现是这样的:
HttpURLConnection连接并下载数据.这将要求在您的清单中声明INTERNET权限AsyncTask.这是一个长时间运行的操作,因此您需要将其放入后台线程中,AsyncTask会为您管理.Service操作中,操作可以运行受保护,而无需用户将Activity保留在前台.NotificationManager在下载完成时通知用户,该消息将向其状态栏发送消息.为了进一步简化,如果你使用IntentService它,它将为你处理线程(在onHandleIntent后台线程上调用所有内容),你可以排队多次下载,只需向它发送多个Intent就可以一次处理一个.这是我所说的骨架示例:
public class DownloadService extends IntentService {
public static final String EXTRA_URL = "extra_url";
public static final int NOTE_ID = 100;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
if(!intent.hasExtra(EXTRA_URL)) {
//This Intent doesn't have anything for us
return;
}
String url = intent.getStringExtra(EXTRA_URL);
boolean result = false;
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Input stream from the connection
InputStream in = new BufferedInputStream(connection.getInputStream());
//Output stream to a file in your application's private space
FileOutputStream out = openFileOutput("filename", Activity.MODE_PRIVATE);
//Read and write the stream data here
result = true;
} catch (Exception e) {
e.printStackTrace();
}
//Post a notification once complete
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification note;
if(result) {
note = new Notification(0, "Download Complete", System.currentTimeMillis());
} else {
note = new Notification(0, "Download Failed", System.currentTimeMillis());
}
manager.notify(NOTE_ID, note);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用您要在活动中的任何位置下载的URL来调用此服务,如下所示:
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra(DownloadService.EXTRA_URL,"http://your.url.here");
startService(intent);
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!
编辑:我正在修复这个例子,以便为后来遇到此问题的人删除不必要的双线程.
| 归档时间: |
|
| 查看次数: |
2858 次 |
| 最近记录: |