开发音乐应用。在我的音乐服务中,我编写了一个自定义广播接收器。它适用于 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();
}
}
}
最佳答案
如 Media playback the right way talk 中所述,您必须注册为“首选媒体应用程序”。当您使用 MediaSessionCompat 时,这会容易得多如 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);
关于java - Android:如何从蓝牙设备控制音乐服务播放/暂停?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35779209/