从Android 4.2开始,manager.getUriForDownloadedFile(id)将返回的scheme是content,返回uri是content://downloads/my_downloads/<id>,没有给出路径,这样调用系统的安装方法就会出现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;
}然后就可以调用这个方法来启动安装了
java
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(install);
本文介绍了一个从Android4.2开始的问题:使用manager.getUriForDownloadedFile(id)获取的URI无法直接用于安装APK文件。文章提供了一种方法,可以将content URI转换为file URI,从而解决ActivityNotFoundException异常。
3860

被折叠的 条评论
为什么被折叠?



