android – 蓝牙设备按钮按下应该在应用程序中触发Onclick Listener

我正在尝试制作一个应用程序,当在配对的蓝牙设备上按下按钮时,该应用程序会在应用程序中触发点击监听器.谷歌搜索几个小时后我想我无法发送蓝牙设备按钮的键码到广播接收器,如果键码匹配,那么我可以打电话给点击听众或者我的方法和理解是错的所以任何人都可以指导我还是指向正确的方法?提前致谢

蓝牙设备:蓝牙自拍遥控器AB快门3

我想要这样的东西
http://www.barbatricks.com/en/android-en/remap-ab-shutter-3-selfie-remote/

我尝试过以下链接供参考,但没有成功

How to capture key events from bluetooth headset with android

BroadcastReceiver for ACTION_MEDIA_BUTTON not working

How to detect bluetooth call/media button press in android app

http://blog.phonedeveloper.com/2015/04/how-to-receive-bluetooth-broadcast.html

最佳答案
自拍遥控器在Android中显示为蓝牙键盘,对吧?或者作为一般的HID(人机接口设备).

如果是这种情况,那么添加到Activity的onCreate();

takeKeyEvents(true);

这解释为in the documentation

Request that key events come to this activity. Use this if your
activity has no views with focus, but the activity still wants a
chance to process key events.

覆盖onKeyUp()(在您的Activity中)并为您要使用的键指定一些操作:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {

    switch (keyCode) {

        case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
            Log.d(this.getClass().getName(), "KEYCODE_MEDIA_PLAY_PAUSE");
            // Do something...

            return true;
        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
            Log.d(this.getClass().getName(), "KEYCODE_MEDIA_PREVIOUS");
            // Do something...

            return true;
        case KeyEvent.KEYCODE_MEDIA_NEXT:
            Log.d(this.getClass().getName(), "KEYCODE_MEDIA_NEXT");
            // Do something...

            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            Log.d(this.getClass().getName(), "KEYCODE_VOLUME_DOWN");
            // Do something...

            return true;
        case KeyEvent.KEYCODE_VOLUME_UP:
            Log.d(this.getClass().getName(), "KEYCODE_VOLUME_UP");
            // Do something...

            return true;
        case KeyEvent.KEYCODE_ENTER:
            Log.d(this.getClass().getName(), "KEYCODE_ENTER");
            // Do something...

            return true;
        default:
            return super.onKeyUp(keyCode, event);
    }
}

onKeyUp()方法is explained

Called when a key was released and not handled by any of the views
inside of the activity. So, for example, key presses while the cursor
is inside a TextView will not trigger the event (unless it is a
navigation to another object) because TextView handles its own key
presses.

The default implementation handles KEYCODE_BACK to stop the activity
and go back.

只需让系统处理您不想捕获的任何键.这是由默认块完成的.

只需检查来自遥控器的密码是什么,并删除不必要的情况.这些只是遥控器可能发送的密钥代码的一些候选者.

当然,任何适用于处理键盘的内容也适用于遥控器. (假设它是一个HID.但它们通常都是.带按钮的蓝牙耳机就是一个完全不同的故事.)

这将允许您在自己的应用程序中使用遥控器.我不明白为什么应该参与BroadcastReceivers或onClickListeners,但也许我错过了这一点.

如果你想要在后台运行的东西并将关键事件发送到其他应用程序/重新映射,则遥控器的键按下其他键码以触发系统服务,那么这也是一个不同的故事.

转载注明原文:android – 蓝牙设备按钮按下应该在应用程序中触发Onclick Listener - 代码日志