2017-11-15 3 views
0

gatt 서비스를 사용하여 안드로이드에 둘 이상의 블루투스 장치의 배터리 레벨을 가져 오려고합니다. 내 현재 코드는 이것이다 (나는 보이는 것이 유감 조금 혼란) :하나 이상의 블루투스 장치 (비컨)의 배터리 잔량을 받으십시오

public void readCustomCharacteristic() { 
// Initializes Bluetooth adapter. 
final BluetoothManager bluetoothManager = 
     (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 
mBluetoothAdapter = bluetoothManager.getAdapter(); 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
    mBluetoothAdapter.getBluetoothLeScanner().startScan(new ScanCallback() { 
     @Override 
     public void onScanResult(int callbackType, ScanResult result) { 
      super.onScanResult(callbackType, result); 
      //Log.i("Beacons", "callbacktype: " + String.valueOf(callbackType)); 
      Log.i("Beacons", "result: " + result.toString()); 
      BluetoothDevice btDevice = result.getDevice(); 
      Log.i("Beacons", "Devicescan: " + (btDevice != null)); 

       BluetoothGatt bluetoothGatt = btDevice.connectGatt(
         getApplicationContext(), false, new BluetoothGattCallback() { 
          @Override 
          public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 
           //super.onConnectionStateChange(gatt, status, newState); 
           Log.i("Beacons", "areServicesDiscovered: " + gatt.discoverServices()); 
           if(gatt.discoverServices()) { 
            onServicesDiscovered(gatt, status); 
           } 
          } 

          @Override 
          public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
           if (gatt.discoverServices()) { 
            //if (status == BluetoothGatt.GATT_SUCCESS) { 

              Log.d("Beacons", "Number of Services: " + gatt.getServices().size()); 

              runOnUiThread(new Runnable() { 
               @Override 
               public void run() { 

                BluetoothGattCharacteristic chars = gatt.getServices().get(0).getCharacteristic(Battery_Level_UUID); 
                Log.i("Beacons", "charsstringval: " + chars.getValue().length); 

               } 
              }); 


           } 
          } 
         }); 
     } 
    }); 
} 

내가 하나 이상의 표지를 스캔해야하고,이 장치를 스캔 할 때 그것은 단지 서비스를 getssometimes. 문제는 서비스 핸들이 다시 null 인 특성을 코드에서 읽고 자 할 때입니다. 나는 필사적이며 당신이 나를 도울 수 있기를 바랍니다.

+0

편집하십시오 : 명확한 문제 설명과 솔루션 접근 방식, 다음 코드 (당신이이 다음처럼, 그것은 짧은 할 수없는 경우) 당신이 노력을 추가하고 어떻게했는지 (안) 작업. – allo

+0

질문을 정리하려고했습니다. 다른 것을 의미한다면 다시 편집하십시오. 코드 형식을 살펴보십시오. 끝내는 단일 "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''. – allo

답변

0

즉, 실행 가능한 스레드가 다른 스레드에서 실행되기 때문에 gatt.getServices() 값이 변경되었을 수 있습니다.

나는 단순히 업데이트 된 서비스 목록을 검색하고 크기를 확인한 다음 하나 이상의 서비스가있는 경우에만 전화를 겁니다.

if (gatt.getServices().size() > 0) { 
    BluetoothGattCharacteristic chars = gatt.getServices().get(0).getCharacteristic(Battery_Level_UUID); 
    Log.i("Beacons", "charsstringval: " + chars.getValue().length); 
} 
관련 문제