Thursday, January 1, 2015

Android Geofence Stop Getting Transition Events After Some Time

And here comes the first technical blog of 2015, Recently in one of our android application we have used Geofences in Android application. The app needs to track entry and exit of device in Geofence. After implementing and configuring Geofences by help of the sample code from android developer site, it worked good for some time but after the app is running for long time suddenly no transitions were recorded even though the device was in Geofence. After looking for the reason for few hours, I finally found a solution, in this blog I am going to mention that.

The issue was with IntentService mentioned in example code. When your device enters into Geofence, this intent service gets called with pending intent. It works good if your app is in foreground but when the app is in background, this IntentService is never called. So to overcome with this shortcomings, we have used Broadcast receiver in stead of IntentService.

So first define BroadcastReceiver in Manifest file.

<receiver
            android:name="com.app.appname.GeofenceReceiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.tracksum.vehicletrack.GeofenceReceiver.ACTION_RECEIVE_GEOFENCE" />
            </intent-filter>

        </receiver>

Now create this class in your package. 

public class GeofenceReceiver extends BroadcastReceiver {

   public void onReceive(Context context, Intent intent) {
       if (LocationClient.hasError(intent)) {
           handleError(intent);
       } else {
           handleEnterExit(intent);
       }
   }

    private void handleError(Intent intent){
       
    }

   private void handleEnterExit(Intent intent) {
       int transition = LocationClient.getGeofenceTransition(intent);
       if (transition == Geofence.GEOFENCE_TRANSITION_ENTER){
           Log.v("geofence","entered");
       }else if(transition == Geofence.GEOFENCE_TRANSITION_EXIT){
           Log.v("geofence","exited");
       }
   }
}

This is your broadcast receiver. Now create an intent and pending intent with this.

Intent intent = new Intent("com.app.appname.GeofenceReceiver.ACTION_RECEIVE_GEOFENCE");

PendingIntent geoFencePendingIntent = PendingIntent.getBroadcast( getApplicationContext(), 0,                                                                             intent, PendingIntent.FLAG_UPDATE_CURRENT);

Add this to location client while adding geofences.

mLocationClient.addGeofences(geofenceList, geoFencePendingIntent, this);

That's it and now you will get all the transitions of Geofence if your app is not in foreground.

2 comments:

  1. geo fence is not work when app is killed instead we use broadcast

    ReplyDelete
  2. I want a example of perfectly working and tested geofence with source code ,I have tried multiple tutorials but none are working with accuracy

    ReplyDelete