1

現在、Bluetoothデバイスを制御するアンドロイドアプリケーションを作成しています。私はArrayList<BluetoothDevice>SharedPreferencesにGsonとJsonクラスを使用して保存しようとしていますが、私の電話でこのコードを実行しようとすると、各デバイスの名前は取得できませんが、 Android Monitorのログ(Androidスタジオを使用)でこのエラーが表示されます:何が間違っていますか? BluetoothデバイスのArrayListをSharedPreferencesに保存する

03-28 16:12:51.706 17640-17640 /? E/BluetoothDevice:BTが有効になっていません。 はここに関連するコードで、私はデバイスのリストを管理するために、カスタムクラスを使用しているリモートデバイス名に

を取得できません:たとえば

​​

が、私はこれら3でリストを保存した場合デバイス:

DeviceName1 
8C:DE:52:FA:96:0A 

DeviceName2 
00:3E:01:00:47:4E 

DeviceName3 
8C:DE:52:FA:B5:F0 

私はSharedPreferencesから読んだ後、私はこれを取得:

null 
8C:DE:52:FA:96:0A 

null 
00:3E:01:00:47:4E 

null 
8C:DE:52:FA:B5:F0 

私が間違っていることは何ですか?

ありがとうございます!

答えて

1

デバイス名はBluetoothDeviceに保存されません。代わりに名前がBluetoothServiceにキャッシュされている:

それはあなたの直列化復元BluetoothDevicesが正しく初期化されていないようです
/** 
* Get the friendly Bluetooth name of the remote device. 
* 
* <p>The local adapter will automatically retrieve remote names when 
* performing a device scan, and will cache them. This method just returns 
* the name for this device from the cache. 
* <p>Requires {@link android.Manifest.permission#BLUETOOTH} 
* 
* @return the Bluetooth name, or null if there was a problem. 
*/ 
    public String getName() { 
    if (sService == null) { 
     Log.e(TAG, "BT not enabled. Cannot get Remote Device name"); 
     return null; 
    } 
    try { 
     return sService.getRemoteName(this); 
    } catch (RemoteException e) {Log.e(TAG, "", e);} 
    return null; 
} 

(Bluetoothサービスに接続されていません)。 できることは、MACアドレス(およびデバイス名)だけを環境設定に保存することです。次に、適切に初期化されたデバイスを取得するには、

BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress); 

を使用してください。

iOSとAndroidデバイスはしばらくしてからMACアドレスを変更する可能性があるため、問題が発生する可能性があることに注意してください。

+0

ありがとう、たくさん助けてください! –

関連する問題