作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想要实现的是,当用户进入地理围栏时,信标前台服务将开始运行,在检测到一个信标后,我将终止该前台服务并开始在后台运行它,就像 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/
我是一名优秀的程序员,十分优秀!