Android BLE扫描、连接、切断连续100次代码并加详细注释
时间: 2023-07-31 17:10:35 浏览: 123
以下是Android BLE扫描、连接、切断连续100次的代码,并加上了详细注释:
```java
public class BLEScanner {
private final BluetoothAdapter mBluetoothAdapter;
private final BluetoothLeScanner mBluetoothLeScanner;
private final Handler mHandler;
private final ScanCallback mScanCallback;
private final List<BluetoothDevice> mDeviceList;
private BluetoothGatt mBluetoothGatt;
private boolean mIsConnected;
public BLEScanner(Context context) {
// 获取蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 获取蓝牙扫描器
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
// 创建Handler对象
mHandler = new Handler(Looper.getMainLooper());
// 创建BLE扫描回调
mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
// 扫描到BLE设备,将其添加到设备列表中
BluetoothDevice device = result.getDevice();
if (!mDeviceList.contains(device)) {
mDeviceList.add(device);
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
// BLE扫描失败,打印错误码
Log.e("BLEScanner", "onScanFailed: " + errorCode);
}
};
// 创建设备列表
mDeviceList = new ArrayList<>();
// 初始化连接状态为false
mIsConnected = false;
}
/**
* 开始BLE扫描
*/
public void startScan() {
// 如果蓝牙适配器不支持BLE,直接返回
if (!mBluetoothAdapter.isMultipleAdvertisementSupported()) {
Log.e("BLEScanner", "BLE not supported");
return;
}
// 如果蓝牙扫描器已经在扫描中,直接返回
if (mBluetoothLeScanner == null) {
Log.e("BLEScanner", "BluetoothLeScanner is null");
return;
}
if (mBluetoothLeScanner != null && !mIsConnected) {
// 开始BLE扫描,设置扫描回调
mBluetoothLeScanner.startScan(mScanCallback);
// 5秒后停止BLE扫描
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
stopScan();
}
}, 5000);
}
}
/**
* 停止BLE扫描
*/
public void stopScan() {
// 如果蓝牙扫描器正在扫描,停止扫描
if (mBluetoothLeScanner != null) {
mBluetoothLeScanner.stopScan(mScanCallback);
}
// 打印扫描到的设备列表
for (BluetoothDevice device : mDeviceList) {
Log.d("BLEScanner", "Device: " + device.getName() + " " + device.getAddress());
}
// 清空设备列表
mDeviceList.clear();
}
/**
* 连接BLE设备
*
* @param device 要连接的BLE设备
*/
public void connect(BluetoothDevice device) {
// 如果设备已经连接,直接返回
if (mIsConnected) {
return;
}
// 连接设备,设置连接回调
mBluetoothGatt = device.connectGatt(mContext, false, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
// 设备连接成功,打印日志,设置连接状态为true
Log.d("BLEScanner", "Connected to GATT server.");
mIsConnected = true;
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
// 设备连接断开,打印日志,设置连接状态为false
Log.d("BLEScanner", "Disconnected from GATT server.");
mIsConnected = false;
}
}
});
}
/**
* 断开BLE设备连接
*/
public void disconnect() {
// 如果设备已经连接,断开连接
if (mBluetoothGatt != null && mIsConnected) {
mBluetoothGatt.disconnect();
}
// 设置连接状态为false
mIsConnected = false;
}
}
```
注:以上代码仅供参考,具体实现可能需要根据具体的业务需求进行修改和完善。
阅读全文