Simple Distance Detection Android App

Hi @Gamma2,

you want to print a distance, so you need the ranging technology.

  • the ranging technology is used in the foreground of your activity,
  • it takes a BeaconRegion in argument to know how beacons to search,
  • it continuously scans (1s by default) the beacons of the region and send you a list of Beacon objects,
  • it drains more battery than the monitring technology.
How to range a region?

class MyRangingActivity {
    private BeaconManager beaconManager;
    private BeaconRegion beaconRegion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get a new BeaconManager instance.
        this.beaconManager = new BeaconManager(this);

        // Set up a ranging listener.
        this.beaconManager.setRangingListener( new BeaconManager.BeaconRangingListener() {
            @Override
            public void onBeaconsDiscovered(BeaconRegion region, List<Beacon> list) {
                // Handle here the discovered beacons list of the region.
                // You can for example calculate the distance with the RSSI.
                // You can also get the proximity value with RegionUtils.computeProximity().
            }
        });

        // Create a new BeaconRegion instance to range.
        this.beaconRegion = new BeaconRegion(<identifier>, <proximityUUID>, <major>, <minor>);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Checks automatically the permissions before ranging.
        SystemRequirementsChecker.checkWithDefaultDialogs(this);

        // Starts ranging after being connected to the BeaconService.
        this.beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
            @Override
            public void onServiceReady() {
                beaconManager.startRanging(beaconRegion);
            }
        });
    }

    @Override
    protected void onPause() {
        // Ranging is on foreground only, so stop it when activity is paused.
        this.beaconManger.stopRanging(this.beaconRegion);

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // Disconnect from BeaconService when not used.
        this.beaconManager.disconnect();

        super.onStop();
    }
}