1 添加文件在res/xml provider_paths.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <paths> <!--拍照--> <external-path name="camera_photos" path="" /> <!--安装包--> <external-path name="download" path="down"/> </paths> </resources>添加检查权限
if (ActivityCompat.checkSelfPermission(BAFMainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(BAFMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_READ_PHONE_STATE); }返回
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_READ_PHONE_STATE: if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { } break; default: break; } }判断是否7.0+版本
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) { Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID+".fileprovider",apkFile); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(contentUri,"application/vnd.android.package-archive"); }else{ Uri uri = Uri.parse("file://" + apkFile.toString()); intent.setDataAndType(uri, "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); }关于权限的问题,如果发现可以下载但是不能正常安装,请在manifest添加
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>