Android Studio – Earphone Button Pause in Background App

247 viewsandroid-studio earphone radio start/pause
0
Tuga Dyrdek | 14 xp

I am developing a Radio App.
I enter the app and start playing the music from a stream url. If I minimize it the music keeps playing in background.

Problem:
What I want is to stop the music with the earphones pause/start button when the music is playing in the background.

img: https://i.imgur.com/kXSatM0.png

Note: the pause/start button from the notification works fine. Also if I receive a call the music stops and after the end of the call, the music starts.

0
Kprabhu Got | 158 xp

Do like this, it can help you.

<application>

    <receiver android:name=”OuterClass$YourBroadcastReceiver”>

        <intent-filter>

           <action android:name=”android.intent.action.MEDIA_BUTTON” />

         </intent-filter>

    </receiver>

    <activity> … </activity>

</application>

mAudioManager =  (AudioManager) getSystemService(Context.AUDIO_SERVICE);

mReceiverComponent = new ComponentName(this,YourBroadcastReceiver.class);

mAudioManager.registerMediaButtonEventReceiver(mReceiverComponent);

// somewhere else

mAudioManager.unregisterMediaButtonEventReceiver(mReceiverComponent);

public static class YourBroadcastReceiver extends BroadcastReceiver{

    // Constructor is mandatory

    public MediaBroadcastReceiver ()

    {

        super ();

    }

    @Override

    public void onReceive(Context context, Intent intent) {

        String intentAction = intent.getAction();

        Log.i (TAG_MEDIA, intentAction.toString() + ” happended”);

        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {

            Log.i (TAG_MEDIA, “no media button information”);

            return;

        }

        KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

        if (event == null) {

            Log.i (TAG_MEDIA, “no keypress”);

            return;

        }

        // other stuff you want to do

    }

}