Search code examples
androidbeaconrssi

Show dialog in Android based on RSSI signal from beacons


I'm working on an Android application that displays messages based on the RSSI beacon signal. The class that scans the beacons in the background is not an activity (but class extends Application), so I can not display a dialog with some informations directly in this class. So how do I capture the RSSI signal from this class in an some other activity and then display the dialog?

Here is function in class that scans beacons:

@Override                                                              
public void onBeaconServiceConnect(){
    mBeaconManager.setRangeNotifier(new RangeNotifier() {

        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {                                                       
             if(beacons.size() > 0) {
                  for (Beacon beacon: beacons) {
                      if(beacon.getRssi() >= - 50) {

                         ... i want here show a dialog

                      }

                  }
              }
         }
    });
}

Solution

  • To present a dialog you need to have an Activity in the foreground. That is not always the case for an Android application, especially one that may be launched in the background by beacon detection. If no activity has been launched yet you can start an activity from the Application class (possible but generally considered a bad practice) or you can simply suppress your dialog in this case.

    To trigger the dialog from your Application class, you need to communicate with whatever activity is in the foreground. There are lots of elegant ways to do this (local BroadcastRceivers, and various design patterns) but the simplest is to store a reference to your Activity on your Application class as a member variable like:

    private MyActivity myActivity;
    
    public  setMyActivity(MyActivity a) {
      myActivity = activity;
    }
    

    Then create a method on your MyActivity class to present the dialog:

    public void show dialog() {
    ...
    }
    

    Finally, call that method inside your detection code:

    if(beacon.getRssi() >= - 50) {
          if (myActivity != null) {
             myActivity.showDialog();
          }
     }
    

    You can find lots of examples of code to actually do the dialog presentation on this site.

    One final tip: take care to prevent your dialog from being repeatedly presented every second with each subsequent beacon detection! You will need some extra logic for that