安卓:如何从蓝牙设备控制音乐服务的播放/暂停



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

请指导如何从蓝牙设备控制音乐控制(播放/暂停/下一个/上一个)。

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

如媒体播放正确方式中所述,您必须注册为"首选媒体应用程序"。当您使用 MediaSessionCompat 时,这要容易得多,如 MediaSessionCompat 视频中所述:

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)

最新更新