Search code examples
androidmonitoringandroid-notificationsestimoteandroid-ibeacon

Notification in android beacon app


I am developing a Beacon App in Android. I want a functionality that when the app enters a beacon region then notification should come in device about "Region Entered" even when the app is not running in android.When it exits then "Region exits then then again notification should come.I am not getting how to bring notification in top bar when app is not running in background. Also when I click on notification it should take me to the beacon screen. Please help me I am new to this .Thanks in advance Here is my code

         public class NotifyDemoActivity extends BaseActivity {

         private static final String TAG =NotifyDemoActivity.class.getSimpleName();
          private static final int NOTIFICATION_ID = 123;

           private BeaconManager beaconManager;
             private NotificationManager notificationManager;
            private Region region;

             @Override protected int getLayoutResId() {
              return R.layout.notify_demo;
               }

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

            Beacon beacon = getIntent().getParcelableExtra(ListBeaconsActivity.EXTRAS_BEACON);
region = new Region("regionId", beacon.getProximityUUID(), beacon.getMajor(), beacon.getMinor());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
beaconManager = new BeaconManager(this);

// Default values are 5s of scanning and 25s of waiting time to save CPU cycles.
// In order for this demo to be more responsive and immediate we lower down those values.
beaconManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(3), 0);

beaconManager.setMonitoringListener(new MonitoringListener() {
  @Override
  public void onEnteredRegion(Region region, List<Beacon> beacons) {
    postNotification("Entered region");
      Log.d(TAG, "entered");

  }

  @Override
  public void onExitedRegion(Region region) {
    postNotification("Exited region");
      Log.d(TAG, "exited");

  }
});
         }

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

notificationManager.cancel(NOTIFICATION_ID);
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
  @Override
  public void onServiceReady() {
    try {
      beaconManager.startMonitoring(region);
    } catch (RemoteException e) {
      Log.d(TAG, "Error while starting monitoring");
    }
  }
});
            }

              @Override
           protected void onDestroy() {
             super.onDestroy();
            /* notificationManager.cancel(NOTIFICATION_ID);*/
          Log.d(TAG, "Beacons monitoring service destroyed");
           Toast.makeText(this, "Beacons monitoring service done",                         Toast.LENGTH_SHORT).show();
        Notification noti = new  Notification.Builder(NotifyDemoActivity.this)
             .setContentTitle("Stopped")
             .setContentText("See you!")
             .setSmallIcon(R.drawable.variance_new_logo)
             .build();

          /*
             beaconManager.disconnect();
             super.onDestroy();
              */}

     private void postNotification(String msg) {
       Intent notifyIntent = new Intent(NotifyDemoActivity.this,DistanceBeaconActivity.class);
           notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                 PendingIntent pendingIntent = PendingIntent.getActivities(
                  NotifyDemoActivity.this,
                0,
                  new Intent[]{notifyIntent},
                  PendingIntent.FLAG_UPDATE_CURRENT);
           Notification notification = new           Notification.Builder(NotifyDemoActivity.this)
                 .setSmallIcon(R.drawable.beacon_gray)
                 .setContentTitle("Beacon Found")
                 .setContentText(msg)
                 .setAutoCancel(true)
                     .setContentIntent(pendingIntent)
                 .build();
                 notification.defaults |= Notification.DEFAULT_SOUND;
                  notification.defaults |= Notification.DEFAULT_LIGHTS;
                  notificationManager.notify(NOTIFICATION_ID, notification);
                  ;

                 TextView statusTextView = (TextView) findViewById(R.id.status);
                 statusTextView.setText(msg);
                 }
                   }

Solution

  • You are initialising the BeaconManager in Activity which runs on UI thread and will get destroyed eventually in background. So you will need to move the BeaconManager scanning part in the receiver and that should work. By the look of the code it seems you are using Estimote but nevertheless the below example should work.

    Here is the couple of links from Estimote Forum:

    https://community.estimote.com/hc/communities/public/questions/200535593-Background-notification-possible-on-Android-

    https://community.estimote.com/hc/communities/public/questions/202762783-Android-notification-when-app-in-background-without-open-the-app

    Here is a simple application on Github using the BeaconManager in background:

    https://github.com/zakaprov/network-switcher

    Check for the AndroidManifest.xml file which registers the BeaconService and BeaconServiceReceiver, and then check the BeaconServiceReceiver source for more detailed implementation.