首先,让我们来回顾下 Google官方 在 Android 5.0 引入的媒体应用框架:Android MediaSession框架简析。
然后,由于支持 蓝牙音乐 的音乐类App,也是基于 MediaBrowserService 实现的功能,所以音乐类App会根据 Android系统 的版本,进行客户端 MediaBrowser 连接服务端 MediaBrowserService 的初始化操作。
最后,若连接成功、获取到 MediaController,则下发相应的指令经 MediaBrowserService 转送到 蓝牙服务,控制音乐的切换、播放。
App 通过 MediaBrowserService 与 蓝牙服务 通信:

1. Android P 及之前
实际是通过 BluetoothAvrcpController 接口的 sendPassThroughCmd() 方法,往 蓝牙服务 下发控制指令。
1 2 3 4 | mMediaBrowser = new MediaBrowserCompat(this, new ComponentName("com.android.bluetooth", "com.android.bluetooth.a2dpsink.mbs.A2dpMediaBrowserService"), mConnectionCallback, null); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * Implements the MediaBrowserService interface to AVRCP and A2DP * * This service provides a means for external applications to access A2DP and AVRCP. * The applications are expected to use MediaBrowser (see API) and all the music * browsing/playback/metadata can be controlled via MediaBrowser and MediaController. * * The current behavior of MediaSession exposed by this service is as follows: * 1. MediaSession is active (i.e. SystemUI and other overview UIs can see updates) when device is * connected and first starts playing. Before it starts playing we do not active the session. * 1.1 The session is active throughout the duration of connection. * 2. The session is de-activated when the device disconnects. It will be connected again when (1) * happens. */ public class A2dpMediaBrowserService extends MediaBrowserService { // 省略代码 } |
2. Android Q 开始
A2dpMediaBrowserService 已被删除,使用 BluetoothMediaBrowserService 做替代。
1 2 3 4 | mMediaBrowser = new MediaBrowserCompat(this, new ComponentName("com.android.bluetooth", "com.android.bluetooth.avrcpcontroller.BluetoothMediaBrowserService"), mConnectionCallback, null); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * Implements the MediaBrowserService interface to AVRCP and A2DP * * This service provides a means for external applications to access A2DP and AVRCP. * The applications are expected to use MediaBrowser (see API) and all the music * browsing/playback/metadata can be controlled via MediaBrowser and MediaController. * * The current behavior of MediaSession exposed by this service is as follows: * 1. MediaSession is active (i.e. SystemUI and other overview UIs can see updates) when device is * connected and first starts playing. Before it starts playing we do not active the session. * 1.1 The session is active throughout the duration of connection. * 2. The session is de-activated when the device disconnects. It will be connected again when (1) * happens. */ public class BluetoothMediaBrowserService extends MediaBrowserService { // 省略代码 } |
参考:
IVI 连接
蓝牙和NFC
蓝牙音乐之AVRCP在安卓系统中的实现