Bluetooth Pairing Google Glass

爱⌒轻易说出口 提交于 2019-12-04 19:18:49

So I will answer my own question as I just found the way.

So first, the discovery of devices is quite easy, in onCreate() I used (besides all other sort of code you need):

MyBT = BluetoothAdapter.getDefaultAdapter();
MyBT.startDiscovery();
Filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);                    // Register the BroadcastReceiver
Filter2 = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);         // Register the Bond changing state
registerReceiver(mReceiver, Filter);                                        // Don't forget to unregister during onDestroy
registerReceiver(mReceiver, Filter2);                                       // ******

Then at the BroadcastReceiver you need to manage the devices and the pairing requests:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {           // Create a BroadcastReceiver for ACTION_FOUND
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {                      // When discovery finds a device
            BluetoothDevice BTdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Get the BluetoothDevice object from the Intent
            ListDev.add(BTdevice);                                              // Add the device to an array adapter to show...
        }     
        if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
            BluetoothDevice device = ListDev.get(selectedDevice);
            byte[] pinBytes = getStrFromName(device.getName(),7,11).getBytes();  // My devices had their own pin in their name, you can put a constant pin here...  
            try {
                Log.d("MY_LOG", "Try to set the PIN");
                Method m = device.getClass().getMethod("setPin", byte[].class);
                m.invoke(device, pinBytes);
                Log.d("MY_LOG", "Success to add the PIN.");
                try {
                    device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
                    Log.d("MY_LOG", "Success to setPairingConfirmation.");
                } catch (Exception e) {
                    Log.e("MY_LOG", e.getMessage());
                    e.printStackTrace();
                } 

            } catch (Exception e) {
                Log.e("MY_LOG", e.getMessage());
                e.printStackTrace();
            }
        }
    }
}; 

After that the device is bonded and you can manage the connection with the UUID and the sockets just as in the Android webpage example.

Hope this helps!

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