我正在尝试在 Oreo 中共享一个音频文件。如果文件在设备的内部存储中,它运行正常,但如果文件存在于外部存储中,它会崩溃并给出此异常 - android.os.FileUriExposedException。
如何解决这个问题:
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"));
}
list :
<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>
最佳答案
如果您的应用使用 Uri 与其他应用共享文件,则您可能在 API 24+ 上遇到过此错误。
第一步
将提供程序添加到您的 list 文件
<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>
第 2 步
创建 XML 文件 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>
第 3 步
添加新代码
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);
关于android - 在 Oreo 中共享文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51121149/