Ashish Agrawal
Ashish Agrawal

Reputation: 1977

Pause music when call received and play music when call disconnected

I want to pause music when call is received and play music when call is disconnected.

for this i created

<receiver android:name="my receiver class">
    <intent-filter>
       <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>

in my receiver class i did this

if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
    //Pause Music
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE) 
    || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
    System.out.println("on phone disconnected");
    //Play music
}

With this i am able to pause music when i receive call but when call get disconnected then music is played after delay of 1-5 minute.

please help me

Upvotes: 0

Views: 148

Answers (2)

vaibhav
vaibhav

Reputation: 816

I would recommend implementing AudioManager.OnAudioFocusChangeListener in the class you are dealing with mediaplayer.

First request AudioFocus like this

    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.
}

then override onAudioFocusChange method

@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN: Log.d("Audio focus gained"); // when call is ended
            //play music
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: Log.d("Audio focus lost transient"); // Means a call is coming


        case AudioManager.AUDIOFOCUS_LOSS: Log.d("Audio focus lost"); // When call is received
            //pause music
            break;

        default: Log.d("Focus changed : " + focusChange);
    }
}

Here is the documentation AudioFocus

Upvotes: 1

Sattar Hummatli
Sattar Hummatli

Reputation: 1408

Hope this will help

On activity or fragment do following

@Override
public void onStart() {
    // Start music
    super.onStart();
}

@Override
public void onStop() {
    // Stop music
    super.onStop();
}

Upvotes: 1

Related Questions