检测到时仅发送一次信标信息

Send beacon information only once when detected

我正在使用 AndroidBeaconLibrary 参考程序,但遇到了一个小问题。

创建了一个全局布尔变量来检测是否是第一次 运行 部分代码:

boolean first_time;

在 onCreate 中我将其设置为 false:

first_time = false;

检测到信标后,我将其值更改为 true。

@Override
public void didDetermineStateForRegion(int state, Region region) {
    if (monitoringActivity != null) {
        monitoringActivity.logToDisplay("I have just switched from seeing/not seeing beacons: " + state);

        if ((state == 1)&&(first_time == false)) {
            //insert beacon data to server.
            first_time = true;
            beaconManager.addRangeNotifier(new RangeNotifier() {
                @Override
                public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                    if (beacons.size() > 0) {
                        Log.i("TEST", "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away.");

                    }
                }
            });

            try {
                beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
            } catch (RemoteException e) {    }
        }
    }

即使每次检查 if 命令时更改布尔值,如果它是 true 或不是 false,所以每次都会在 Log 中显示消息。

这个怎么样?

   if (state == 1) {
        beaconManager.addRangeNotifier(new RangeNotifier() {
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                if (beacons.size() > 0 && first_time == false) {
                    //insert beacon data to server.
                    first_time = true;
                    Log.i("TEST", "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away.");

                }
            }
        });

        try {
            beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
        } catch (RemoteException e) {    }
    }