Alternative for deprecated AudioManger.setStreamMu

2019-06-15 19:15发布

AudioManger.setStreamMute is now deprecated with api 23 and it is preferred to use AudioManager.adjustStreamVolume with AudioManager.ADJUST_MUTE.

My problem is that this kind of flag is only supported with api 23 while my app is minimum api 16.

Is there an other way of muting the whole system?

If not, why would google deprecate this method?

2条回答
趁早两清
2楼-- · 2019-06-15 19:35

The way I would do it would be to use an if/else block to use the proper calls depending on the version of Android that the app is currently running under.

// Change the stream to your stream of choice. 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
   am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
} else {
   am.setStreamMute(AudioManager.STREAM_MUSIC, true);
}
查看更多
淡お忘
3楼-- · 2019-06-15 19:39

The accepted answer works fine in muting the system, but if you need to restore the state (e.g. when users pause / quit your app), please note that the semantics of the adjustStreamVolume and setStreamMute methods are different:

For setStreamMute, from the documentation:

The mute requests for a given stream are cumulative: the AudioManager can receive several mute requests from one or more clients and the stream will be unmuted only when the same number of unmute requests are received.

This does not seem to be the case for adjustStreamVolume with AudioManager.ADJUST_MUTE. In other words, if the status of the stream is already muted before you mute it with setStreamMute (stream, true), an immediate setStreamMute (stream, false) will leave it in muted state, while adjustStreamVolume with AudioManager.ADJUST_UNMUTE may unmute the stream.

Depending on the use case, to emulate the old semantics, one way is to check the mute state before muting, something like the following -

To mute:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!audioManager.isStreamMute(stream)) {
       savedStreamMuted = true;
       audioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
    }
} else {
    audioManager.setStreamMute(stream, true);
}

To unmute:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (savedStreamMuted) {
         audioManager.adjustStreamVolume(stream, AudioManager.ADJUST_UNMUTE, 0);
         savedStreamMuted = false;
    }
} else {
    // Note that this must be the same instance of audioManager that mutes
    // http://stackoverflow.com/questions/7908962/setstreammute-never-unmutes?rq=1
    audioManager.setStreamMute(stream, false);
}

This assumes users are unlikely to invoke another app to mute the stream in-between and expect the stream to stay muted after your app unmutes (anyway there seems no way to check this).

Incidentally, the isStreamMute method was previously hidden, and was only unhidden in API 23, enabling its use for this purpose.

查看更多
登录 后发表回答