【发布时间】:2019-10-02 11:47:53
【问题描述】:
我是 BLE 信标的新手。
当我的移动应用程序中有新数据可用时,我有一个 BLE 设备需要不时更新,反之亦然 - 当 BLE 做了应用程序应该知道的事情时。
换言之,BLE 设备需要与移动应用“同步”。
如果用户打开应用程序,BLE 正在同步,一切都很好。
但我希望这种同步在后台运行,即使用户有 1、2 天甚至几周没有打开应用程序,所以下次打开应用程序时,BLE 设备中已经有新数据了在应用程序内部,反之亦然 - 即使用户没有打开应用程序,应用程序也会针对应该发生的事件更新 BLE(例如命令 BLE 在 10 分钟内闪烁颜色)。
我尝试将 Android 蓝牙库与 RegionBootstrap 一起使用,但我对监控是否是我的方案中的最佳选择感到困惑。
这是我的自定义应用程序 onCreate() 中的代码:
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(IBEACON_PARSER_LAYOUT));
mBeaconManager.setRegionStatePersistenceEnabled(false);
mBeaconManager.setBackgroundBetweenScanPeriod(10000l);
mBeaconManager.setForegroundBetweenScanPeriod(10000l);
mBeaconManager.setBackgroundScanPeriod(1100l);
mBeaconManager.setForegroundScanPeriod(1100l);
region = new Region(getPackageName(),Identifier.parse(MY_BLE_BEACON_UID), null, null);
mRegionBootstrap = new RegionBootstrap(this, region);
这是我的触发事件:
@Override
public void didEnterRegion(Region region) {
Log.e(TAG, "didEnterRegion: ");
synchronizeBleWithTheApp();
playSoundEnterRegion();
}
@Override
public void didExitRegion(Region region) {
Log.e(TAG, "didExitRegion: ");
playSoundExitRegion();
}
private void synchronizeBleWithTheApp() {
// 1) Check if there is any new data the BLE is interested in, if yes the app should push it to the BLE in the background.
// 2) Check if there is any new data in the BLE the app is interested in, if yes fetch it from the BLE in the background.
}
我的问题是:
1) 我什至应该在我的情况下使用监控吗?我的意思是,即使设备每 X 分钟仍在该区域中,我也想继续尝试同步。 RegionBootstrap 适合这种情况吗?
现在,didEnterRegion 被触发一次,30~ 秒后 onExitRegion 被触发,即使 BLE 信标正在传输,这让我很困惑。
2) 如果自定义 Application 类中的 synchronizeBleWithTheApp() 使用 Activity MainActivity 类中的代码,是否意味着我需要应用程序才能打开该 MainActivity?我还能在后台触发同步吗?
【问题讨论】:
-
如果您计划在后台运行您的应用程序,那么您必须实现前台服务并将所有逻辑从活动移动到服务级别或应用程序级别。如果您不能这样做,那么由于后台限制,您的应用永远不会在 Android OS >= 8.0 中运行
-
@MD 你写这个是为了回答问题 2 对吗?
-
是的。这对你有意义吗?
-
有道理,是的,我认为活动已死,但服务/应用程序组件仍在运行。但是,为什么在低于 Android 8 的版本中我可以在我的 Activity 中实现同步逻辑?
-
在 Android 8 之前,应用程序在后台运行没有时间限制,只要有足够的可用内存,启动的活动就会无限期地保持活动状态。对于 Android 8+,这不再适用。包括活动在内的应用程序在大约后被杀死。在后台播放 10 分钟。
标签: android bluetooth-lowenergy altbeacon ibeacon-android android-ibeacon