I´m using the Android IBeacon Library for a Project. I need to create a Service that starts ranging for beacons in the background and notify the user when it finds one (the nearest one). I have searched a lot and coded based on many examples I have found, but still it doesn´t work. Using logs I found that the IBeaconManager doesn't bind, so onIBeaconServiceConnect never gets called. I have already tried some solutions I found here but none of them has been useful. I would really appreciate if someone could help me solving this problem. I post some of my code here
public class RangingService extends Service implements IBeaconConsumer {
private IBeaconManager beaconManager;@Override public void onCreate() { super.onCreate(); beaconManager = IBeaconManager.getInstanceForApplication(this); Log.d("RangingService","Created beaconManager instance"); beaconManager.setBackgroundBetweenScanPeriod(120000); beaconManager.setBackgroundScanPeriod(30000); beaconManager.bind(this); if(beaconManager.isBound(this)) { Log.d("RangingService","Beacon manager bound"); } else { Log.d("RangingService","Beacon manager not bound"); } //Show the service has started notify("RangingService created", "RangingService has started"); } @Override public void onDestroy() { super.onDestroy(); beaconManager.unBind(this); } @Override public void onIBeaconServiceConnect() { Log.d("RangingService", "Entering onIBeaconServiceConnect"); beaconManager.setRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(Collection<IBeacon> beacons, Region region) { if(beacons.size() > 0) { IBeacon nearestBeacon = beacons.iterator().next(); for(IBeacon b : beacons) { if(nearestBeacon.getProximity() == IBeacon.PROXIMITY_UNKNOWN) { nearestBeacon = b; } else { if(b.getProximity() != IBeacon.PROXIMITY_UNKNOWN) { if(b.getAccuracy() < nearestBeacon.getAccuracy()) { nearestBeacon = b; } } } } Log.d("RangingService","Nearest Beacon Found "+nearestBeacon.getMajor()+";"+nearestBeacon.getMinor()); notify("Beacon read","Major: "+nearestBeacon.getMajor()+"; Minor: "+nearestBeacon.getMinor()); } else { Log.d("RangingService","No beacons"); } } }); try { Log.d("RangingService", "Entering startRangingBeacons"); beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); } catch(RemoteException e) { notificar("Error", e.getMessage()); Log.e("RangingService", "Error while starting scanning: "+e.getMessage()); } } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.d("RangingService", "Entering onBind"); return null; }
The Service is already in my manifest also. Thanks for your help.