我正在实施媒体按钮服务来处理耳机的媒体按钮事件(蓝牙或有线),对于某些特定的耳机(例如:BOSE QC35,APPLE airpods),该服务无法检测到的事件按钮首先单击,但可以检测到它的下一次单击。
例如:
让我们说在点击BOSE QC35 / AirPods的媒体按钮后我想结束互联网通话,点击媒体按钮后呼叫不会结束,而是呼叫被转到电话(我也可以听到) "呼叫结束" QC35上的语音点),当我再次点击媒体按钮时,呼叫将结束。
对于相同的实现,如果我使用Monster powerbeats2或任何有线耳机,呼叫将在第一次点击后结束
以下是代码:
public class SampleMediaButtonService extends MediaBrowserServiceCompat {
private MediaSessionCompat mSession;
private static final int POSITION = 0;
private static final float PLAYBACK_SPEED = 1f;
@Override
public void onCreate() {
super.onCreate();
initMediaSessions();
}
@Nullable
@Override
public BrowserRoot onGetRoot(@NonNull final String clientPackageName, final int clientUid,
@Nullable final Bundle rootHints) {
return null;
}
@Override
public void onLoadChildren(@NonNull final String parentId,
@NonNull final Result<List<MediaBrowserCompat.MediaItem>> result) {
}
private void initMediaSessions() {
mSession = new MediaSessionCompat(getApplicationContext(),
MediaButtonService.class.getSimpleName());
mSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
setSessionToken(mSession.getSessionToken());
mSession.setCallback(
new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
LOG.i("Handling media button click");
if (//CALL IS ACTIVE) {
//END the call
}
}
}
);
/* Keeping the initial state as STATE_PAUSED. This will ensure when button is clicked
* onPlay() is called.
*/
long actions = PlaybackStateCompat.ACTION_PLAY;
PlaybackStateCompat playbackStateCompat = new PlaybackStateCompat.Builder()
.setActions(actions)
.setState(PlaybackStateCompat.STATE_PAUSED, POSITION, PLAYBACK_SPEED)
.build();
mSession.setPlaybackState(playbackStateCompat);
mSession.setActive(true);
}
@Override
public int onStartCommand(final Intent startIntent, final int flags, final int startId) {
if (startIntent != null) {
// Try to handle the intent as a media button event wrapped by MediaButtonReceiver
MediaButtonReceiver.handleIntent(mSession, startIntent);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mSession.release();
}
}