简体   繁体   English

Android:如何从代码中禁用所有第三方应用程序的通知声音?

[英]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.

相关问题 如何报告JVM中的所有异常,无论是自己的代码还是第三方代码? - How to report all exceptions in JVM, be it own or third-party code? 如何在我自己的应用程序中禁用EditText中的所有第三方键盘? - How to disable all third-party keyboard in EditText in my own application? 从Eclipse中的第三方jar查看源代码 - Viewing source code from a third-party jar in Eclipse 如何杀死从第三方库导入的线程? - How to kill a thread imported from third-party lib? 如何模拟来自第三方库的类的静态调用 - How to mock a static call on a class from a third-party library 如何调试第三方Gradle插件? - How to debug a third-party Gradle plugin? Android:是否可以直接从第三方api发送推送通知? - Android: Is it possible to send push notifications directly from third party api? 如何自动列出Java + React项目中使用的所有第三方组件? - How to automatically list all third-party components used in a java + React project? 如何在提交给ExecutorService的Task中处理第三方Java代码,以防它具有无限循环 - How to handle third-party Java code in a Task submitted to ExecutorService in case it has an infinite loop 如何将第三方jar文件添加到我的android应用jar文件中? - How to add third-party jar files into my android application jar file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM