0

我正在使用 altBeacon 库进行信标检测。在查看了 Beacon 检测的示例代码后,他们总是BootstrapNotifierApplication类上实现 Interface 而不是Activity,用于在后台检测信标。但是我注意到,当BootstrapNotifierActivity. 我不希望我的应用程序在启动后立即检测信标,因此我没有BootStrapNotifierApplication课堂上实施。我有一个特定的要求,我希望仅在特定Activity启动后才检测到信标,此后应始终检测到信标在后台。altBeacon 库是否有任何实现这一点的规定?谢谢。

示例代码

4

1 回答 1

3

是的,只有在Activity启动后才能在后台检测信标,但您仍然需要创建一个自定义Application类来实现BootstrapNotifier.

这是必要的原因是因为 Android 生命周期。AnActivity可以通过退出它来退出,继续一个新的Activity,或者如果你从前台获取它,操作系统会在内存不足的情况下终止它。

在内存不足的情况下,整个应用程序,包括Application类实例(和信标扫描服务)与Activity. 这种情况完全超出您的控制范围,但 Android 信标库有代码可以在这种情况发生几分钟后自动重启应用程序和信标扫描服务。

就您而言,棘手的部分是在类的onCreate方法中Application确定这是应用程序重新启动(在低内存关闭之后),还是在Activity运行之前首次启动应用程序。

执行此操作的一个好方法是在SharedPreferences中存储启动时的时间戳Activity

所以你的Application班级可能有这样的代码:

public void onCreate() {
  ...
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  long lastActivityLaunchTime = prefs.getLong("myapp_activity_launch_time_millis", 0l);
  if (lastActivityLaunchTime > System.currentTimeMillis()-SystemClock.elapsedRealtime() ) {
    // If we are in here we have launched the Activity since boot, and this is a restart
    // after temporary low memory shutdown.  Need to start scanning
    startBeaconScanning();  
  }
}

public void startBeaconScanning() {
    Region region = new Region("backgroundRegion",
            null, null, null);
    mRegionBootstrap = new RegionBootstrap(this, region);
    mBackgroundPowerSaver = new BackgroundPowerSaver(this);      
}

在您的Activity系统中,您还需要代码来检测它是否是首次启动,如果是,请从那里开始扫描。

public void onCreate() {
  ...
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  long lastActivityLaunchTime = prefs.getLong("myapp_activity_launch_time_millis", 0l);
  if (lastActivityLaunchTime < System.currentTimeMillis()-SystemClock.elapsedRealtime() ) {
    // This is the first Activity launch since boot
    ((MyApplication) this.getApplicationContext()).startBeaconScanning();
    SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putLong("myapp_activity_launch_time_millis", System.currentTimeMillis());
    prefsEditor.commit();
  }
}
于 2016-01-16T15:41:57.130 回答