我无法在 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);
但它也不起作用。 为什么屏幕关闭时前台服务停止?
请检查位置权限。 从Android 10开始,无法获得位置权限的“一直允许”选项。
所以,你需要说服用户设置它。
如果要在后台使用BLE,位置权限必须设置为“一直允许”。
答案: 根据Adnroid 文档,如果您不使用扫描过滤器(即扫描所有可用设备),当屏幕关闭时扫描将停止以节省电量。当屏幕再次打开时,扫描将恢复。
我的情况: 我使用 React Native 开发 Android 10 应用程序。即使屏幕保持打开状态,在应用程序未处于活动状态的情况下在前台服务中进行扫描也会在几分钟内停止。如果关闭屏幕,扫描会立即停止。