gpt4 book ai didi

Android信标库如何将前台服务转为后台模式?

转载 作者:行者123 更新时间:2023-11-29 00:53:23 26 4
gpt4 key购买 nike

我想要实现的是,当用户进入地理围栏时,信标前台服务将开始运行,在检测到一个信标后,我将终止该前台服务并开始在后台运行它,就像 android-beacon-library-reference 上的示例代码一样图书馆。

private fun monitorBeacons(startForegroundService: Boolean) {
var beaconManager = WolApp.appContext?.beaconManager
if (beaconManager == null) {
WolApp.appContext?.beaconManager = BeaconManager.getInstanceForApplication(WolApp.appContext!!)
beaconManager = WolApp.appContext?.beaconManager
beaconManager?.backgroundMode = true
beaconManager?.beaconParsers?.clear()
beaconManager?.beaconParsers?.add(BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"))
beaconManager?.removeAllMonitorNotifiers()
}
if (startForegroundService) {
setupForegroundNotificationService(WolApp.appContext!!)
} else {
WolApp.appContext?.regionBootstrap?.disable()
WolApp.appContext?.regionBootstrap = null
try {
WolApp.appContext?.beaconManager?.disableForegroundServiceScanning()
} catch (e: IllegalStateException) {}

if (beaconManager?.scheduledScanJobsEnabled == false) {
beaconManager.setEnableScheduledScanJobs(true)
beaconManager.backgroundBetweenScanPeriod = BeaconManager.DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD
beaconManager.backgroundScanPeriod = BeaconManager.DEFAULT_BACKGROUND_SCAN_PERIOD
}
}

if (WolApp.appContext?.regionBootstrap == null) {
WolApp.appContext?.regionBootstrap = RegionBootstrap(WolApp.appContext!!, regions)//regions are some iBeacon regions
}
if (!startForegroundService) {
WolApp.appContext?.backgroundPowerSaver = BackgroundPowerSaver(WolApp.appContext!!)
}
}

setupForegroundNotificationService方法同android-beacon-library-reference

我不太确定我这样做是对还是错,有人可以帮忙吗?

最佳答案

打开或关闭前台服务有点棘手,因为您要尝试更改已在现有服务幕后运行的多个执行线程的行为。

显示的代码中缺少的关键是,您还必须确保在切换之前已停止库扫描。这很复杂,因为它是异步的——扫描器需要时间来关闭它的线程。

如果使用 regionBootstrap,调用 regionBootstrap.disable() 会执行此操作。 (如果不使用 regionBootstrap,您也可以使用 beaconManager.unbind(...))。但问题是当扫描服务完全关闭时,这些 API 不会给您回调。在关闭之前再次重新启动它可能会导致问题。我在这里没有很好的建议,除了可能使用计时器 - 比如停止和开始之间的一秒钟?

您可能还想查看类似设置的讨论: https://github.com/AltBeacon/android-beacon-library/issues/845

关于Android信标库如何将前台服务转为后台模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57352324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com