2016-09-26 31 views
0

我正在創建一個使用BLE與MCU通信的Android應用程序,目前我能夠使用我的應用程序連接到MCU,但是當我嘗試發現並獲取設備服務時,我是返回一個null數組,我不確定原因。Java BLE不返回服務

//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:連接到GATT服務器。

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

09-26 16時33分:09.658 10917-10931/bamboomobile.medhead I/TAG:試圖啓動服務發現:真正的

09-26 16:33:09.668 10917-10931/bamboomobile.medhead W/BluetoothGatt:未處理的異常回調 的Java。 lang.IndexOutOfBoundsException:索引0無效,大小爲0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(A rrayList.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) 在android.os.Binder.execTransact(Binder.java:446)

09-26 16:33:09.688 10917-10931/bamboomobile.medhead d/BluetoothGatt:onSearchComplete() =設備= DC:1B:A3:10:B9:D5狀態= 0

回答

0

連接後,您需要撥打mGatt.discoverServices()。然後在onServicesDiscovered回調中,您可以使用mGatt.getServices()並繼續。