Android: 如何通过代码关闭所有第三方应用的通知声音?

Android: How to disable the sound of all third-party apps' notifications from code?

我需要从代码中禁用所有第三方应用程序通知的声音。

是这样的:当应用程序打开时 - 来自所有应用程序的所有通知都是静音的。当应用程序关闭时 - 声音设置 return 恢复到之前的状态。

如何实现?是否有可能做到这一点?

看来 AudioManager 就是您要找的。

你可以这样访问它(在本例中在 Activity 中调用):

val audioManager: AudioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager

要获取当前音量(以便稍后恢复),请使用

audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)

当您的应用启动时,您可以通过调用

使通知静音

对于 SDK < 23:

audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0)

对于 SDK >= 23:

audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, 0)

根据官方文档注意:

From N onward, volume adjustments that would toggle Do Not Disturb are not allowed unless the app has been granted Do Not Disturb Access.

如前所述 ,您需要声明 ACCESS_NOTIFICATION_POLICY 并主动申请访问权限。