版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/poorkick/article/details/86286155
前言
最近遇到一个问题:
自定义Notification通知声音(一个外部存储MP3文件),Android7.0版本上无法正常播放。
分析
- 查阅代码是否正常执行,setSound是否设置有效Uri正常执行,设置的Uri有效
- 查看Log发现权限问题相关Log
MediaPlayer: Couldn't open content://xxxxxxxx/new_order.mp3: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{ce87f22 2005:com.android.systemui/u0a18} (pid=2005, uid=10018) that is not exported from uid 10257
传递参数FileProvider Uri,com.android.systemui无访问权限,导致设置的MP3无法播放
- adb shell dumpsys notification查看sound是否为设置的Urisound为设置的Uri,正常
解决办法
使用grantUriPermissions()
grantUriPermission("com.android.systemui", sound,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
(这个具体情况可以根据上面分析中的Log确定包名)
使用android.resource
假设使用raw资源保存test.mp3文件,然后使用
Uri uri = Uri.parse("android.resource://“+ context.getPackageName() + R.id.test);
Uri uri = Uri.parse("android.resource://“+ context.getPackageName() + "/raw/test.mp3");
禁止严格模式&不使用FileProvider(不推荐)
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().build());
总结
-
Android7.0 注意Uri权限问题
-
Android8.0 注意setSound在NotificationChannel完成