0

彼はちょうど私のコードです。この例をどこかで見た。しかし、それは動作しませんでした。コンクリートへGATTサービス:青色ビーコンのバッテリレベルを取得

private static final UUID Battery_Service_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb"); 
private static final UUID Battery_Level_UUID = UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb"); 
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
private BluetoothGattService mBluetoothGatt; 

...

public void readCustomCharacteristic() { 

    if (mBluetoothAdapter == null || mBluetoothGatt == null) { 
     Log.w("Beacons", "BluetoothAdapter not initialized"); 
     return; 
    } 
    /*check if the service is available on the device*/ 
    BluetoothGattService mBatteryService = mBluetoothGatt; 
    if(mBatteryService == null){ 
     Log.w("Beacons", "Battery BLE Service not found"); 
     return; 
    } 
    /*get the read characteristic from the service*/ 
    BluetoothGattCharacteristic mReadCharacteristic = mBatteryService.getCharacteristic(Battery_Level_UUID); 


    if(mReadCharacteristic.getStringValue(0) == null){ 
     Log.w("Beacons", "Failed to read characteristic"); 
    } else { 
     Log.i("Beacons", "Battery Level: " + mReadCharacteristic.getValue()); 
    } 
} 

、私はNullPointerExceptionが取得:

のjava.lang.NullPointerException:アンドロイドをjava.lang.Stringで仮想メソッド「を起動しようとします。 nullオブジェクトリファレンスのbluetooth.BluetoothGattCharacteristic.getStringValue(int) '

おそらく、完全なサーバー、サービス、およびブロードキャスト受信者を実装する必要がありますか? ありがとうございます!

+0

mBluetoothGattがBattery_Level_UUIDの特性を持っていないので、あなたは例外を取得します。 mBluetoothGattの初期化方法のコードを表示できますか? – davidgyoung

+0

ああ、忘れてしまった。それはこのようなonCreate(Bundle ...)関数にあります:mBluetoothGatt =新しいBluetoothGattService(Battery_Service_UUID、0); –

+0

GETT DB構造を見るには、nRF connectのようないくつかのBLEエクスプローラアプリでアプリを開く必要があります。そうすることで、それが持つ特性とサービスを知ることができます。 – Emil

答えて

0

コンストラクタnew BluetoothGattService(Battery_Service_UUID, 0);を使用してBluetoothGattServiceを単純に構築することはできません。このコードの使用方法は、あなたのAndroidアプリ内でGattServiceをホストすることを想定しているため、取得しているエラーが予想されます。

Android上で外部のBluetoothデバイスからGATTのBluetooth特性を読み取るためには、まず、非同期APIを使用して、工程数を経なければならないための:

  1. スキャンとBluetoothデバイスを発見します。 (あなたが何らかの形で正しいものを選択する必要がありますので、複数の表示があるかもしれません。)デバイスへ

    mBluetoothAdapter.startLeScan(mLeScanCallback); 
    // the above will bring a callback to onLeScan(final BluetoothDevice device, int rssi, 
        byte[] scanRecord) 
    
  2. 接続

    device.connectGatt(mContext, false, mGattCallback); 
    // the above will cause a callback to onConnectionStateChange(BluetoothGatt gatt, int status, int newState) 
    
  3. 発見デバイスのサービス

    gatt.discoverServices(); 
    // the above will bring a callback to onServicesDiscovered(BluetoothGatt gatt, int status) 
    
  4. サービスから特性を読み取る

    gatt.getCharacteristic(Battery_Level_UUID); 
    

最終段階でのコードの行は、問題のコードがやろうとしている、ヌルが生じているものです。これが機能するには、最初の3つのステップを実行する必要があります。

は、詳細はこちらをご覧ください:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html

+0

私はそこにコード例を掲載しました。あなたが私を助けてくれることを願っています。 –

関連する問題