android代码中保存上次连接的蓝牙信息
时间: 2023-07-29 18:06:02 浏览: 92
在 Android 中,可以通过 SharedPreferences 来保存上次连接的蓝牙设备信息SharedPreferences 是 Android 提供的一种轻量级的数据存储方式,可以用来存储简单的键值对。
以下是一个示例代码,用来保存上次连接的蓝牙设备的 MAC 地址和名称:
```java
// 获取 SharedPreferences 对象
SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// 保存 MAC 地址和名称
String address = device.getAddress();
String name = device.getName();
editor.putString("address", address);
editor.putString("name", name);
editor.apply();
```
在代码中,我们首先获取了一个 SharedPreferences 对象,并通过 edit() 方法获取到它的编辑器对象。然后,我们通过 putString() 方法将蓝牙设备的 MAC 地址和名称保存到 SharedPreferences 中,并通过 apply() 方法提交更改。
在下次连接蓝牙设备时,可以通过以下代码读取保存的 MAC 地址和名称:
```java
// 获取 SharedPreferences 对象
SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE);
// 读取保存的 MAC 地址和名称
String address = sharedPreferences.getString("address", null);
String name = sharedPreferences.getString("name", null);
```
在代码中,我们通过 getSharedPreferences() 方法获取到之前保存的 SharedPreferences 对象,并通过 getString() 方法读取保存的 MAC 地址和名称。需要注意的是,如果之前没有保存过数据,则 getString() 方法会返回 null。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)