我正在为一个项目使用 Android IBeacon 库。我需要创建一个在后台开始对信标进行测距的服务,并在找到一个(最近的一个)时通知用户。我已经根据我找到的许多示例进行了很多搜索并进行了编码,但它仍然不起作用。使用日志我发现 IBeaconManager 没有绑定,所以 onIBeaconServiceConnect 永远不会被调用。我已经尝试了一些我在这里找到的解决方案,但没有一个有用。如果有人可以帮助我解决这个问题,我将不胜感激。我在这里发布了一些代码
公共类 RangingService 扩展服务实现 IBeaconConsumer {
私人 IBeaconManager 信标管理器;@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; }
该服务也已经在我的清单中。谢谢你的帮助。