0

我有一个 android 应用程序,我在其中检测前景/背景中的信标。一切正常,除了我关闭设备上的蓝牙。在这种情况下,它会调用 OnExitRegion 但我必须忽略它,因为我真的不知道用户在做什么,但是如果我远离信标并再次打开蓝牙,将不会再次调用 onExitRegion 并且我不会知道我退出了该地区。

这是我的代码的一部分。

public class MyApplication extends Application implements BootstrapNotifier {
public void onCreate() {
    super.onCreate();
    ...
    mBeaconManager = BeaconManager.getInstanceForApplication(this);
    mBeaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout(Constants.BEACON_LAYOUT));
    mBeaconRegion = new Region(Constants.BEACON_BACKGROUND_REGION, Identifier.parse(Constants.BEACON_UDID), null, null);
    regionBootstrap = new RegionBootstrap(this, mBeaconRegion);
    backgroundPowerSaver = new BackgroundPowerSaver(this);
    mBeaconManager.setBackgroundScanPeriod(Constants.BEACON_BACKGROUND_SCAN_PERIOD);       
    mBeaconManager.setBackgroundBetweenScanPeriod(Constants.BEACON_BACKGROUND_BETWEEN_SCAN_PERIOD);
    mBeaconManager.setAndroidLScanningDisabled(true);
    ...

}

我试图创建一个 BroadcastReceiver 来检测蓝牙何时关闭或开启

public class BluetoothBroadcastReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
                == BluetoothAdapter.STATE_OFF) {
            Log.w("BLUETOOTH", "Bluetooth is disconnected");
        } else {
            Log.w("BLUETOOTH", "Bluetooth is connected");
        }
    }
}
}

我需要的是检查这个广播接收器,当蓝牙打开时,我是否仍在该地区或不修改 UI。

希望我的解释足够清楚。

提前谢谢了!

4

1 回答 1

0

显然,如果蓝牙无线电关闭, Android 信标库无法检测到您是否真的离开了信标区域。但是,一旦蓝牙重新打开,您可以做些什么来模拟退出行为:

  1. 保留两个应用程序级变量:

    Set<Region> regionsActive = new HashSet<Region>();
    Set<Region> regionsActiveWhenBluetoothDisabled = new HashSet<Region>();
    
  2. 向变量添加代码didExitRegiondidEnterRegionregionsActive变量添加/删除区域。

  3. 在您检测到蓝牙已关闭的代码中,执行以下操作:

    regionActiveWhenBluetoothDisabled = new HashSet(regionsActive);

  4. 在您收到蓝牙打开的回调的代码中,启动一个 10 秒左右的计时器。在此计时器结束时,执行如下操作:

    for (Region region: regionsActiveWhenBluetoothDisabled) {
        if (!regionsActive.contains(region)) {
            // We know we are no longer in a region that we were in when bluetooth was last turned off
            // execute code to say we are out of this region
        }
    }
    
于 2015-03-18T21:59:59.187 回答