android DownloadManager

From: https://www.jianshu.com/p/46fd1c253701


private static long mTaskId = -1;

/*
* android system api to download
*/
public static void download(Context context, String urlStr, String filename) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlStr));
request.setAllowedOverRoaming(false);//漫游网络是否可以下载

//设置文件类型,可以在下载结束后自动打开该文件
// MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
// String mimeString = mimeTypeMap.getMimeTypeFromExtension(
// MimeTypeMap.getFileExtensionFromUrl(urlStr));
// request.setMimeType(mimeString);

//在通知栏中显示,默认就是显示的
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setVisibleInDownloadsUi(true);

//sdcard的目录下的download文件夹,必须设置
request.setDestinationInExternalPublicDir("/download/", filename);
// request.setDestinationInExternalFilesDir(context,type, filepath) // 也可以自己指定下载路径

// 将下载任务加入队列
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//加入下载队列后会给该任务返回一个long型的id,
//通过该id可以取消任务,重启任务等等,看上面源码中框起来的方法
mTaskId = downloadManager.enqueue(request);

// downloadManager.remove(taskId) //

context.registerReceiver(mReceiverDownload, new IntentFilter());
}

private static BroadcastReceiver mReceiverDownload = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkDownloadStatus();
}
};

private static void checkDownloadStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(mTaskId);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()){
int status = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
switch (status){
case DownloadManager.STATUS_PAUSED:
Log.v(TAG, "下载暂停");
break;
case DownloadManager.STATUS_PENDING:
Log.v(TAG, "下载延迟");
break;
case DownloadManager.STATUS_RUNNING:
Log.v(TAG, "正在下载...");
break;
case DownloadManager.STATUS_SUCCESSFUL:
Log.v(TAG,"下载完成");
// Play Act
break;
case DownloadManager.STATUS_FAILED:
Log.v(TAG, "下载失败");
break;
}
}
}

希望你可以看到最后这几句,不然你也会被坑的!
1.虽然下载什么的不需要自己操心了,但是建议还是将整个上面四段代码放在Service中执行,因为放在Activity中时,当用户按home键后,即使下载完了,也不会弹出安装界面
2.建议使用startService的方式启动Service,这样不会与Activity生命周期绑定,保证下载完后能顺利安装。
3.Service使用完后要及时地停掉!


作者:Marno
链接:https://www.jianshu.com/p/46fd1c253701
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值