Android: 如何从蓝牙设备控制音乐服务play/pause?

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

开发音乐应用。在我的音乐服务中,我编写了一个自定义广播接收器。它适用于 Intent.ACTION_HEADSET_PLUG 但不适用于 Intent.ACTION_MEDIA_BUTTON.

请指导如何从蓝牙设备(Play/Pause/Next/Previous)控制音乐控件。

Intent.ACTION_HEADSET_PLUG 的代码是:

@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();
            }

        }
    }

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);

已接受的答案似乎无效

我用 ExoPlayer 以另一种方式实现了它

步骤#1 添加依赖项

    implementation 'com.google.android.exoplayer:exoplayer:2.13.1'
    implementation 'com.google.android.exoplayer:extension-mediasession:2.13.1'

第 2 步

        mediaSession = MediaSessionCompat(this, "Vion")
        val mediaSessionConnector = MediaSessionConnector(mediaSession!!)
        mediaSessionConnector.setMediaButtonEventHandler(object: MediaSessionConnector.MediaButtonEventHandler{
            override fun onMediaButtonEvent(player: Player, controlDispatcher: ControlDispatcher, mediaButtonEvent: Intent): Boolean {
                val event: KeyEvent = mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT) ?: return false
                if(event.action == KeyEvent.ACTION_UP) {
                    when(event.keyCode) {
                        KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {
                           
                        }
                        KeyEvent.KEYCODE_MEDIA_PAUSE -> {
                            
                        }
                        KeyEvent.KEYCODE_MEDIA_PLAY -> {
                            
                        }
                        KeyEvent.KEYCODE_MEDIA_NEXT -> {
                            
                        }
                    }
                }
                return true
            }
        })
        mediaSessionConnector.setPlayer(exoPlayer)