Solution of fileuriexposedexception for Android 7.0 behavior change

The source of this article is as follows 27512671/article/details/71439571

When we develop functions related to [sharing files between applications], we often report this runtime exception on Android 7.0. Why do we run the code with no problem below Android 7.0 on Android 7.0 +?This is mainly from a behavior change in Android 7.0!

For Android 7.0-oriented applications, the strictmode API policy implemented by the Android framework prohibits the disclosure of file:// URI outside your application. If an intent containing a file URI leaves your application, the application fails and a fileuriexposedexception occurs. As shown in the figure:

To share files between applications, you should send a content:// URI and grant temporary access to the URI. The easiest way to do this is to use the fileprovider class.

Usage of fileprovider class:

Step 1: define a fileprovider list entry for your application. This entry can declare an XML file, which is used to specify the directory that the application can share.

<manifest xmlns:android=""
                android:resource="@xml/filepaths" />

In this code, android:authorities Attribute should be unique. It is recommended to use [application package name + fileprovider]. It is recommended to write this android:authorities= ”${applicationId}.file_ The application package name can be found automatically.
The meta data tag specifies a path, which uses the XML file specified by resource to indicate the path:
the XML file is as follows:

<?xml version="1.0" encoding="utf-8"?>
    <external-files-path name="bga_upgrade_apk" path="upgrade_apk" />

The way to obtain URI should also be treated differently according to the current Android system version

      File dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(getApplicationContext(),
                    "com.mqt.android_headicon_cut.file_provider", new File(dir, TEMP_FILE_NAME));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));

So the problem is solved. Paste an example of installing APK adapter 7.0: 27512671/article/details/70224978


Read More: