Search code examples
androidibeaconibeacon-android

Android lollipop show notification, if beacon in specific range


Could anyone please share any steps to show notification when beacon came in specific range in android lollipop.


Solution

  • You can do this with the Android Beacon Library with code like this:

        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                for (Beacon beacon: beacons) {
                        if (beacon.getDistance() < 5.0) {
                                Log.d(TAG, "I see a beacon that is less than 5 meters away.");
                                NotificationCompat.Builder builder =
                                    new NotificationCompat.Builder(this)
                                      .setContentTitle("Beacon Reference Application")
                                      .setContentText("An beacon is nearby.")
                                      .setSmallIcon(R.drawable.ic_launcher);
    
                                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                                stackBuilder.addNextIntent(new Intent(this, MonitoringActivity.class));
                                PendingIntent resultPendingIntent =
                                stackBuilder.getPendingIntent(
                                   0,
                                   PendingIntent.FLAG_UPDATE_CURRENT
                                );
                                builder.setContentIntent(resultPendingIntent);
                                NotificationManager notificationManager =
                                       (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
                                notificationManager.notify(1, builder.build());                        
                        }
                }
        }
    

    Full details here:

    http://altbeacon.github.io/android-beacon-library/distance-triggering.html