Java BLE 不返回服务

标签 java android bluetooth-lowenergy

我正在创建一个使用 BLE 与 MCU 通信的 Android 应用程序,目前我可以使用我的应用程序连接到 MCU,但是当我尝试发现并获取设备的服务时,我返回了一个空数组,并且不确定原因。

//Code used to connect to the device
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i("TAG", "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i("TAG", "Attempting to start service discovery:" + mGatt.discoverServices());
            services = mGatt.getServices();
            System.out.println("Service 1 is : " + services.get(0));
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i("TAG", "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

输出:

09-26 16:33:09.648 10917-10931/bamboomobile.medhead I/TAG: Connected to GATT server.

09-26 16:33:09.648 10917-10931/bamboomobile.medhead D/BluetoothGatt: discoverServices() - device: DC:1B:A3:10:B9:D5

09-26 16:33:09.658 10917-10931/bamboomobile.medhead I/TAG: Attempting to start service discovery:true

09-26 16:33:09.668 10917-10931/bamboomobile.medhead W/BluetoothGatt: Unhandled exception in callback java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at bamboomobile.medhead.MainMenu$1.onConnectionStateChange(MainMenu.java:86) at android.bluetooth.BluetoothGatt$1.onClientConnectionState(BluetoothGatt.java:186) at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:70) at android.os.Binder.execTransact(Binder.java:446)

09-26 16:33:09.688 10917-10931/bamboomobile.medhead D/BluetoothGatt: onSearchComplete() = Device=DC:1B:A3:10:B9:D5 Status=0

最佳答案

连接后,您需要调用mGatt.discoverServices()。然后在 onServicesDiscovered 回调中,您可以使用 mGatt.getServices() 并继续。

关于Java BLE 不返回服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39711973/

相关文章:

iOS BLE 配件想要在应用程序未被查看时打开应用程序。如何使此警报静音?

ios - iOS 上的自定义 BLE 广告

Java 8 Stream - 标记 "("出现语法错误,此标记后应有表达式

java - 如何使用 Java 中的 Gson 库将对象列表自动转换为 JSONArray?

java - 如何在 Java 流上调用多个终端操作

android - 在通话过程中播放闹钟

android - 如何向MIFARE卡发送NFCA命令?

android - 如何在 Android 版 Here Maps 上显示我的位置按钮

bluetooth - Roboletric 返回 null 蓝牙管理器

java - 在没有 GAE 和 Apache Commons 的情况下在 GWT 中上传文件