移动开发 \ Android \ Android7.0使用Intent打开文件

Android7.0使用Intent打开文件

总点击519
简介:版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/u012691505/article/details/71080275

版权声明:本文为博主原创文章,未经博主允许不得转载。 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

<provider

android:name="android.support.v4.content.FileProvider"

android:authorities="${applicationId}.fileprovider"

android:exported="false"

android:grantUriPermissions="true">

</provider>

defaultConfig {

applicationId "xxx"

minSdkVersion 17

targetSdkVersion 25

versionCode 6

versionName "1.0.5"

}


authorities:设置FileProvider的控制域

exported:设置FileProvider不需要是公开的

grantUriPermissions :授予对文件的临时访问权限


2.创建file_paths文件

<?xml version="1.0" encoding="utf-8"?>

<resources>

<paths>

<external-path name="my" path=""></external-path>

</paths>

</resources>

<paths>有很多可直接利用的目录

<files-path name="name" path="path" /><!--Context.getFilesDir()-->

<cache-path name="name" path="path" /> <!--getCacheDir()-->

<external-path name="name" path="path" /><!--Environment.getExternalStorageDirectory()-->

<external-files-path name="name" path="path" /><!--表示应用程序外部存储区域根目录中的文件。

该子目录的根路径与Context#getExternalFilesDir(String)Context.getExternalFilesDir(null)返回的值相同。-->

<external-cache-path name="name" path="path" /><!--Context.getExternalCacheDir()-->

3.配置file_paths

<meta-data

android:name="android.support.FILE_PROVIDER_PATHS"

android:resource="@xml/file_paths"/>

 provider整体配置:

<provider

android:name="android.support.v4.content.FileProvider"

android:authorities="${applicationId}.fileprovider"

android:exported="false"

android:grantUriPermissions="true">

<meta-data

android:name="android.support.FILE_PROVIDER_PATHS"

android:resource="@xml/file_paths"/>

</provider>


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属性值

意见反馈 常见问题 官方微信 返回顶部