【问题标题】:How to connect to a paired BLE device如何连接到配对的 BLE 设备
【发布时间】:2018-02-14 19:00:00
【问题描述】:

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

我是 Android 新手。我已经阅读了此链接Android BLE SDK,但我无法理解所有内容,并且该代码中的某些部分丢失了。

我知道如何查找配对设备,但不知道之后该怎么做:

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

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

【问题讨论】:

  • keep the connection alive 是什么意思?
  • 我的意思是我的智能手机订阅了一个特性并重新连接到 micro:bit,以防连接丢失。

标签: android bluetooth bluetooth-lowenergy


【解决方案1】:

所以在获得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 Connectdevice.connectGatt(context, Auto Connect, BluetoothGattCallback);中设置Auto Connect变量true

【讨论】:

  • 谢谢!我已经发布了另一个有更多疑问的问题:stackoverflow.com/questions/48810469/…
  • 对不起,我不知道为什么我启动LeScan时的地址是“D7:1E:5E:34:74:D1”,但是连接到这个设备+getBondedDevices()后,我得到了“66: F2:24:55:5E:A8"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多