Tag Archives: Failed to Share Images

Android7.0+ Failed to Share Images: exposed beyond app through ClipData.Item.getUri()

In Android 7.0 and above, the error exposed beyond app through ClipData.Item.getUri() occurs when sharing image files

reason

In fact, it is because of the problem caused by the Uri path enabled in versions 7.0 and above that we are not allowed to use file://it, only allowed to use content://it. We need to do the adaptation of FileProvider to solve this problem, or it will be simple and rude, and directly verify this to the close Lose

Solution (turn off the verification of uri)

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();

Write the above code in the application

Solution (adapted to FileProvider)

Create an xml folder in res (if the folder already exists, skip this step), create a file named myfileprovider.xml(the name can be arbitrary)

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>

After that, declare this Provider in AndroidManifest.xml (the following code only needs to change the values ​​in the authorities and resources)

<application>
  ...
     <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="site.starsone.demo.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <!-- ressource file to create -->
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/myfileprovider">  
        </meta-data>
    </provider>
</application>

Finally, when building the uri of the image file, use the following method to build (you can add a version judgment by the way, and use this method to build the Uri for Android 7.0 and above)

Uri imageUri = FileProvider.getUriForFile(
    MainActivity.this,
    "site.starsone.demo.provider", //(Use your package name+“.provider" )
    imageFile);

PS: The third parameter above is actually the authoritiesproperty defined by Provider in AndroidMainfest