Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AUDIOFOCUS_LOSS called after a phone call in android

I'm trying to pause media player when the phone rings. I use the sample code from android site. It's like this;

public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            // resume playback
            if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
                mMediaPlayer.start();
                mMediaPlayer.setVolume(1.0f, 1.0f);
            }

            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            // Lost focus for an unbounded amount of time: stop playback and
            // release media player
            stopMediaPlayer();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            // Lost focus for a short time, but we have to stop
            // playback. We don't release the media player because playback
            // is likely to resume
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.pause();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // Lost focus for a short time, but it's ok to keep playing
            // at an attenuated level
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.setVolume(0.1f, 0.1f);
            break;
        }
    }

When the phone rings AUDIOFOCUS_LOSS_TRANSIENT is sent; which is OK. And when the call ends the AUDIOFOCUS_GAIN is sent and the player continue to play; which is also OK. But right after sending AUDIOFOCUS_GAIN, AUDIOFOCUS_LOSS is sent. Have any ideas why it is losing audio focus? Thx in advance.

like image 899
syloc Avatar asked Sep 08 '12 20:09

syloc


1 Answers

Two things to check: 1) Do you have a play button for instance, that when clicked, requests focus and starts playback? I had a problem once that they played a "tick" sound to provide feedback of a click. They would take audio focus away from my app when that happened. In your XML set this value to false for all your buttons in that activity:

android:soundEffectsEnabled = 'false'

2) Check for the installation of other media player apps that also request focus. Are they requesting focus right after losing it? If so there's not much you can do about this other than warn your users not to install this app.

like image 63
ajacian81 Avatar answered Nov 08 '22 16:11

ajacian81