我曾经使用过 Android iBeacon 库,并为后台扫描创建了一个服务,在服务中定义了监控和范围。当程序销毁时,我启动了该服务并达到了预期效果。您也可以像这样创建新的服务。
public class Beaconservice extends Service implements IBeaconConsumer {
private ArrayList<IBeacon> arrayL = new ArrayList<IBeacon>();
private BeaconServiceUtility beaconUtill = null;
private IBeaconManager iBeaconManager = IBeaconManager.getInstanceForApplication(this);
private Handler hand;
private Runnable runn;
private int count = 30;
@Override
public void onIBeaconServiceConnect() {
iBeaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection<IBeacon> iBeacons, Region region) {
arrayL.clear();
arrayL.addAll((ArrayList<IBeacon>) iBeacons);
if(count>0){
count=0;
}
}
});
iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
@Override
public void didEnterRegion(Region region) {
Log.e("BeaconDetactorService", "didEnterRegion");
}
@Override
public void didExitRegion(Region region) {
Log.e("BeaconDetactorService", "didExitRegion");
}
@Override
public void didDetermineStateForRegion(int state, Region region) {
Log.e("BeaconDetactorService", "didDetermineStateForRegion");
}
});
try {
iBeaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
try {
iBeaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
beaconUtill = new BeaconServiceUtility(this);
Log.e("UUID","start service");
hand = new Handler();
runn = new Runnable() {
@Override
public void run() {
count ++;
hand.postDelayed(runn, 1000);
}
};
hand.post(runn);
super.onCreate();
}
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
beaconUtill.onStart(iBeaconManager, this);
beaconUtill = new BeaconServiceUtility(this);
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
beaconUtill.onStop(iBeaconManager, this);
super.onDestroy();
}
}
在 AndroidManifest.xml 中
<service android:name="com.beacone.keyfinder.app.Beaconservice" >
</service>
Estimote
信标,它们有自己的SDK
和实现。我制作了一个应用程序,在其中使用了这些信标,对于任何初学者来说,了解Android信标和BLE非常有用。从此链接https://github.com/Estimote/Android-SDK尝试此操作。 - Zubair Ahmed