Search code examples
javaandroidbeaconibeacon-androideddystone

Lollipop+ Unbind BeaconManager not working


I am trying to implement beacon functionality in my Android application. Unfortunately there are a few strange behaviours I couldn't solve yet.

I am using the Android Beacon Library in Version 2.15 and Android 6.0.1.

I have an Activity

 class MainActivity extends AppCompatActivity implements BeaconConsumer

where I want to search for nearby beacons. I initialize the BeaconManager like

 private BeaconManager m_beaconManager;
 [...]

 m_beaconManager = BeaconManager.getInstanceForApplication(this);
 m_beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(BeaconParser.EDDYSTONE_URL_LAYOUT));
 m_beaconManager.bind(this);

in the onCreate() method.

The way I search for beacons

 @Override
public void onBeaconServiceConnect() {
    m_beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
             // do something
         }

    });

    try {
        m_beaconManager.startRangingBeaconsInRegion(m_region);
    } catch(RemoteException e) {
        e.printStackTrace();
    }
}

works perfectly fine.

In my application I want to display these beacons in a list and if I click onto one of them I want to start a new activity with more informations about the beacon (MAC address, distance etc.). My current approach is to unbind my BeaconManager in the onPause() method and create a whole new BeaconManager in my new Activity. This also works flawless.

But a soon as I finish() my second activity it does not stop searching for beacons. I also unbind my BeaconManager like so

 @Override
public void onPause() {
    super.onPause();
    m_beaconManager.unbind(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    m_beaconManager.unbind(this);
}

@Override
public void onStop() {
    super.onStop();
    m_beaconManager.unbind(this);
}

but back in my MainActivity I get 2 searches for beacons. One from my MainActivity and the other one from my already finished second activity.

Furthermore if I click on another item of my list which means I create my second activity again, it looks for the beacon from the first start and the new one. Each new click on the list adds a new search to the existing ones.

I already searched for known Bugs but there is nothing similar.

What am I doing wrong?


Solution

  • In order to prevent duplicate callbacks, in addition to unbinding, you should call (a) stopRangingBeaconsInRegion(...) and (b) removeRangeNotifier(...). To remove the notifier you will need to keep a reference to your callback class.