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

时间:2018-02-02 02:02:34

标签: android altbeacon

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

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

boolean first_time;

在onCreate中,我认为它是假的:

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命令时更改布尔值,如果它为真,它都是假的,所以每当消息显示在Log时。

1 个答案:

答案 0 :(得分:0)

这个怎么样?

   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) {    }
    }