use of android.media.AudioManager.OnAudioFocusChangeListener in project ultrasonic by ultrasonic.
the class Util method requestAudioFocus.
public static void requestAudioFocus(final Context context) {
if (!hasFocus) {
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
hasFocus = true;
audioManager.requestAudioFocus(new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
DownloadService downloadService = (DownloadService) context;
if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) && !downloadService.isJukeboxEnabled()) {
if (downloadService.getPlayerState() == PlayerState.STARTED) {
SharedPreferences preferences = getPreferences(context);
int lossPref = Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
if (lossPref == 2 || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
lowerFocus = true;
downloadService.setVolume(0.1f);
} else if (lossPref == 0 || (lossPref == 1)) {
pauseFocus = true;
downloadService.pause();
}
}
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
if (pauseFocus) {
pauseFocus = false;
downloadService.start();
} else if (lowerFocus) {
lowerFocus = false;
downloadService.setVolume(1.0f);
}
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isJukeboxEnabled()) {
hasFocus = false;
downloadService.pause();
audioManager.abandonAudioFocus(this);
}
}
}, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
}
Aggregations