安卓实现低功耗蓝牙从初始化到发送数据的完整代码
时间: 2024-09-15 15:09:58 浏览: 86
在Android上实现低功耗蓝牙(Low Energy Bluetooth, LE)通信通常需要使用Bluetooth Low Energy API。以下是使用Android官方库`bluetooth.le`实现从初始化到发送数据的基本步骤:
```java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
//... (在你的Activity或Fragment中)
private BluetoothAdapter bleAdapter;
private BluetoothGatt gatt;
// 在onCreate()中初始化蓝牙
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取蓝牙管理器
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bleAdapter = manager.getAdapter();
if (bleAdapter == null) {
Log.e(TAG, "Bluetooth is not available");
return;
}
// 检查是否支持LE蓝牙
if (!bleAdapter.isEnabled()) {
Intent enableBleIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBleIntent, REQUEST_ENABLE_BT);
} else {
// 初始化扫描并连接设备
startScan();
}
}
// 扫描附近的LE设备
private void startScan() {
BluetoothLeScanner scanner = bleAdapter.getBluetoothLeScanner();
ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(0); // 设置报告延迟以提高响应速度
ScanFilter.Builder filterBuilder = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(SERVICE_UUID)) // 替换为你服务的UUID
.build();
scanner.startScan(filterBuilder.build(), scanSettingsBuilder.build(), this::onScanResult);
}
// 当找到设备时,连接它
private void onScanResult(BluetoothDevice device, int rssi, byte[] scanRecord) {
if (device.connectGatt(this, false, gattCallback)) { // 创建GattCallback
Log.i(TAG, "Connected to: " + device.getName());
} else {
Log.e(TAG, "Failed to connect to: " + device.getAddress());
}
}
// GATT回调
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
discoverServices();
break;
// ...其他状态处理
}
}
private void discoverServices() {
gatt.discoverServices(); // 发现服务
gatt.setCharacteristicNotification(SERVICE_CHARACTERISTIC_ID, true); // 订阅特性通知
BluetoothGattDescriptor descriptor = gatt.getService(SERVICE_UUID).getCharacteristic(SERVICE_CHARACTERISTIC_ID).getDescriptor(NOTIFICATION_DESCRIPTOR_UUID);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); // 开启通知
gatt.writeDescriptor(descriptor); // 写入描述符设置通知
}
// 发送数据
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
sendData(characteristic.getValue()); // 根据实际数据格式发送数据
} else {
Log.e(TAG, "Write characteristic failed with status: " + status);
}
}
// ...其他回调处理
};
// 发送数据的具体实现
private void sendData(byte[] data) {
BluetoothGattCharacteristic writeChar = ...; // 创建你要写的特性
gatt.writeCharacteristic(writeChar, data, BluetoothGatt.GATT_WRITE_TYPE_DEFAULT); // 写入数据
}
// ... (在onActivityResult()中关闭扫描和连接等操作)
```
请注意,以上代码是一个简化示例,实际应用中可能还需要处理错误、异常以及更多的交互逻辑。你需要替换`SERVICE_UUID`, `SERVICE_CHARACTERISTIC_ID`, 和 `NOTIFICATION_DESCRIPTOR_UUID`为你的蓝牙服务和特性的UUID。同时,发送的数据结构也要按照特定的协议进行编码。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)