繁体   English   中英

Android,非常简单的BLE示例,无法连接到设备

[英]Android, very Simple BLE Example, unable to connect to device

在工作中,我们有一台每隔几秒钟会在定制服务中更新一个定制特征并使用BLE的设备。 我要做的就是监视这些更新。 我的目标是编写最少量的代码,以连接到该设备,然后连接到服务,然后监视其特性。 但是我无法连接到设备。

每次通过扫描找到蓝牙设备时,都会调用此功能:

void checkDevice(BluetoothDevice device){
    if (targetFound) return;
    if (device.getAddress().equals(DEVICE_ADDRESS)){
        logger.append("-> Target device found with name: " + device.getName() + "\n");
        targetFound = true;
        targetDevice = device;
        bleAdapter.stopLeScan(new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                logger.append("-> Scan has stopped\n");
            }
        });

        logger.append("-> Attempting to connect to target device\n");
        gattConnection = targetDevice.connectGatt(this,false,gattCallBackFuntion);
    }
}

这是我对gattCallBackFunction的实现:

private BluetoothGattCallback gattCallBackFuntion = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Boolean gattRes = gattConnection.discoverServices();
            logger.append("-> Connected to GATT Server. Starting service discovery. Result: " + gattRes.toString() +  "\n");
        }
        else{
            logger.append("-> Connection state has changed but is " + newState);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        List<BluetoothGattService> services = gatt.getServices();
        String list = "";
        String tab = "   ";
        for (int i = 0; i < services.size(); i++){
            BluetoothGattService service = services.get(i);
            list = list + tab + service.toString() + "\n";
        }
        logger.append("-> Services Discovered: \n");
        logger.append(list);
    }
};

这两个功能都在同一类中实现,这是唯一的活动。

据我了解,Android必须调用onConnectionStateChange函数,以指示与设备的连接。 但是,这永远不会发生。 该应用程序将显示“正在尝试连接到目标设备”,但不会发生其他情况

有任何想法吗?

大多数蓝牙gatt回调都在后台线程内运行,因此您不应在回调内执行任何UI操作。 您需要按照Android UI指南在UI线程上运行所有操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM