如何以编程方式使 Android 手机在来电时静音?(比如在来电时按电源按钮)?
我知道setStreamMute
and adjustStreamVolume
,但我认为有更好的方法。
如何以编程方式使 Android 手机在来电时静音?(比如在来电时按电源按钮)?
我知道setStreamMute
and adjustStreamVolume
,但我认为有更好的方法。
setStreamMute()
在 Build 版本 23 (marshmallow) 及以上版本中已弃用。您可以adjustStreamVolume()
用于棉花糖及以上。
public void adjustAudio(boolean setMute) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int adJustMute;
if (setMute) {
adJustMute = AudioManager.ADJUST_MUTE;
} else {
adJustMute = AudioManager.ADJUST_UNMUTE;
}
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, adJustMute, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_ALARM, adJustMute, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, adJustMute, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, adJustMute, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, adJustMute, 0);
} else {
audioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, setMute);
audioManager.setStreamMute(AudioManager.STREAM_ALARM, setMute);
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, setMute);
audioManager.setStreamMute(AudioManager.STREAM_RING, setMute);
audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, setMute);
}
}
你可以像这样调用这个方法,
adjustAudio(true) // To mute all the system, ringer, alarm, music, notification sounds on any event like button click.
adjustAudio(false) // To unmute all the system, ringer, alarm, music, notification sounds on any event like button click.