在参考应用程序中,RegionBootstrap在其onCreate 方法的自定义应用程序类中初始化,当然,在调用任何活动之前调用应用程序类。
有没有办法在活动中初始化 RegionBootstrap?我已经尝试过制作 RegionBootstrap 的静态变量,以便我可以在不同的活动中调用它,但不幸的是,它不起作用。
BeaconApplication.regionBootstrap = new RegionBootstrap((BootstrapNotifier) this.getApplication(), downloadedBeacons);
我需要初始化的区域将来自服务器,因此 RegionBootstrap 的初始化不能来自应用程序类。
* 编辑 *
public class LoginActivity extends ActionBarActivity {
…
/*** short version ***/
@Override
protected void onCreate(Bundle savedInstanceState) {
/*** after successful login ***/
BeaconApplication.beacons = downloadBeaconsFromServer();
}
}
public class BeaconActivity extends ActionBarActivity {
…
@Override
protected void onCreate(Bundle savedInstanceState) {
…
startService(new Intent(this, BeaconService.class));
}
}
这是我实施的地方BeaconConsumer
public class BeaconService extends Service implements BeaconConsumer {
private BeaconManager beaconManager;
private BeaconNotifier beaconNotifier;
private RegionBootstrap regionBootstrap;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.setBackgroundBetweenScanPeriod(1001);
beaconManager.setBackgroundScanPeriod(101);
beaconManager.setForegroundScanPeriod(101);
beaconManager.setForegroundBetweenScanPeriod(1001);
beaconNotifier = new BeaconNotifier(this);
beaconManager.bind(this);
}
@Override
public void onBeaconServiceConnect() {
beaconManager.setMonitorNotifier(beaconNotifier);
monitorBeacons();
regionBootstrap = new RegionBootstrap(beaconNotifier, BeaconApplication.beacons);
}
private void monitorBeacons() {
for (Region beacon : BeaconApplication.beacons) {
try {
Log.i(TAG, "Monitoring beacon " + beacon.getUniqueId());
beaconManager.startMonitoringBeaconsInRegion(beacon);
} catch (RemoteException e) {
Log.e(TAG, "Monitoring beacon failed");
e.printStackTrace();
}
}
}
}
实施BeaconNotifier
public class BeaconNotifier implements BootstrapNotifier {
private Context context;
public BeaconNotifier(Context context) {
this.context = context;
}
@Override
didEnter.. etc
@Override
public Context getApplicationContext() {
return context;
}
}