2017-11-15 7 views
0

gattサービスを使用して複数のBluetoothデバイスのバッテリーレベルをアンドロイドで取得したいと考えています。私は複数のビーコンをスキャンする必要があり、それは、デバイスをスキャンして、それが唯一のサービスをgetssometimesとき複数のbluetoothdevices(ビーコン)のbatterylevelを取得

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); 

               } 
              }); 


           } 
          } 
         }); 
     } 
    }); 
} 

: 私の現在のコードは、この(私はそれが少し混沌に見えることを申し訳ありません)です。 問題は、サービスハンドルが再びnullであるという特性をコードが読み取ろうとしている場合です。私は必死で、あなたが私を助けてくれることを願っています。

+0

編集してください:あなたの問題とソリューションのアプローチ、そしてコード(もしそれが短くできないなら、それが好きなら)とあなたが試したものとそれがどうしたのかを明確にしてください。 – allo

+0

私は少し質問をクリーンアップしようとしました。他に何か意味があった場合は、再度編集してください。そして、コードの書式を見てください。最終的に単一の ''} ''が多すぎるように見えましたが、おそらく残りのコードのインデントが問題でした。 – allo

答えて

0

つまり、実行可能ファイルが別のスレッドで実行されているため、gatt.getServices()の値が変更されている可能性があります。

私は、単に更新されたサービスリストを取得し、サイズを確認し、少なくとも1つのサービスがある場合にのみ電話をかけます。

関連する問題