'Share PDF using intent in android not working in Android 12

Am not able to share PDF using intent only in android 12 but its working fine below version. Am downloading file and taking file Uri from download folder.

Download location:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

Error message: Sharing failed, please try again.

private void sharePDF() {
    Uri fileUri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", pdfFile);

    Intent share = new Intent();
    share.setAction(Intent.ACTION_SEND);
    share.putExtra(Intent.EXTRA_STREAM, fileUri);
    share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    share.setType("application/pdf");
    startActivity(Intent.createChooser(share, "Share Catalogue"));
}


Solution 1:[1]

I was facing an issue in Android 12 (API-31) mentioned below,

Error Log: java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.test.catalogue.provider/external/Download/test.pdf from pid=30787, uid=1000 requires the provider be exported, or grantUriPermission()

After many R&D, i have added few line and resolved share pdf file issue through intent.

share.setClipData(ClipData.newRawUri("", fileUri));
    share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

share.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

But still one issue is found here, some time we will get "sharing filed try again".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1