Android:使用 DownloadManager 进行版本更新,出现 No Activity found to handle Intent 及解决办法

时间:2023-03-09 15:39:29
Android:使用 DownloadManager 进行版本更新,出现 No Activity found to handle Intent 及解决办法

项目中,进行版本更新的时候,用的是自己写的下载方案,最近看到了使用系统服务 DownloadManager 进行版本更新,自己也试试。

在下载完成以后,安装更新的时候,出现了一个 crash,抓取的 log :

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW type=application/vnd.android.package-archive flg=0x10000000 }

代码:

             Intent install = new Intent(Intent.ACTION_VIEW);
DownloadManager mManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadFileUri = mManager.getUriForDownloadedFile(downloadApkId);
install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);

通过搜索发现应该是传入的 Uri 有问题,安装 apk 的 Uri 应该是 file:// 开头的,但是代码中获取的 Uri 是 content://

修改后的代码:

         Intent install = new Intent(Intent.ACTION_VIEW);
Uri downloadFileUri;
File file = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/update.apk");
if (file != null) {
String path = file.getAbsolutePath();
downloadFileUri = Uri.parse("file://" + path);
install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}

修改后的代码可以正常进行版本更新了。