javaandroidandroid-intentandroid-bluetoothandroid-music-player

Android: How to control music service play/pause from bluetooth device?


Developing a music app. In my Music Service, I have written a custom broadcast receiver. It works with Intent.ACTION_HEADSET_PLUG but not with Intent.ACTION_MEDIA_BUTTON.

Please guide on how to control music controls from bluetooth devices (Play/Pause/Next/Previous).

Code for Intent.ACTION_HEADSET_PLUG is:

@Override
    public void onReceive(Context context, Intent intent) {

        // aux
        if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG))
        {
            int state = intent.getIntExtra("state", -1);

            if(state == 0)
            {
                // Headset is unplugged. PAUSE
                pauseSong();
                sendBroadcast();
            }
            else if(state == 1)
            {
                // headset is plugged
                resumeSong();
                sendBroadcast();
            }

        }
    }

Solution

  • As explained in the Media playback the right way talk, you must be registered as the 'preferred media app'. This is much easier when you use MediaSessionCompat as explained in the MediaSessionCompat video:

    ComponentName mediaButtonReceiver =
      new ComponentName(context, YourBroadcastReceiver.class);
    MediaSessionCompat mediaSession = 
      new MediaSessionCompat(context,
      tag, // Debugging tag, any string
      mediaButtonReceiver,
      null);
    mediaSession.setFlags(
      MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | 
      MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(this); // a MediaSessionCompat.Callback
    
    // This is what enables media buttons and should be called
    // Immediately after getting audio focus
    mediaSession.setActive(true);