我究竟做错了什么?将 BluetoothDevice 的 ArrayList 保存到 SharedPreferences

What am i doing wrong? Saving ArrayList of BluetoothDevice to SharedPreferences

我目前正在编写一个 android 应用程序来控制蓝牙设备。我正在尝试使用 Gson 和 Json classes 将 ArrayList<BluetoothDevice> 保存到 SharedPreferences,但是当我尝试 运行 我的 [=34] 上的这段代码时=],我无法获取每个设备的名称,但我可以获取它们的地址。我在 Android 监控日志中看到这个错误(使用 Android Studio):

03-28 16:12:51.706 17640-17640/? E/BluetoothDevice: BT not enabled. Cannot get Remote Device name

我正在使用自定义 class 来管理设备列表,这里是相关代码:

public class DeviceList {

private ArrayList<BluetoothDevice> mDeviceList_bt;
private ArrayList<String> mDeviceList_s;

private ArrayAdapter mAdapter;

private String PREFS_NAME;

SharedPreferences mPrefs;
SharedPreferences.Editor mEditor;

private int i = 0;

public DeviceList(Context c, String Prefs_Name){

    this.PREFS_NAME = Prefs_Name;

    mDeviceList_bt = new ArrayList<BluetoothDevice>();
    mDeviceList_s = new ArrayList<String>();

    mPrefs = PreferenceManager.getDefaultSharedPreferences(c);
    mEditor = mPrefs.edit();

    mAdapter = new ArrayAdapter(c, android.R.layout.simple_list_item_1, mDeviceList_s);
}

public void readFromSharedPrefs(){

    Gson gson = new Gson();
    String json = mPrefs.getString(PREFS_NAME, null);
    Type type = new TypeToken<ArrayList<BluetoothDevice>>() {}.getType();
    mDeviceList_bt = gson.fromJson(json, type);

    for (BluetoothDevice device : mDeviceList_bt) {
        mDeviceList_s.add(device.getName() + "\n" + device.getAddress());
    }

    mAdapter.notifyDataSetChanged();
}

public void saveToSharedPrefs(){
    Gson gson = new Gson();
    String json = gson.toJson(mDeviceList_bt); // myObject - instance of MyObject
    mEditor.putString(PREFS_NAME, json);
    mEditor.commit();
}

例如,如果我用这 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

知道我做错了什么吗?

提前致谢!

设备名称未保存在蓝牙设备中。相反,该名称缓存在 BluetoothService 中:

/**
 * 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;
}

您的反序列化蓝牙设备似乎未正确初始化(未连接到蓝牙服务)。 您可以做的是在首选项中仅保存 MAC 地址(和设备名称)。然后你可以使用

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

获得正确初始化的设备。

请注意,您可能 运行 遇到问题,因为 iOS 和 Android 设备可能会在一段时间后更改其 MAC 地址。