Connection to specific HID profile bluetooth device

为君一笑 提交于 2019-12-01 00:21:38
Nihilus13

I figured out how to solve my problem. That was very helpful. First of all I needed to prepare reflection method which return input_device hidden constants of hid profile:

public static int getInputDeviceHiddenConstant() {
    Class<BluetoothProfile> clazz = BluetoothProfile.class;
    for (Field f : clazz.getFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
            try {
                if (f.getName().equals("INPUT_DEVICE")) {
                    return f.getInt(null);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, e.toString(), e);
            }
        }
    }
    return -1;
}

Instead of that function, I could use value 4, but i want to do it elegant.

Second step was to define listener of specific profile:

BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            Log.i("btclass", profile + "");
            if (profile == ConnectToLastBluetoothBarcodeDeviceTask.getInputDeviceHiddenConstans()) {
                List<BluetoothDevice> connectedDevices = proxy.getConnectedDevices();
                if (connectedDevices.size() == 0) {
                } else if (connectedDevices.size() == 1) {
                    BluetoothDevice bluetoothDevice = connectedDevices.get(0);
                    ...
                } else {
                    Log.i("btclass", "too many input devices");
                }
            }

        }

        @Override
        public void onServiceDisconnected(int profile) {

        }
    };

In third step I invoked

mBluetoothAdapter.getProfileProxy(getActivity(), mProfileListener,
            ConnectToLastBluetoothBarcodeDeviceTask.getInputDeviceHiddenConstant());

Everything clearly works and mProfileListener returns me list of specific profile bluetooth device/-es. Most interesting thing takes place in onServiceConnected() method, which returs object of hidden class BluetoothInputDevice :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!