Using synchronization for audio focus in android

62 Views Asked by At

https://developer.android.com/reference/android/media/AudioFocusRequest

This is a link to android developers' documentation on AudioFocusRequest. Following are some code snippets from the code example given in that documentation. I doubt that why was there a need to use synchronized block in these lines of code? I know what is the function of a synchronized block. What I would like to know is what could go wrong if that block of code is not synchronized in this case.

Code snippet of requestAudioFocus:

    int res = mAudioManager.requestAudioFocus(mFocusRequest);
 synchronized (mFocusLock) {
     if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
         mPlaybackDelayed = false;
     } else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
         mPlaybackDelayed = false;
         playbackNow();
     } else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
        mPlaybackDelayed = true;
     }
 }

Code snippet of OnFocusChangeListener:

@Override
 public void onAudioFocusChange(int focusChange) {
     switch (focusChange) {
         case AudioManager.AUDIOFOCUS_GAIN:
             if (mPlaybackDelayed || mResumeOnFocusGain) {
                 synchronized (mFocusLock) {
                     mPlaybackDelayed = false;
                     mResumeOnFocusGain = false;
                 }
                 playbackNow();
             }
             break;
         case AudioManager.AUDIOFOCUS_LOSS:
             synchronized (mFocusLock) {
                 // this is not a transient loss, we shouldn't automatically resume for now
                 mResumeOnFocusGain = false;
                 mPlaybackDelayed = false;
             }
             pausePlayback();
             break;
         case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
         case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
             // we handle all transient losses the same way because we never duck audio books
             synchronized (mFocusLock) {
                 // we should only resume if playback was interrupted
                 mResumeOnFocusGain = mMediaPlayer.isPlaying();
                 mPlaybackDelayed = false;
             }
             pausePlayback();
             break;
     }
 }

I hope my doubt was clear. Thanks in advance.

0

There are 0 best solutions below