通过intent打开内置音乐播放器,传递一个Uri,但是崩了:
android.os.FileUriExposedException
貌似是安卓7.0+的锅,处理方法如下:
以本例包名com.toly1994.audio
为例,
以本例包名com.toly1994.audio
为例,
以本例包名com.toly1994.audio
为例,重要的话说三遍!,大家对应自己包名修改
1.AndroidManifest.xml的<application中:
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="com.toly1994.audio.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2.在res下新建xml文件夹及file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/com.toly1994.audio/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
3.封装
public class Compat {
public static void fileUri(Context context, Intent intent, File file, String type) {
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
intent.setDataAndType(contentUri, type);
} else {
intent.setDataAndType(Uri.fromFile(file), type);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
}
4.使用
File file = new File(PathUtils.getSDPath(), "toly/test.mp3");
Intent intent = new Intent(Intent.ACTION_VIEW);
Compat.fileUri(this, intent, file, "audio/mp3");
startActivity(intent);