如何检测连接的蓝牙外围设备(自拍杆)的点击事件?

时间:2014-12-12 09:14:22

标签: android bluetooth bluetooth-lowenergy android-bluetooth

我将自拍杆连接到手机上。我可以使用以下代码找到设备ID:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        this.registerReceiver(mReceiver, filter);
}

  //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                //Device is now connected
                Toast.makeText(getApplicationContext(), "ACTION_ACL_CONNECTED" + device, Toast.LENGTH_LONG).show();
            }
         }
    };

我的问题是如何检测此连接的外围设备的按键按下事件?

代码片段/教程/评论形式的帮助非常值得注意。 谢谢!!!

编辑:

当我按下Selfie stick按钮时,音量+按钮会听取事件

3 个答案:

答案 0 :(得分:2)

我找到了答案。这很简单。只需覆盖Activity的onKeyDown()方法即可。

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    return super.onKeyDown(keyCode, event);
}

此处keyCode是返回的事件名称。

答案 1 :(得分:1)

我对您的代码稍作修改。请查看它是否有用

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    IntentFilter a_filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    this.registerReceiver(mReceiver, a_filter);
    IntentFilter b_filter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON);
    **b_filter.setPriority(1000);** 
    this.registerReceiver(mReceiver, b_filter);
}

//侦听蓝牙广播的BroadcastReceiver

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Device is now connected
            Toast.makeText(getApplicationContext(), "ACTION_ACL_CONNECTED" + device, Toast.LENGTH_LONG).show();
        }

    if (!Intent.ACTION_CAMERA_BUTTON.equals(action)) {
        return;
    }
    KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
    if (event == null) {
        return;
    }
    int action = event.getAction();
    if (action == KeyEvent.ACTION_DOWN) {
    // do something
    Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show(); 
    }
    abortBroadcast();
    }
 };

答案 2 :(得分:0)

使用accessibility service,可以实现自动点击。

Answer explained here,可能对您有所帮助!