在Android中检索gatt服务的值,然后将数据发送到该服务的特征时遇到问题



我是非常新的BLE技术。我已经在蓝牙服务中声明了以下服务.java:

public final static UUID UUID_SERV = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");

我尝试为UUID_SERV做一个getService()

BluetoothGattService gattService = mBluetoothGatt.getService(UUID_SERV); 

问题是gattService显示空。我想获取UUID_SERV及其特征,然后将数据写入此特征。

public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }
        System.out.println("mBluetoothDeviceAddress======================" + mBluetoothDeviceAddress);
        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }
        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        System.out.println("mBluetoothGatt=============" + mBluetoothGatt);
        Log.d(TAG, "Trying to create a new connection.");
        System.out.println("UUID_SERV======" + UUID_SERV);
        BluetoothGattService gattService = mBluetoothGatt.getService(UUID_SERV);
        System.out.println("gattService is===============" + gattService);
        if (gattService != null) {
            BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(UUID_CHAR);
        }
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

您必须先发现服务,然后才能通过该方法检索它们。

公共布尔发现服务 ()

在 API 级别 18 中添加

发现远程设备提供的服务以及它们的特征和描述符。

这是一个异步操作。一旦服务发现已完成,onServicesDiscover(BluetoothGatt,int)回调为引发。如果发现成功,则远程服务可以使用 getServices() 函数检索。

需要蓝牙权限。

如果远程服务发现已启动

,则返回 true,如果远程服务发现已启动

最新更新