Geofences not triggering (pendingintents and broadcastreceiver)

gregor picture gregor · Sep 9, 2014 · Viewed 8.2k times · Source

I've used the Android tutorial with Geofences which, obviously, doesn't work when app is closed. So, after searching around, I've noticed user b-ryce on SO used BroadcastReceiver so geofences get triggered even if app is not active (link for his SO question).

I just cannot force geofences to trigger when I move outside/inside registered location. Here's my procedure:

    /**
     * GeoLocation library
     */
    mGeoLocation = new GeoLocation(sInstance);


    /**
     * mReceiver init
     */
    mReceiver = new Receiver();
    sInstance.registerReceiver(mReceiver, mReceiver.createIntentFilter());

And inside GeoLocation class:

/*
 * Create a PendingIntent that triggers an IntentService in your
 * app when a geofence transition occurs.
 */
protected PendingIntent getTransitionPendingIntent() {
    if (mGeoPendingIntent != null) {
        return mGeoPendingIntent;
    }

    else {

        // Create an explicit Intent
        //  Intent intent = new Intent(mContext,
        //          ReceiveTransitionsIntentService.class);

        Intent intent = new Intent(getClass().getPackage().getName() + ".GEOFENCE_RECEIVE");

        /**
         * Return the PendingIntent
         */
        return PendingIntent.getBroadcast(
                mContext,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

    }
}

Here's how I create new geofence:

                        Geofence fence = new Geofence.Builder()
                                .setRequestId(hashCode)
                                        // when entering this geofence
                                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                                .setCircularRegion(
                                        Double.parseDouble(single.getSetting("latitude")),
                                        Double.parseDouble(single.getSetting("longitude")),
                                        Float.parseFloat(single.getSetting("radius")) // radius in meters
                                )
                                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                                .build();

                        mGeofences.add(fence);

Array gets populated and we call AddGeofences method inside Geofence class

mGeoLocation.AddGeofences(mGeofences);

AndroidManifest.xml for reciever class:

    <!-- RECEIVER -->
    <receiver android:name=".Receiver" >
    </receiver>

And the Receiver class should just log when geofence triggers

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    Log.d("sfen", "Broadcast recieved "+ action +" but not needed.");
}

The problem is, that Geofence are triggering ONLY when I open map inside my app where I pick the locations. Closing the app (running it in background) doesn't trigger anything and geofence transitions don't trigger anything.

Can someone tell me what am I doing wrong?

Answer

Jishi Chen picture Jishi Chen · Sep 12, 2014

you should use IntentService to receive geofencing event(not receiver).I wrote a demo at https://github.com/chenjishi/android_location_demo.

1.first define LocationClient

    private LocationClient locationClient;

2.init it

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resp == ConnectionResult.SUCCESS) {
        locationClient = new LocationClient(this, this, this);
        locationClient.connect();
    }
}

3.when connect success, register geofences

@Override
public void onConnected(Bundle bundle) {
    ArrayList<Store> storeList = getStoreList();
    if (null != storeList && storeList.size() > 0) {
        ArrayList<Geofence> geofenceList = new ArrayList<Geofence>();
        for (Store store : storeList) {
            float radius = (float) store.radius;
            Geofence geofence = new Geofence.Builder()
                    .setRequestId(store.id)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .setCircularRegion(store.latitude, store.longitude, radius)
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .build();

            geofenceList.add(geofence);
        }

        PendingIntent geoFencePendingIntent = PendingIntent.getService(this, 0,
                new Intent(this, GeofenceIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
        locationClient.addGeofences(geofenceList, geoFencePendingIntent, this);
    }
}

4.finally define the IntentService to receive geofencing event

public class GeofenceIntentService extends IntentService {
public static final String TRANSITION_INTENT_SERVICE = "ReceiveTransitionsIntentService";

public GeofenceIntentService() {
    super(TRANSITION_INTENT_SERVICE);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (LocationClient.hasError(intent)) {
        //todo error process
    } else {
        int transitionType = LocationClient.getGeofenceTransition(intent);
        if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ||
                transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
            List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);

            for (Geofence geofence : triggerList) {
                generateNotification(geofence.getRequestId(), "address you defined");
            }
        }
    }
}

private void generateNotification(String locationId, String address) {
    long when = System.currentTimeMillis();
    Intent notifyIntent = new Intent(this, MainActivity.class);
    notifyIntent.putExtra("id", locationId);
    notifyIntent.putExtra("address", address);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.dac_logo)
                    .setContentTitle(locationId)
                    .setContentText(address)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setWhen(when);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify((int) when, builder.build());
}

}