简体   繁体   中英

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.

You can access it like that (called inside an Activity in this example):

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 :

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

for 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.

As mentioned is this answer , you'll need to declare ACCESS_NOTIFICATION_POLICY and actively request access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM