问题
I'm trying to share an audio file in Oreo. If the file is in internal storage of the device, it runs fine but if the file is present on the external storage it crashes giving this exception - android.os.FileUriExposedException.
How to solve this problem:
public void shareSong(SongInfoModel songInfoModel){
Uri uri = Uri.parse("");
File f = new File(songInfoModel.getData());
if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.N_MR1) {
uri = Uri.parse("file://" + f.getAbsolutePath());
}else {
uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", f);
}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(Intent.createChooser(share, "Share audio File"));
}
Manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
回答1:
If you have an app that shares files with other apps using a Uri, you may have encountered this error on API 24+.
Step 1
add provider to your manifest file
<manifest ...>
<application ...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
Step 2
Create XML file res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Step 3
add new code
File file ; // your code
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// Old Approach
install.setDataAndType(Uri.fromFile(file), mimeType);
// End Old approach
// New Approach
Uri apkURI = FileProvider.getUriForFile(
context,
context.getApplicationContext()
.getPackageName() + ".provider", file);
install.setDataAndType(apkURI, mimeType);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// End New Approach
context.startActivity(install);
来源:https://stackoverflow.com/questions/51121149/sharing-file-in-oreo-not-working