问题
I am trying to add the Estimote SDK into my Android app. I'm getting pretty close, but I'm having some trouble monitoring for a region. I am following the Estimote Android SDK Guide on GitHub at https://github.com/Estimote/Android-SDK.
For some reason, the onEnteredRegion and onExitedRegion methods are not firing at all. I'm would like them to trigger any time the app sees an Estimote beacon. Thanks!
Here is the code I have so far. Nothing too complicated:
public class MainActivity extends Activity {
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId", "B9407F30-F5F8-466E-AFF9-25556B57FE6D", null, null);
BeaconManager beaconManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
beaconManager = new BeaconManager(this);
beaconManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
beaconManager.setMonitoringListener(new MonitoringListener() {
@Override
public void onEnteredRegion(Region region, List<Beacon> beacons) {
builder.setTitle("Entered Region")
.setMessage("")
.setNeutralButton("OK", null);
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onExitedRegion(Region region) {
builder.setTitle("Exited Region")
.setMessage("")
.setNeutralButton("OK", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
protected void onStart() {
super.onStart();
try {
beaconManager.startMonitoring(ALL_ESTIMOTE_BEACONS);
}
catch (RemoteException e) {
}
}
}
回答1:
Try putting this in your onStart()
method:
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
@Override
public void onServiceReady() {
try {
beaconManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while starting monitoring");
}
}
You also need to remember about disconnecting from the BeaconManager when it's no longer needed, e.g. with this onDestroy
implementation:
@Override
protected void onDestroy() {
beaconManager.disconnect();
super.onDestroy();
}
Basically, ranging and monitoring need to be started after the beacon service is made ready, which can be easily achieved by utilizing the callback shown above.
来源:https://stackoverflow.com/questions/28121038/android-estimote-region-monitoring