項目中,進行版本更新的時候,用的是自己寫的下載方案,最近看到了使用系統服務 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 }
代碼:
1 Intent install = new Intent(Intent.ACTION_VIEW); 2 DownloadManager mManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); 3 Uri downloadFileUri = mManager.getUriForDownloadedFile(downloadApkId); 4 install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive"); 5 install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 6 context.startActivity(install);
通過搜索發現應該是傳入的 Uri 有問題,安裝 apk 的 Uri 應該是 file:// 開頭的,但是代碼中獲取的 Uri 是 content://
修改后的代碼:
1 Intent install = new Intent(Intent.ACTION_VIEW); 2 Uri downloadFileUri; 3 File file = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/update.apk"); 4 if (file != null) { 5 String path = file.getAbsolutePath(); 6 downloadFileUri = Uri.parse("file://" + path); 7 install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive"); 8 install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 9 context.startActivity(install); 10 }
修改后的代碼可以正常進行版本更新了。