在Android 13中通过NotificationManager.notify更新没有POST_NOTIFICATIONS权限的前台服务的MediaStyle通知

问题描述 投票:0回答:1

我的应用程序以 API 33 为目标,并运行前台服务来播放在线音乐。

一旦通过

startForeground(notification_Id, notification)
启动通知,我可以通过
notificationManager.notify(notification_Id, notification)
更新通知,但是 Android Studio 告诉我缺少
android.permission.POST_NOTIFICATIONS
权限。

即使我在 AndroidManifest 中包含该权限,我也不需要要求用户授予更新通知的权限。

任何人都可以确认这种更新通知的方法是否有效或者是否存在安全漏洞? 显然该方法有效,但我在 Android 13+ 的文档中没有找到任何参考

谢谢你。

android foreground-service android-13 android-notification.mediastyle
1个回答
0
投票

您似乎遇到了与具有

POST_NOTIFICATIONS
权限的 Android 13+ 中的 MediaStyle 通知更新相关的问题。 Android 在最近的版本中引入了与安全和权限相关的更改,这可能会影响通知的处理方式。

在 Android 11 (API 30) 及更高版本中,引入了

POST_NOTIFICATIONS
授权以加强通知的安全性。要使用此授权,您需要征求用户的许可。

以下是应对这种情况的方法:

  1. 确保您已在 AndroidManifest.xml 文件中包含
    POST_NOTIFICATIONS
    授权:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  1. 使用代码中的
    requestPermission()
    函数向用户请求此权限。例如:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    NotificationManager notificationManager = getSystemService(NotificationManager.class);
    if (notificationManager != null) {
        NotificationManager.Policy policy = notificationManager.getNotificationPolicy();
        if (!policy.isCategoryAllowed(Notification.CATEGORY_CALLS)) {
            Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
            startActivity(intent);
        }
    }
}
  1. 当您想要更新通知时,您可以随时使用
    NotificationManager.notify()
    。确保
    notification_Id
    与您要更新的通知 ID 匹配。

这应该允许您更新前台服务的 MediaStyle 通知而不会出现错误。但是,请记住,出于安全原因,通知权限很重要,因此在必要时请求用户许可很重要。

© www.soinside.com 2019 - 2024. All rights reserved.