主要解决sdk version >= 24时,sdcard文件的访问需要调用FileProvider;
其他文件的访问例如图片,也需要使用FileProvider
private static void startInstallApk(Context context, String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
uri = FileProvider.getUriForFile(context.getApplicationContext(), context
.getPackageName() + ".fileprovider", new File(filePath));
} else {
uri = Uri.fromFile(new File(filePath));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}
- 添加FileProvider
- 在AndroidManifest.xml下添加
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="app_package_name.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2.在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/app_package_name/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
3.修改代码适配Android N
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
参考链接
http://blog.csdn.net/yy1300326388/article/details/52787853
网友评论