问题描述:
应用内更新,下载apk调用系统api进行安装,在android8.0+手机上无法安装,在android8.0以下可以安装成功,看了看google for android 官网得知android8.0权限控制的更严格,安装应用需要应用本身具有“安装未知来源”权限。
解决方案:
一,如果构建 compileSdkVersion<27 先判断应用是否具有“安装未知应用”权限,没有则引导开启,有则调起安装View 其次安装是需要判断大于ADK.API>=24,条件成立则apk文件uri需要从FileProvider中获取,否则安装最简单方式调起安装。
例:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.xxx.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
xml目录下新建file_paths.xml
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android">;; <external-path name="pic" path="zzTong/" /> </paths>
调起安装
@TargetApi(Build.VERSION_CODES.O) private void openFile(File file) { HPLog.i(HPLog.LFP_TAG,"openFile:"+file.getAbsolutePath()); apkFile=file; //判读版本是否在8.0以上 if (Build.VERSION.SDK_INT >= 26) { //来判断应用是否有权限安装apk boolean installAllowed= getPackageManager().canRequestPackageInstalls(); HPLog.e(HPLog.LFP_TAG,"installAllowed="+installAllowed); if(installAllowed){ install(apkFile); }else { AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_INSTALL_APK). permission(Manifest.permission.REQUEST_INSTALL_PACKAGES). rationale(new RationaleListener() { @Override public void showRequestPermissionRationale(int requestCode, Rationale rationale) { AndPermission.rationaleDialog(DownloadApkActivity.this, rationale).show(); } }).send(); } } else { install(apkFile); } } private void install(File file){ Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= 24) { //provider authorities Uri apkUri = FileProvider.getUriForFile(this, "com.handpay.fileprovider", file); //Granting Temporary Permissions to a URI intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); }else { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); } startActivity(intent); }
二,compileSdkVersion>=27
如果构建SDK版本在27版本及以上则不需要判断是否有“安装未知应用”权限,直接调起安装应用即可,系统会自动提示。
例

private void install(File file){ Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); }
至此即可正常安装应用