下载文件
Andorid的下载通过开启下载服务在后台执行,通过下载器来进行管理,通过下载请求来执行请求,在通过调用enqueue方法来下载,下载完成后,会发送一个广播,这个广播为ACTION_DOWNLOAD_COMPLETE,下载完成后接收到。
//设置下载服务
String servicestring = Context.DOWNLOAD_SERVICE;
//DownloadManager下载管理
DownloadManager downloadManager = (DownloadManager) getSystemService(servicestring);
Uri uri =Uri.parse("http://119.29.85.118/Finance/FlashFXP.zip");
DownloadManager.Request request = new DownloadManager.Request(uri);
//调用enqueue方法后,就会开始下载
long reference = downloadManager.enqueue(request);
//设置在WIFI下才能下载
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
//设置标题
request.setTitle("FlashFXP");
request.setDescription("FlashFxp.zip");
//直到下载完成都会显示
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//隐式注册一个广播,当程序下载完成后
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT);
}
};
//注册
registerReceiver(receiver,filter);
//隐式注册一个广播,当程序下载完成后
IntentFilter filter2 = new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);
BroadcastReceiver receiver2 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
long[] references =intent.getLongArrayExtra(extraID);
for(long refer:references){
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
Toast.makeText(context,"下载完成通知",Toast.LENGTH_SHORT);
}
}
};
//注册
registerReceiver(receiver2,filter2);