代码之家  ›  专栏  ›  技术社区  ›  Lechucico

如何连接到配对的BLE设备

  •  1
  • Lechucico  · 技术社区  · 7 年前

    我目前有一个设备与我的智能手机配对(Micro:Bit BBC)。我的应用程序必须连接到它,在失去连接的情况下重新连接,并读取该设备提供的一个特征。

    我是Android新手。我已经阅读了此链接 Android BLE SDK 但我不能理解所有的东西,代码中有一些部分缺失了。

    我知道如何查找配对设备,但我不知道接下来该怎么做:

    bleAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
    Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
    

    这向我展示了唯一的绑定设备(BBC micro:bit[zogav])。如何连接到该设备,保持连接活动,并在micro:位超出范围时重新连接?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Salman Naseem    7 年前

    所以在得到 Paired Devices ,找到您的设备并按如下方式连接:

    BluetoothAdapter bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
                Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
                for(BluetoothDevice d: pairedDevices){
                    if(d.getAddress().equals("Your Device MAC")){
                       d.connectGatt(MainActivity.this, true, new BluetoothGattCallback() {
                            @Override
                            public void onConnectionStateChange(BluetoothGatt 
                                   gatt, int status, int newState) {
                                super.onConnectionStateChange(gatt, status, newState);
                                switch (newState) {
                                    case BluetoothProfile.STATE_CONNECTED:
                                        Log.i("GattCallback", "connected");
                                        gatt.getServices();
                                        break;
                                    case BluetoothProfile.STATE_DISCONNECTED:
                                        Log.i("GattCallback", "Disconnected");
                                        break;
                                }
                            }
                        });
                    }
                }
    

    实现 Auto Connect 设置 自动连接 变量 true 在里面 device.connectGatt(context, Auto Connect, BluetoothGattCallback); .