android DownloadManager下载apk

1、使用DownloadReceiver下载apk:

    /**
     * 下载apk文件
     * @param path apk的下载地址url
     */
    private void downApkLoad(String path) {
        //app的下载地址
        Uri uri = Uri.parse(path);
        DownloadManager.Request req = new DownloadManager.Request(uri);
        //设置网络状态下进行更新
        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
        //下载中和下载完后都·显示通知栏
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //使用系统默认的下载路径 此处为应用内 /android/data/packages ,所以兼容7.0 8.0
        req.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS, getResources().getString(R.string.app_name) + ".apk");
        //通知栏标题
        req.setTitle(getResources().getString(R.string.app_name));
        //通知栏描述信息
        req.setDescription("下载中");
        //设置类型为.apk
        req.setMimeType("application/vnd.android.package-archive");
        req.setVisibleInDownloadsUi(true);
        //获取下载任务ID
        DownloadManager dm = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        BaseApplication.downloadId = dm.enqueue(req);
        registerReceiver(new DownloadReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        Toast.makeText(mContext,"下载中,您可以在通知栏查看进度!",Toast.LENGTH_LONG).show();
    }

2、注册的DownloadReceiver:

public class DownloadReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
		Intent install = new Intent(Intent.ACTION_VIEW);
		install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//根据id判断如果文件已经下载成功返回保存文件的路径
		Uri downloadFileUri = dManager.getUriForDownloadedFile(BaseApplication.downloadId);
		Log.d("DownloadManager", "apk存储路径 : " + downloadFileUri);
		install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
		if (downloadFileUri != null) {
			if ((Build.VERSION.SDK_INT >= 24)) {//判读版本是否在7.0以上
				install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				//添加这一句表示对目标应用临时授权该Uri所代表的文件
				//  不添加无法安装 或者出现解析包异常
			}
			context.startActivity(install);
		}
	}
}

 

参考:https://blog.csdn.net/Liuxb_zao/article/details/84989511

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漠天515

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值