[英]Android: How to disable the sound of all third-party apps' notifications from code?
I need to disable all sounds of third-party apps' notifications from code.我需要从代码中禁用第三方应用程序通知的所有声音。
Something like this: when the app is open - all notifications from all apps are silent.像这样:当应用程序打开时 - 所有应用程序的所有通知都是静音的。 When the app closes - the sound settings return to what they were before.
当应用程序关闭时 - 声音设置会恢复到之前的状态。
How to implement it?如何实施? Is it possible to do this?
是否有可能做到这一点?
It seems the AudioManager is what you are looking for.看来AudioManager正是您要找的。
You can access it like that (called inside an Activity in this example):您可以像这样访问它(在本例中在 Activity 内部调用):
val audioManager: AudioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
To get the current volume (so you can restore it at a later point), use要获取当前音量(以便您可以在以后恢复它),请使用
audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)
When your app starts, you mute the notifications by calling当您的应用程序启动时,您可以通过调用将通知静音
for SDK < 23 :对于 SDK < 23 :
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0)
for SDK >= 23 :对于 SDK >= 23 :
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, 0)
Note as per official docs:根据官方文档注意:
From N onward, volume adjustments that would toggle Do Not Disturb are not allowed unless the app has been granted Do Not Disturb Access.
从 N 开始,除非应用程序已被授予“请勿打扰”访问权限,否则将不允许切换“请勿打扰”的音量调整。
As mentioned is this answer , you'll need to declare ACCESS_NOTIFICATION_POLICY
and actively request access.正如所提到的这个答案,您需要声明
ACCESS_NOTIFICATION_POLICY
并主动请求访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.