lixplor / android-Q-A

🐞 android related questions and answers
0 stars 0 forks source link

Android N(7.0) FileUriExposedException #76

Closed lixplor closed 7 years ago

lixplor commented 7 years ago

7.0报错

lixplor commented 7 years ago

file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat). And here is the solution.

原因:

解决:

FileProvider使用示例

步骤:

  1. AndroidManifest.xml<application>标签内, 增加<provider>标签, 并填写相关信息
  2. res目录下, 创建xml目录, 创建provider_paths.xml文件, 并填写相关信息. path="."说明共享外部存储的根目录具有访问权限
  3. 判断当前系统版本, 如果是7.0则修改之前获取文件URI的方法Uri.fromFileFileProvider.getUriForFile
// AndroidManifest.xml
-----------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>
// provider_paths.xml
---------------------

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
// 按系统版本区别使用方法
--------------------------

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    // 7.0及以上
    Uri photoURI = FileProvider.getUriForFile(context,
        BuildConfig.APPLICATION_ID + ".provider",
        createImageFile());
} else {
    // 7.0以下
    Uri photoURI = Uri.fromFile(createImageFile());
}