【问题标题】:Application cycles between didEnterRegion() and didExitRegion() even when the device stays stationary near the beacon应用程序在 didEnterRegion() 和 didExitRegion() 之间循环,即使设备在信标附近保持静止
【发布时间】:2018-01-10 18:37:15
【问题描述】:

我正在使用 AltBeacon Android 库(我复制了 v2.9.2 和 v2.11 的问题)与 Onyx 和 kontact.io 提供的 iBeacon 设备集成。

该库似乎运行良好,但我似乎遇到了一个问题,我找不到可接受的解决方案。

以下是有关我如何使用 AltBeacon 库和问题的更多详细信息:

  • 设备在信标附近静止
  • 蓝牙开启
  • 应用程序在前台运行
  • BeaconManager 配置为使用以下设置在前台模式下扫描:

    BeaconManager.setRegionExitPeriod(30000L);
    beaconManager.setBackgroundBetweenScanPeriod(120000L);
    beaconManager.setForegroundScanPeriod(5000L);
    beaconManager.setForegroundBetweenScanPeriod(10000L);
    beaconManager.getBeaconParsers().add(
    new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
    
  • 应用程序将 BeaconManager 设置为前台模式

    beaconManager.setBackgroundMode(false);
    
  • 应用程序绑定到 BeaconManager

    beaconManager.bind(…)
    
  • 当onBeaconServiceConnect() 被触发时,应用程序开始监视特定区域中的信标(我要监视的信标列表是已知的,静态的;我使用区域列表,每个要监视的信标一个不同的区域)

    beaconManager.startMonitoringBeaconsInRegion(region);
    
  • 当设备进入信标区域(调用didEnterRegion())时,应用程序开始对进入的区域进行测距

    beaconManager.startRangingBeaconsInRegion(region);
    
  • 检测到信标(为相应的信标调用didRangeBeaconsInRegion())

  • 应用程序将信标扫描切换到后台模式:

    beaconManager.setBackgroundMode(true);
    
  • 几分钟后,didExitRegion() 被调用,即使设备和信标没有移动并且应用程序保持相同的状态。

我发现了两个描述相同问题的 Stackoverflow 问题:

  1. AltBeacon unstable for OnyxBeacons, cycling through didEnterRegion and didExitRegion repeatedly

  2. http://stackoverflow.com/questions/40835671/altbeacon-reference-app-and-multiple-exit-entry-calls

我目前使用的解决方法是 Stackoverflow 问题中建议的解决方法:

  • 我已将信标 广告频率 值从 1000 毫秒更新为 100 毫秒。

一旦频率增加,一切似乎都正常,但是 该解决方案是不可接受的,因为信标的电池寿命是 严重受损。

所有信标扫描都在后台执行(即不使用任何活动):

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.Identifier;
import org.altbeacon.beacon.MonitorNotifier;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class BeaconDataProvider implements BeaconConsumer, RangeNotifier, MonitorNotifier {

  private final Logger LOGGER = LogFactory.get(this);
  private final Context applicationContext;
  private final BeaconIdentifierFactory beaconIdentifierFactory;
  private final BeaconScanningListener beaconScanningListener;

  private BeaconManager beaconManager;
  private Collection<Region> targetedRegions;

  /**
   * This field is used for improving battery consumption. Do not remove it.
   */
  @SuppressWarnings({"unused", "FieldCanBeLocal"})
  private BackgroundPowerSaver backgroundPowerSaver;

  public BeaconDataProvider(Context applicationContext, BeaconIdentifierFactory beaconIdentifierFactory,
      BeaconScanningListener beaconScanningListener) {
    LOGGER.v("BeaconDataProvider - new instance created.");
    this.applicationContext = applicationContext;
    this.beaconIdentifierFactory = beaconIdentifierFactory;
    this.beaconScanningListener = beaconScanningListener;
    beaconManager = BeaconManager.getInstanceForApplication(applicationContext);
    LOGGER.v("BeaconManager hashCode=%s", beaconManager.hashCode());
    BeaconManager.setRegionExitPeriod(30000L);
    beaconManager.setBackgroundBetweenScanPeriod(120000L);
    beaconManager.setForegroundScanPeriod(5000L);
    beaconManager.setForegroundBetweenScanPeriod(10000L);
    beaconManager.getBeaconParsers().add(
        new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
    backgroundPowerSaver = new BackgroundPowerSaver(applicationContext);
  }

  public void setBackgroundMode() {
    LOGGER.i("setBackgroundMode()");
    beaconManager.setBackgroundMode(true);
  }

  public void setForegroundMode() {
    LOGGER.i("setForegroundMode()");
    beaconManager.setBackgroundMode(false);
  }

  public boolean checkAvailability() {
    return android.os.Build.VERSION.SDK_INT >= 18 && applicationContext.getPackageManager()
        .hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);

  }

  public boolean isBluetoothEnabled() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean result = mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
    LOGGER.i("isBluetoothEnabled() -> %s", result);
    return result;
  }

  public boolean isLocationPermissionGranted(Context context) {
    return (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
        == PackageManager.PERMISSION_GRANTED);
  }

  public void startScanning(Collection<BeaconIdentifier> targetedBeacons) {
    LOGGER.i("startScanning()");
    if (!beaconManager.isBound(this)) {
      this.targetedRegions = getRegionsForTargetedBeacons(targetedBeacons);
      beaconManager.bind(this);
    }
    else {
      LOGGER.i("Scanning already started.");
    }
  }

  @NonNull
  private List<Region> getRegionsForTargetedBeacons(Collection<BeaconIdentifier> beaconIdentifiers) {
    List<Region> regions = new ArrayList<>();
    for (BeaconIdentifier beaconIdentifier : beaconIdentifiers) {
      try {
        Region region = new Region(beaconIdentifier.getRegionId(), Identifier.parse(beaconIdentifier.getUuid()),
            Identifier.parse(String.valueOf(beaconIdentifier.getMajor())),
            Identifier.parse(String.valueOf(beaconIdentifier.getMinor())));
        regions.add(region);
      }
      catch (Exception e) {
        LOGGER.e("Caught exception.", e);
        LOGGER.w("Failed to create region for beaconIdentifier=%s", beaconIdentifier.getCallParamRepresentation());
      }
    }
    return regions;
  }

  public void stopScanning() {
    LOGGER.i("stopScanning()");
    if (beaconManager.isBound(this)) {
      for (Region region : targetedRegions) {
        try {
          beaconManager.stopMonitoringBeaconsInRegion(region);
        }
        catch (RemoteException e) {
          LOGGER.e("Caught exception", e);
        }
      }
      beaconManager.unbind(this);
    }
  }

  @Override
  public void didEnterRegion(Region region) {
    LOGGER.v("didEnterRegion(region=%s)", region);
    beaconScanningListener.onEnterRegion(region.getUniqueId());
    try {
      beaconManager.startRangingBeaconsInRegion(region);
    }
    catch (RemoteException e) {
      LOGGER.e("Caught Exception", e);
    }
  }

  @Override
  public void didExitRegion(Region region) {
    LOGGER.v("didExitRegion(region=%s)", region);
    beaconScanningListener.onExitRegion(region.getUniqueId());
    try {
      beaconManager.stopRangingBeaconsInRegion(region);
    }
    catch (RemoteException e) {
      LOGGER.e("Error", e);
    }
  }

  @Override
  public void didDetermineStateForRegion(int state, Region region) {
    LOGGER.v("didDetermineStateForRegion(state=%s, region=%s)", state, region);
  }

  @Override
  public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
    LOGGER.v("didRangeBeaconsInRegion(size=%s, region=%s, regionUniqueId=%s)", beacons.size(), region,
        region.getUniqueId());
    if (beacons.size() > 0) {
      beaconScanningListener.onBeaconsInRange(beaconIdentifierFactory.from(beacons, region.getUniqueId()));
    }
  }

  @Override
  public void onBeaconServiceConnect() {
    LOGGER.v("onBeaconServiceConnect()");
    beaconManager.addRangeNotifier(this);
    beaconManager.addMonitorNotifier(this);
    for (Region region : targetedRegions) {
      try {
        beaconManager.startMonitoringBeaconsInRegion(region);
      }
      catch (RemoteException e) {
        LOGGER.e("Caught exception", e);
      }
    }
  }

  @Override
  public Context getApplicationContext() {
    return applicationContext;
  }

  @Override
  public void unbindService(ServiceConnection serviceConnection) {
    LOGGER.v("unbindService()");
    applicationContext.unbindService(serviceConnection);
  }

  @Override
  public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
    LOGGER.v("bindService()");
    return applicationContext.bindService(intent, serviceConnection, i);
  }
}

public class BeaconIdentifier {

  private final String uuid;
  private final int major;
  private final int minor;
  private String regionId;

  public BeaconIdentifier(String uuid, int major, int minor) {
    this.uuid = uuid;
    this.major = major;
    this.minor = minor;
  }

  public int getMinor() {
    return minor;
  }

  public int getMajor() {
    return major;
  }

  public String getUuid() {
    return uuid;
  }

  public String getCallParamRepresentation() {
    return (uuid + "_" + major + "_" + minor).toUpperCase();
  }

  public String getRegionId() {
    return regionId;
  }

  public void setRegionId(String regionId) {
    this.regionId = regionId;
  }

  @Override
  public boolean equals(Object o) {
    if (o != null) {
      if (o instanceof BeaconIdentifier) {
        BeaconIdentifier other = (BeaconIdentifier) o;
        return this == other || (this.uuid.equalsIgnoreCase(other.uuid)
            && this.major == other.major && this.minor == other.minor);
      }
      else {
        return false;
      }
    }
    else {
      return false;
    }
  }

  @Override
  public int hashCode() {
    int result = 17;
    result = 31 * result + (uuid != null ? uuid.toUpperCase().hashCode() : 0);
    result = 31 * result + major;
    result = 31 * result + minor;
    return result;
  }

  @Override
  public String toString() {
    return "BeaconIdentifier{" +
        "uuid='" + uuid + '\'' +
        ", major=" + major +
        ", minor=" + minor +
        ", regionId='" + regionId + '\'' +
        '}';
  }
}

BeaconDataProvider 用作每个应用程序的单个实例;它在创建 Android 应用程序时由 Dagger 2 实例化。它具有@ApplicationScope 生命周期。

Beacon 扫描首先在 前台模式 中从 Android IntentService 开始:

    beaconDataProvider.setForegroundMode();    
    beaconDataProvider.startScanning(targetedBeacons);

一旦设备进入区域并检测到信标,信标扫描就会切换到后台模式:

    beaconDataProvider.setBackgroundMode();    

起初我认为我使用的 Onyx 信标有问题,但我可以用 Kontact IO 信标重现同样的问题。

  1. 您有什么建议吗?

  2. 我错过了使用 AltBeacon Android 库吗?

谢谢, 阿林

【问题讨论】:

  • 请发布您的 RangingActivity。
  • @AndreaEbano,我编辑了我的帖子并包含了用于与 AltBeacon 集成的主要类。如果有什么不清楚的地方请告诉我。

标签: android ibeacon battery altbeacon


【解决方案1】:

调用didExitRegion() 的根本原因是Android 蓝牙堆栈在前10 秒内没有收到与该区域匹配的BLE 信标广告数据包。 (注意:这个值可以用BeaconManager.setRegionExitPeriod(...)配置。)

有几件事可能会导致这些虚假的didExitRegion() 调用:

  1. 信标的广告频率不够高。
  2. 信标正在以非常低的无线电信号进行广告。
  3. 附近的无线电噪声过多,无法进行可靠检测。
  4. 接收设备的蓝牙天线设计不佳,导致无法检测到较弱的信号。
  5. 接收设备距离太远,无法可靠地检测到信标。
  6. foregroundScanPeriod 或 backgroundScanPeriod 设置得太短,无法保证检测到

鉴于您描述的设置,我怀疑当您以 1Hz 传输信标时,1-4 的某种组合会导致问题。您将不得不对这些变量中的每一个进行试验,看看您是否可以将问题隔离为一个主要问题。但同样,不止一个可能同时在起作用。

了解即使在良好的条件下,也只有 80-90% 通过无线传输的信标数据包被典型的 Android 设备接收。因此,如果您的设置通常在 10 秒内仅接收 1-5 个信标数据包,那么如果您运气不好,您仍然会有时收到退出事件,并且在一个行被无线电噪声破坏。没有办法保证这不会发生。您可以通过设置系统使其在统计上更不可能发生,以便在标称条件下它在 10 秒内接收尽可能多的数据包,因此这变得更不可能。

提高广告率是解决此问题的最简单方法,因为它为您提供了更多在任何 10 秒内检测到数据包的统计机会。但正如您所见,在电池寿命方面存在折衷。

如果您想保持电池寿命,但不关心获取 didExitRegion 回调所需的时间,那么您可能需要将 BeaconManager.setRegionExitPeriod(...) 修改为 30,000 毫秒或更长时间,直到问题消失。

以上讨论是针对Android Beacon Library 的配置,同样的理论思想适用于任何Beacon 检测框架,包括iOS Core Location。您有时也会看到该框架的虚假退出事件。

【讨论】:

  • 感谢您的详细回复!我将在更多设备上使用参数进行更多测试,然后返回一些统计数据。
  • 我在 HtcOne Mini (Android 4.3)、Nexus 4 (Android 5.1.1) 和 Galaxy S7 (Android 6.0.1) 上进行了一些测试。扫描设置为后台模式,setRegionExitPeriod() 设置为 120000L(2 分钟)。我在不到 1 小时内收到了 didExitRegion(),即使设备和信标(Onyx Beacon)是固定的。在装有 Android 5.1.1 的 Nexus 4 上,我设法使用不同的 iBeacons 设备(Onyx、Estimote、Contact.io、Roximity)重现了这个问题。
  • 在 Nexus 4、Android 5.1.1 上,即使在设置后我也重现了该问题:setBackgroundScanPeriod(20000L)
【解决方案2】:

我认为问题出在这里:

beaconManager.setForegroundScanPeriod(5000L);
beaconManager.setForegroundBetweenScanPeriod(10000L);

您通常应将 scanPeriod 设置为 5100 毫秒或更长,因为如果发送广告的信标始终处于您开始和停止扫描的边界,则它们的传输可能会被错过。

那就试试吧:

beaconManager.setForegroundScanPeriod(5100L);
beaconManager.setForegroundBetweenScanPeriod(10000L);

希望对您有所帮助。让我知道是否有效。

【讨论】:

  • 感谢您的快速回复。我会根据您的建议进行一些测试,然后返回答案。
  • 我已经编辑了我最初的问题。实际上,当 beaconManager 在后台模式下配置时,问题就会重现。因此,在前台模式下启动信标扫描后,一旦检测到信标,扫描就会切换到后台模式。我使用默认的 backgroundScanPeriod,我认为它是 10000L。我还设法用最新的 AltBeacon 版本重现了这个问题:2.11
  • 出于测试目的,我编辑了我的代码以在检测到信标后将 beaconManager 保持在 前台模式。我设法用以下 foregroundScanPeriod 值重现了这个问题:5000L; 5100L; 6000L甚至10000L
【解决方案3】:

作为此问题的解决方法,我已经实现了一些额外的逻辑来考虑 didExitRegion() 事件,仅当相应的 didEnterRegion() 未在特定时间间隔内调用时(在我的情况下为 5 分钟,但这可以调整)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多