问题是,应用程序没有检测到蓝牙关闭时的信标。但是,如果我打开蓝牙工作正常。还有一件很奇怪的事情。如果我在应用程序运行时再次关闭蓝牙,它仍会继续检测。这意味着BLE检测正在工作,但仅在打开蓝牙并再次关闭蓝牙时才有效。
如何启用BLE检测?下面是我的实现。我想念什么?
灯塔服务类
public class BeaconDiscoverer extends Service implements BeaconConsumer {
private static final String TAG = BeaconDiscoverer.class.getSimpleName();
private static BeaconManager beaconManager;
private static Region region;
private BackgroundPowerSaver backgroundPowerSaver;
public BeaconDiscoverer() {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
region = new Region("myRangingUniqueId", null, null, null);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
configureBatterySaverMode();
beaconManager.bind(this);
}
@Override
public void onDestroy() {
beaconManager.unbind(this);
super.onDestroy();
}
private void configureBatterySaverMode() {
BeaconManager.setAndroidLScanningDisabled(true);
backgroundPowerSaver = new BackgroundPowerSaver(getApplicationContext());
// set the duration of the scan to be 5 seconds
beaconManager.setBackgroundScanPeriod(Utility.convertToMilliseconds(2));
// set the time between each scan to be 1 min (60 seconds)
beaconManager.setBackgroundBetweenScanPeriod(Utility.convertToMilliseconds(25));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "BeaconDiscoverer started up");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onBeaconServiceConnect() {
Log.d(TAG, "onBeaconServiceConnect");
beaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection beacons, Region region) {
if (beacons.size() > 0) {
Beacon firstBeacon = beacons.iterator().next();
Log.i(TAG, "Beacon detected: " + firstBeacon.getDistance() + " m. - " + firstBeacon.getBluetoothAddress());
}
}
});
startRanging();
}
public void stopRanging() {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void startRanging() {
if (User.currentUser() == null)
return;
try {
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
应用类
public class App extends Application {
private static final String TAG = App.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, BeaconDiscoverer.class));
}
}
+0
你想达到什么目前还不清楚。 –
+0
我想在蓝牙未关闭时检测信标。我的意思是如果用户至少没有打开蓝牙一次,可以检测不起作用。 –