We create our own class inheriting FileProvider
in order to make sure our FileProvider doesn't conflict with FileProviders declared in imported dependencies. First create class with name GenericFileProvider
like this:
import android.support.v4.content.FileProvider;
public class GenericFileProvider extends FileProvider {
}
Then create provider_paths.xml
inside res/xml
folder. Folder may be needed to created if it doesn't exist. The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".")
with the name external_files.:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="." />
</paths>
Now in manifest inside application
tag, add this lines:
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.my.package.name.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
Then Try this code:
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".my.package.name.provider", new File(Objects.requireNonNull(sharePath))));
startActivity(Intent.createChooser(share, "Share Sound File"));