【发布时间】:2025-11-23 08:35:01
【问题描述】:
我无法在 Android 10 上使用前台服务在后台进行 BLE 扫描。 我的应用程序在清单 FOREGROUND_SERVICE 中有权限,并在启动时从用户那里获得权限 ACCESS_FINE_LOCATION 和 ACCESS_BACKGROUND_LOCATION。然后它使用 BLE Scan 启动前台服务。当屏幕在服务上扫描并查找设备时,当屏幕关闭时,前台服务停止工作并停止扫描。
启动服务:
Intent serviceIntent = new Intent(context, BTService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
使其成为前景:
startForeground(BT_SERVICE_ID, notification);
我试图从服务发出通知:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(getString(R.string.service))
.setContentText((new Date()).toString())
.setSmallIcon(R.drawable.ic_service)
.build();
notificationManager.notify(BT_SERVICE_ID, notification);
handler.postDelayed(runnable, delay);
}
};
int delay = 30000;
每 30 秒从前台服务发送一次:
handler.postDelayed(runnable, delay);
但它也不起作用。 为什么屏幕关闭时前台服务停止?
【问题讨论】:
-
您是否要求用户允许位置权限?您是否在清单中启用了您的服务?最近,我开发了一个可以工作的 BLE 应用程序,可以扫描和读取 BLE 设备中的数据
标签: android bluetooth-lowenergy foreground-service