0

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);
                 }
                   }
Harsh Mittal
  • 2,868
  • 1
  • 16
  • 21

2 Answers2

0

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.

dhaval
  • 7,611
  • 3
  • 29
  • 38
  • Hey thank you @dhaval for reply . I want to ask what do you mean by "So you will need to move the BeaconManager scanning part in the receiver ". Means whether it is other acftivity or class? I know it might be a dumb question to ask but please guide me! – Harsh Mittal Sep 14 '15 at 05:38
  • Basically `Activity` is a screen, so your code works fine as long as the screen is visible to user. But as Beacon notifications can come at any point of time you will need to move the listening part in `BackgroundReceiver` which is like a background task run by Android whether or not the user is using the app. The Github demo I mentioned in the answer does exactly that, if you just skim through the code you will understand the logic. If you are new to Android, I would suggest just go though basic understanding of Activity, BackgroundReceiver and Service, that will help you long way. – dhaval Sep 14 '15 at 06:50
  • yhh ok means I have to make a new activity of beacon manager as per the link project and there I have to extend the broadcast receiver.!! And the rest is the code I have to do.Right??@dhaval – Harsh Mittal Sep 14 '15 at 07:31
0

You can follow our Android tutorial to learn how to set up background monitoring:

http://developer.estimote.com/android/tutorial/part-2-background-monitoring/

Long story short, the trick is to create the BeaconManager in an Application subclass. This way, it won't be tied to any particular activity.

As of this moment, Estimote SDK doesn't yet support monitoring when the gets killed completely. We're working on addressing that in one of the upcoming SDK updates.

You can still make it work this way manually, as @dhaval pointed out, by tying the BeaconManager in a service with START_STICKY option enabled—this way, Android should never kill the service and monitoring will continue even if the app itself got killed. This is a bit more advanced topic though.

heypiotr
  • 2,139
  • 2
  • 15
  • 22