I use the following code to increase music volume when the user presses the VolumeUp
button:
@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
AudioManager audio = (AudioManager)getApplicationContext().getSystemService(AUDIO_SERVICE);
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
}
}
In the Google Developer Console, I’m seeing this ANR:
This Binder call may be taking too long, causing the main thread to
wait, and triggering the ANR.at android.os.BinderProxy.transactNative (Native method) at android.os.BinderProxy.transact (Binder.iava: 1154) at android.media.IAudioServiceSStub$Proxy.adjustStreamVolume (IAudioService.java: 1150) at android.media.AudioManager.adjustStreamVolume (AudioManager.java: 820) at com.example.MyActivity.onKeyDown (MyActivity.java:42)
Your app’s code results in the Binder call above. Code that triggers
Binder calls should be moved out of the main thread.
Should calls to AudioManager.adjustStreamVolume
be performed on a background Thread
?
@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
new Thread(this::increaseVolume).start();
return true;
}
}
private void increaseVolume() {
AudioManager audio = (AudioManager)getApplicationContext().getSystemService(AUDIO_SERVICE);
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
}