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

来源:互联网 发布:win7精简优化版 编辑:程序博客网 时间:2024/06/05 11:24

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

后来查了一下,是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);    }
阅读全文
0 0