android SharedPreferences 保存BluetoothDevice
时间: 2023-07-22 15:15:46 浏览: 30
在 Android 中,因为 BluetoothDevice 类并没有实现 Serializable 接口,所以不能直接将 BluetoothDevice 对象保存到 SharedPreferences 中。不过,我们可以将 BluetoothDevice 对象中的 MAC 地址和名称保存到 SharedPreferences 中。
以下是一个示例代码,用来将 BluetoothDevice 对象的 MAC 地址和名称保存到 SharedPreferences 中:
```java
// 将 BluetoothDevice 对象保存到 SharedPreferences 中
private void saveBluetoothDevice(BluetoothDevice device) {
// 获取 SharedPreferences 对象
SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE);
// 获取 MAC 地址和名称
String address = device.getAddress();
String name = device.getName();
// 获取 SharedPreferences 编辑器对象
SharedPreferences.Editor editor = sharedPreferences.edit();
// 保存 MAC 地址和名称
editor.putString("address", address);
editor.putString("name", name);
// 提交更改
editor.apply();
}
```
在代码中,我们首先通过 getSharedPreferences() 方法获取到一个 SharedPreferences 对象,并通过 edit() 方法获取到它的编辑器对象。然后,我们通过 BluetoothDevice 对象的 getAddress() 和 getName() 方法获取到 MAC 地址和名称,并将它们保存到 SharedPreferences 中。最后,我们通过 apply() 方法提交更改。
在需要读取保存的 BluetoothDevice 信息时,可以通过以下代码读取:
```java
// 从 SharedPreferences 中读取 BluetoothDevice 信息
private BluetoothDevice readBluetoothDevice() {
// 获取 SharedPreferences 对象
SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE);
// 读取保存的 MAC 地址和名称
String address = sharedPreferences.getString("address", null);
String name = sharedPreferences.getString("name", null);
// 如果 MAC 地址或名称为空,则返回 null
if (address == null || name == null) {
return null;
}
// 使用 MAC 地址创建 BluetoothDevice 对象
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return bluetoothAdapter.getRemoteDevice(address);
}
```
在代码中,我们首先通过 getSharedPreferences() 方法获取到之前保存的 SharedPreferences 对象,并通过 getString() 方法读取保存的 MAC 地址和名称。然后,我们使用 BluetoothAdapter 的 getRemoteDevice() 方法根据 MAC 地址创建 BluetoothDevice 对象。需要注意的是,如果之前没有保存过数据,则 getString() 方法会返回 null。
相关推荐


















