我正在使用 AltBeacon 库开发蓝牙应用程序。似乎每个应用程序只允许 BeaconManager
实例。我面临的问题是:我想要一个持续运行的后台服务,不断进行蓝牙测距并发送通知。如果我打开我的应用程序(将其置于前台),我就是暂停测距的服务。然后前台 Activity 将进行测距并在屏幕上显示内容。
问题是 Activity 和服务中的信标管理器(来自 BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
)是同一个实例。因此,当 Activity 关闭时,将调用 beaconManager.unbind(this);
并且服务中的范围通知程序不再触发。
是否有可能获得两个独立的信标管理器实例?如果没有,我该如何在持续运行的服务和 Activity 中进行测距?
测距 Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
...
regionEstimote = new Region("estimote", null, null, null);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.bind(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
notificationManager.cancel(NOTIFICATION_ID);
//beaconManager.unbind(this);
}
@Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
....
});
try {
beaconManager.startRangingBeaconsInRegion(regionEstimote);
} catch (RemoteException e) {
Log.e(TAG, "RangingActivity", e);
}
}
信标服务.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(beaconHistory == null)
beaconHistory = new HashMap<Integer, Date>();
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBeaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
beaconHistory = null;
mBeaconManager.unbind(this);
}
@Override
public void onBeaconServiceConnect() {
mBeaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if(ActivityBase.isActivityVisible()) { //don't do ranging logic if any activity from my app is in the foreground
return;
}
...
}
});
try {
mBeaconManager.startRangingBeaconsInRegion(regionMint);
} catch (RemoteException e) {
Log.e(TAG, "BeaconService", e);
}
}
最佳答案
在这种情况下,自定义 android.app.Application
类非常有用。 BeaconManager
是一个单例,因此同一时间只允许存在一个。同样,Application
类每个 Activity 的 Android 应用程序都有一个实例。如果您想同时在 Activity
和 Service
中进行信标检测,请使用集中式 Application
类绑定(bind)到 BeaconManager
,然后将回调转发给您的 Activity
和您的 Service
。
您可以在此处的引用应用程序中查看绑定(bind)到 Application
类中的 BeaconManager
并将回调传递给 Activity
的示例: https://github.com/AltBeacon/android-beacon-library-reference/blob/master/app/src/main/java/org/altbeacon/beaconreference/BeaconReferenceApplication.java
关于java - Android AltBeacon 后台服务测距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26609519/