Android 7.0 Notification Sound Issue

1,246 阅读1分钟

Android7.0NotificationSound

前言

最近遇到一个问题: 自定义Notification通知声音(一个外部存储MP3文件),Android7.0版本上无法正常播放。

分析

  1. 查阅代码是否正常执行,setSound是否设置有效Uri
    正常执行,设置的Uri有效
  2. 查看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无法播放

  1. adb shell dumpsys notification查看sound是否为设置的Uri
    sound为设置的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完成

参考

  1. Notifications, Sounds, Android 7.0, and Aggravation
  2. Google Issue Tracker
  3. Stackoverflow Issue

本文由 onlyloveyd 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2019/01/11 08:49