
本文介绍如何使用android foreground service实现ble设备的持续数据接收,支持后台运行、csv本地存储及云端上传,适合初学者快速上手。
本文介绍如何使用android foreground service实现ble设备的持续数据接收,支持后台运行、csv本地存储及云端上传,适合初学者快速上手。
开发一个能稳定接收BLE设备持续通知(Notification)的Android应用,关键在于避免系统因省电策略杀死后台连接。单纯在Activity中处理BLE通信极易中断——当App退至后台或屏幕关闭时,系统可能暂停或终止BluetoothGatt操作。因此,必须采用 Foreground Service(前台服务),它具备更高优先级,可长期维持BLE连接与数据监听。
核心实现步骤
-
声明必要权限与服务
在 AndroidManifest.xml 中添加:<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission><!-- Android 6.0+ 扫描必需 --><uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><!-- CSV写入(Android 10以下) --><!-- Android 11+ 建议使用应用专属目录或MANAGE_EXTERNAL_STORAGE(需特殊审核) --><service android:name=".BleDataService" android:enabled="true" android:exported="false" android:foregroundservicetype="connectedDevice"></service>
-
构建BLE前台服务(BleDataService)
继承 Service,在 onStartCommand() 中启动前台通知,并初始化 BluetoothGatt 连接与特征通知:public class BleDataService extends Service { private BluetoothGatt gatt; private BluetoothGattCharacteristic notifyChar; @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(1, createNotification()); // 必须调用 connectToDevice(intent.getStringExtra("deviceAddress")); return START_STICKY; } private void enableNotification() { if (gatt != null && notifyChar != null) { gatt.setCharacteristicNotification(notifyChar, true); // 写入Client Characteristic Configuration Descriptor (CCCD) 启用通知 BluetoothGattDescriptor descriptor = notifyChar.getDescriptor( UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(descriptor); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { byte[] data = characteristic.getValue(); String csvLine = System.currentTimeMillis() + "," + Base64.encodeToString(data, Base64.NO_WRAP); saveToCsv(csvLine); // 本地存储 uploadToCloud(data); // 可选:上传至Firebase/HTTP API } } -
安全存储与云端同步建议
Android Adb Skill下载Android 开发调试技能,通过系统 ADB 工具操作 Android 设备。以下场景必须触发此技能:(1) 直接 ADB 操作——安装 APK、查看设备列表、抓取 logcat 日志、查看已安装应用、清除应用数据、截图、重启设备、拉取/推送文件、查看 CPU/内存/电池信息、adb shell 操作;(2)...
- ✅ CSV本地存储:推荐使用 getFilesDir()(无需权限)保存为 data_log.csv,避免外部存储权限问题;
- ✅ 云端上传:集成 Firebase Realtime Database 或 Retrofit + REST API,将 data 和时间戳封装为JSON异步提交;
- ⚠️ 注意:Android 8.0+ 对后台服务限制严格,ForegroundService 是唯一可靠方案;Android 12+ 需声明 FOREGROUND_SERVICE_SPECIAL_USE(仅限特定场景)或改用 WorkManager + BLE scanning trigger(适用于间歇性连接)。
? 新手提示:从 REInVent650/foreground-service-base 克隆基础模板开始,它已预置前台服务生命周期管理、通知栏UI和蓝牙状态监听,可专注实现 onCharacteristicChanged 中的数据解析与持久化逻辑。
最终,该架构确保设备在锁屏、切换App等场景下仍稳定接收BLE通知,为后续数据分析、远程监控或IoT平台对接奠定坚实基础。










