I am new to Android and Java. I have been working with the MediaPlayer and AudioManager examples provided by the Android Developer and other websites.
What I have noticed is that for the call to requestAudioFocus() there seems to be two separate signatures that are used. For example, from the http://ift.tt/1gulC2h site there is:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// could not get audio focus.
}
With the following text:
"The first parameter to requestAudioFocus() is an AudioManager.OnAudioFocusChangeListener, whose onAudioFocusChange() method is called whenever there is a change in audio focus. Therefore, you should also implement this interface on your service and activities. For example:" (With the following code:)
class MyService extends Service
implements AudioManager.OnAudioFocusChangeListener {
// ....
public void onAudioFocusChange(int focusChange) {
// Do something based on focus change...
}
}
Then from the site: http://ift.tt/10sElNh there is:
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
...
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
// Start playback.
}
with:
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
// Pause playback
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Resume playback
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
// Stop playback
}
}
};
I've seen this dichotomy across numerous sites giving sample code for handling changes in audio focus. My understanding is that "this" provides context of the application's current state. I do not understand why in some cases "this" is the correct parameter while in other cases a handle to a change listener is the correct parameter when calling requestAudioFocus().
In fact the first example I provided states the first parameter should be an AudioManager.OnAudioFocusChangeListener. But "this" is used.
If you could explain why "this" is used instead of an AudioManager.OnAudioFocusChangeListener is used as a parameter it would be greatly appreciated. Thanks in advance and Happy New Year! Jim
Aucun commentaire:
Enregistrer un commentaire