2--安卓7.0+的android.os.FileUriExposedException的解决方法

通过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);
9414344-089fd142e37201fe.png
音乐播放.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值