簡體   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