版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/u012691505/article/details/71080275
软件使用过程中,有人反馈调用Intent打开文件地方无法出现选择。以为是个别用户手机上没有此类软件。后查看发现这些用户手机系统都是android7.0,查看7.0对于Intent的使用发现The increased level of file access security offered by a content URI makes FileProvider a key part of Android's security infrastructure.
android7.0之后,安全级别升级了。为了保护源文件,所以限制了其访问权限。使用第三方应用打开文件的时候会通过FileProvider ,生成 content URI允许您使用临时访问权限来授予读取和写入访问权限。关于FileProvider的介绍和使用。
我需要使用的功能是打开pdf
1.配置文件中定义FileProvider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
defaultConfig {
applicationId "xxx"
minSdkVersion 17
targetSdkVersion 25
versionCode 6
versionName "1.0.5"
}
authorities:设置FileProvider的控制域
exported:设置FileProvider不需要是公开的
grantUriPermissions :授予对文件的临时访问权限
2.创建file_paths文件
有很多可直接利用的目录
3.配置file_paths
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
provider整体配置:
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
4.生成文件的 content URI,并调用文件
private void show(String file) {
try {
Uri uri = null;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(this,"xx",new File(file));
} else {
uri = Uri.fromFile(new File(file));
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri,"application/pdf");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
xx:配置文件中为provide配置的authorities属性值