private void startInstall(String filePath){
//分别进行7.0以上和7.0以下的尝试
File apkfile = new File(filePath);
if (!apkfile.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//7.0以上
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),"你的包名.FileProvider",apkfile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
}
startActivity(intent);
}
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的包名.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/rc_file_path" />
</provider>
- 其中,在res -> xml中新建rc_file_path.xml,如果没有xml包新建一个,内容如下
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/你的包名/" name="files_root"/>
<external-path path="." name="external_storage_root"/>
</paths>