Android 手机蓝牙与BLE设备建立连接 代码
时间: 2023-11-16 10:12:54 浏览: 112
Android 蓝牙 BLE4.0代码
4星 · 用户满意度95%
以下是 Android 手机蓝牙与 BLE 设备建立连接的代码示例:
1. 在 AndroidManifest.xml 文件中添加蓝牙权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在 Activity 中初始化 BluetoothAdapter 对象:
```java
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
```
3. 扫描 BLE 设备并建立连接:
```java
// 扫描时间 10 秒
private static final long SCAN_PERIOD = 10000;
// 扫描回调
private final BluetoothAdapter.LeScanCallback leScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
// 根据设备名称或 MAC 地址过滤
if (device.getName() != null && device.getName().startsWith("BLE")) {
// 停止扫描
bluetoothAdapter.stopLeScan(leScanCallback);
// 建立连接
device.connectGatt(MainActivity.this, false, gattCallback);
}
}
};
// GATT 回调
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功,开始发现服务
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
Log.i(TAG, "Disconnected from GATT server.");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// 服务发现成功,可以进行数据交互
Log.i(TAG, "Services discovered.");
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// 读取特征值成功
Log.i(TAG, "Characteristic read successfully.");
} else {
Log.w(TAG, "Characteristic read failed: " + status);
}
}
};
// 开始扫描 BLE 设备
private void scanBLEDevice() {
if (bluetoothAdapter == null) {
Log.w(TAG, "Bluetooth not supported.");
return;
}
// 如果正在扫描,则先停止扫描
bluetoothAdapter.stopLeScan(leScanCallback);
// 开始扫描
bluetoothAdapter.startLeScan(leScanCallback);
// 扫描 SCAN_PERIOD 后停止扫描
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
bluetoothAdapter.stopLeScan(leScanCallback);
}
}, SCAN_PERIOD);
}
```
注意:在建立连接之前需要先扫描 BLE 设备,扫描到符合条件的设备后才能进行连接。在连接建立成功后,需要调用 `discoverServices()` 方法发现设备的服务,然后才能进行数据交互。以上代码仅供参考,实际开发中需要根据具体需求进行调整。
阅读全文