在开发的过程中,遇到过一个问题,在android6.0上实现下载更新之后,在下载完成安装APK时,发生错误,并未跳转到系统的安装应用界面,跳转到安装页面的代码如下:
private void installApkBySystem(long downloadId) { try { DownloadManager downloadManager = (DownloadManager) currActivity.getSystemService(Context.DOWNLOAD_SERVICE); Uri filepath = downloadManager.getUriForDownloadedFile(downloadId); Intent activityIntent = new Intent(Intent.ACTION_VIEW); activityIntent.setDataAndType(filepath, "application/vnd.android.package-archive"); activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); currActivity.startActivity(activityIntent); } catch (ActivityNotFoundException ex) { ex.printStackTrace(); } }
因此对android6.0以上的采用打开文件的方式安装APK:
/** * for sdk >= 23 */ private void installApkByOpen(Context context, long downloadId){ try { DownloadManager downloadManager = (DownloadManager) currActivity.getSystemService(Context.DOWNLOAD_SERVICE); Uri fileUri = downloadManager.getUriForDownloadedFile(downloadId); String filePath = getRealFilePath(context, fileUri); File file = new File(filePath); if (file.exists()){ openFile(file, context); } } catch (ActivityNotFoundException ex) { ex.printStackTrace(); } }private void openFile(File file , Context context){ Intent var2 = new Intent(); var2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); var2.setAction("android.intent.action.VIEW"); String var3 = getMIMEType(file); var2.setDataAndType(Uri.fromFile(file), var3); try { context.startActivity(var2); } catch (Exception var5) { var5.printStackTrace(); ToastUtil.show(context, "没有找到打开此类文件的程序"); } } public String getMIMEType(File file) { String var1 = ""; String var2 = file.getName(); String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase(); var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3); return var1; } private String getRealFilePath(final Context context, final Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null) data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; }