需求:蓝牙耳机的按键事件,暂停/播放 音频/视频 ,无法响应蓝牙KeyEvent的事件
此问题是由于中的蓝牙KeyEvent监听不到导致的,可以通过以下方法监听蓝牙按键事件
private MediaSession mSession;//在OnResume中使用createMediaSession()方法create
private void createMediaSession() {
Log.v(TAG, "createMediaSession() mSession= " + mSession);
if (mSession == null) {
mSession = new MediaSession(mContext, VideoPlayerActivity.class.getSimpleName());
mSession.setCallback(mSessionCallback);
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
mSession.setActive(true);
}
}
//在OnPause中使用releaseMediaSession()方法release
private void releaseMediaSession() {
Log.v(TAG, "releaseMediaSession() mSession=" + mSession);
if (mSession != null) {
mSession.setCallback(null);
mSession.setActive(false);
mSession.release();
mSession = null;
}
}
private final MediaSession.Callback mSessionCallback = new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(Intent mediaIntent) {
if (mSession == null || mediaIntent == null) {
Log.v(TAG, "SessionCallback mSession= " + mSession + "mediaIntent= " + mediaIntent);
return false;
}
if (Intent.ACTION_MEDIA_BUTTON.equals(mediaIntent.getAction())) {
KeyEvent event = (KeyEvent) mediaIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
Log.v(TAG, "SessionCallback event= " + event);
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
onKeyDown(event.getKeyCode(),event);
onKeyUp(event.getKeyCode(),event);
return true;
}
}
return false;
}
};
这样就可以响应onKeyUp(); 或 onKeyDown();
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { Log.d(TAG, "onKeyUp() keycode=" + keyCode); switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PAUSE: //暂停
return true;
case KeyEvent.KEYCODE_MEDIA_PLAY: //播放 return true; } return super.onKeyUp(keyCode, event);}
并且需要在 添加权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>