1. 程式人生 > >Android監聽藍芽耳機的按鍵事件 藍芽無法響應KeyEvent監聽不到

Android監聽藍芽耳機的按鍵事件 藍芽無法響應KeyEvent監聽不到

需求:藍芽耳機的按鍵事件,暫停/播放 音訊/視訊 ,無法響應藍芽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"/>