android调用系统的安装方法出现ActivityNotFoundException的异常

在Android 4.2及以上版本中,使用DownloadManager下载APK后,通过id获取的Uri是content类型,导致安装时抛出ActivityNotFoundException异常。本文分享如何将content Uri转换为file Uri,或者通过保存的文件名来获取URI进行安装的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天测试下载新版本后自动安装,结果报错了~
这里写图片描述

后来查了一下,是DownloadManager的问题~
从Android 4.2开始,manager.getUriForDownloadedFile(id)将返回的scheme是content,返回uri是content://downloads/my_downloads/15,没有给出路径,这样调用系统的安装方法就会出现ActivityNotFoundException的异常,我找了很久终于找到了文件放在了哪里。
下面我把转化content的Uri为file的Uri方法分享给大家;

    /**
     * 转化contentUri为fileUri
     *
     * @param contentUri 包含content的Uri
     * @param downLoadId 下载方法返回系统为当前下载请求分配的一个唯一的ID
     * @param manager    系统的下载管理
     *
     * @return fileUri
     */
    private Uri getApkFilePathUri(Uri contentUri, long downLoadId, DownloadManager manager) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downLoadId);
        Cursor c = manager.query(query);
        if (c.moveToFirst()) {
            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
            // 下载失败也会返回这个广播,所以要判断下是否真的下载成功
            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                // 获取下载好的 apk 路径
                String downloadFileLocalUri = c.getString(c.getColumnIndex(DownloadManager
                        .COLUMN_LOCAL_URI));
                if (downloadFileLocalUri != null) {
                    File mFile = new File(Uri.parse(downloadFileLocalUri).getPath());
                    String uriString = mFile.getAbsolutePath();
                    // 提示用户安装
                    contentUri = Uri.parse("file://" + uriString);
                }
            }

        }
        return contentUri;
    }

或者使用另外一种方式实现。
1.设置下载路径和文件名 本地记录文件名称

DownloadManager.Request request = new DownloadManager.Request(uri);
String filename = name + ".apk";
request.setDestinationInExternalPublicDir("download",  filename );

2.调用系统安装的时候根据第一步记录的文件名称filename 来获取URI 而不是根据request返回的 downloadID参数

/**
     * 打开APK程序代码,安装应用
     */
    public void openFileForInstall() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), filename ));
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值