我有一个应用程序,其中我实现了一个开关按钮来打开和关闭音频。我非常理解使用adjustStreamVolume
仅适用于api 23及以上,而setStreamMute
已弃用,因此我会适当地处理逻辑。
但是,我遇到设备api低于api 23的音频状态问题,因为它在bein之前静音后没有取消静音。对于api 23及以上版本,交换机和音频状态仍然运行良好,但我需要有关如何正确静音和取消静音设备的设备api低于23的帮助。
这是我的逻辑。
public class SettingsActivity extends AppCompatActivity {
private Switch mSoundSwitch;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
AudioManager aManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
mSoundSwitch = (Switch) findViewById(R.id.soundSwitch);
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
mSoundSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
unmute();
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("sound", true);
editor.apply();
} else {
mute();
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("sound", false);
editor.apply();
}
}
});
// retrieving value from shared preferences (sound)
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
boolean isChecked = sharedPreferences.getBoolean("sound", true);
mSoundSwitch.setChecked(isChecked);
}
private void mute() {
//mute audio
aManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
} else {
aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
}
}
public void unmute() {
//unmute audio
aManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);
} else {
aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
}
}
}
答案 0 :(得分:0)
我用这段代码解决了我的问题:
private void mute() {
//mute audio
aManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
} else {
aManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
}
public void unmute() {
//unmute audio
aManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);
} else {
aManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
}
}