Android 测试手机与小米手环BLE蓝牙扫描、连接、断开的代码
时间: 2023-08-17 19:05:08 浏览: 63
以下是 Android 测试手机与小米手环 BLE 蓝牙扫描、连接、断开的代码:
1. 首先,在 AndroidManifest.xml 中添加以下权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在代码中声明蓝牙适配器和扫描回调:
```java
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private ScanCallback mScanCallback;
```
3. 初始化蓝牙适配器和扫描回调:
```java
// 初始化蓝牙适配器
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// 初始化扫描回调
mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
BluetoothDevice device = result.getDevice();
// 连接设备
connect(device);
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
// 扫描失败
}
};
```
4. 开始扫描:
```java
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
mBluetoothLeScanner.startScan(mScanCallback);
}
```
5. 连接设备:
```java
private BluetoothGatt mBluetoothGatt;
private void connect(BluetoothDevice device) {
if (mBluetoothGatt != null) {
mBluetoothGatt.close();
}
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
}
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
// 断开连接
}
}
};
```
6. 断开连接:
```java
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
```
以上是 Android 测试手机与小米手环 BLE 蓝牙扫描、连接、断开的代码。