如何在用户登录时如何在后台制作AltBeacon监视器?

时间:2015-03-20 01:02:56

标签: android ibeacon ibeacon-android altbeacon android-ibeacon

我想在Android上试用iBeacon。看起来AltBeacon是最好的工具。我读到如果我将我的应用程序的子应用程序子类化为this,即使该应用程序在之后被杀死,我仍可以使我的应用程序正常工作。

如果我希望我的应用仅在用户登录时进行监控,该怎么办?应用程序将运行每个应用程序启动,赢了吗?如何在登录后在Application中运行BootstrapNotifier,如果用户没有登录则不运行它?



        @Override
        protected void onPostExecute(final Boolean success) {
            if (success) {
                //algorithm to make altbeacon run in the background, even after the app killed
            } else {
                //if failed
            }
        }




所以,这是建议的解决方案:



public class BeaconReferenceApplication extends Application implements BootstrapNotifier {

    // OTHER CODE

    public void onCreate() {
        super.onCreate();
        if (loggedin) {
            BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
            Region region = new Region("backgroundRegion", null, null, null);
            regionBootstrap = new RegionBootstrap(this, region);
            BeaconManager.getBeaconSimulator()).createTimedSimulatedBeacons();
        }
    }

    // OTHER CODE

}


public class LoginACtivity {

    // OTHER CODE

    public void onClick {

        if (username == TRUE && password == TRUE) {
            // SINCE THE USER LOGGED IN, HOW DO I MAKE MY APP TO START ALWAYS SCAN EVEN AFTER REBOOTING AS LONG THE USER ISN'T LOGGING OUT?
        }

    }

    // OTHER CODE

}

public class MainActivity {

    // OTHER CODE

    private void logout {

        // SINCE THE USER CLICK LOG OUT BUTTON, HOW DO I MAKE MY APP TO STOP SCANNING EVEN AFTER REBOOTING UNTIL THE USER LOGGING IN AGAIN?

    }

    // OTHER CODE

}




该代码是否会保证我的应用只有在用户登录时才会始终扫描信标,即使重启后应用程序还没有运行?

1 个答案:

答案 0 :(得分:1)

您只需要包装构造RegionBootstrap对象的代码,以检查用户之前是否已登录。如果没有,请不要构建它。

然后,您可以稍后停用RegionBootstrap,并在必要时重新构建它。像这样:

public class BeaconReferenceApplication extends Application implements BootstrapNotifier {
  ...
  private RegionBootstrap regionBootstrap;

  public RegionBootstrap startBeaconMonitoring() {
    if (regionBootstrap == null) {
        Region region = new Region("backgroundRegion", null, null, null);
        regionBootstrap = new RegionBootstrap(this, region);          
    }
  }

  public RegionBootstrap stopBeaconMonitoring() {
    if (regionBootstrap != null) {
        regionBootstrap.disable();          
    }
  }

  public void onCreate() {
    super.onCreate();
    if (loggedin) {
       startBeaconMonitoring();
       ...
    }
}


public class MainActivity {
  ...
  private void logout() {
    ((BeaconReferenceApplication)this.getApplication()).stopBeaconMonitoring();
  }
  private void login() {
    ((BeaconReferenceApplication)this.getApplication()).startBeaconMonitoring();
  }

}