Android 6: cannot share files anymore?

Daniele B picture Daniele B · Oct 7, 2015 · Viewed 12.1k times · Source

I am sharing an image, and this code works properly for devices before Android 6:

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.fromFile(new File(mFilename));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
mContext.startActivity(Intent.createChooser(shareIntent, mChooserTitle));

However I get the toast error "can't attach empty files" when I try to share using Android 6.

I verified that the file exists and it's not zero-length.

Anyone has a solution for this?

Answer

Daniele B picture Daniele B · Oct 7, 2015

I solved it by implementing a FileProvider, as suggested by @CommonsWare

You first need to configure a FileProvider:

  • first, add the <provider> to your file manifest XML

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.myfileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_provider_paths" />
    </provider>
    
  • second, define your file paths in a separate XML file, I called it "file_provider_paths.xml"

    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="share" path="/" />
    </paths>
    

you can find the complete explanation in this documentation page

after you have set up your file provider in XML, this is the code to share the image file:

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri fileUri = FileProvider.getUriForFile(mContext, "com.myfileprovider", new File(mFilename));
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
mContext.startActivity(Intent.createChooser(shareIntent, mChooserTitle));