Search code examples
androidandroid-intentintentservicegeofencing

Error on Geofencing event when I use putExtra()


I'm having trouble trying to pass an object to the GeofenceTransitionIntentService. Whenever I use putExtra(), the geofenceTransition is -1 so I always get an error and the rest of the code is skipped. If I don't use putExtra(), the notification does work. Is there any way to solve this?

This is the piece of code where i want to put the extras, currentCharacter is a Character and does implement serializable.

private PendingIntent getGeofencePendingIntent() {
    if (geofencePendingIntent != null) {
        Log.d(TAG, "getGeofencependingintent return");
        return geofencePendingIntent;
    }

    Intent intent = new Intent(this, GeofenceTransitionIntentService.class);
    intent.putExtra("char", currentCharacter);
    Log.d(TAG, "getGeofencependingintent new");
    return PendingIntent.getService(this, 0, intent, PendingIntent.
            FLAG_UPDATE_CURRENT);
}

Here is the piece of code where it goes wrong. This is in a class that extends IntentService

 @Override
 protected void onHandleIntent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); 
    if (geofencingEvent.hasError()) {
        String errorMessage = "err";
        Log.e(TAG, errorMessage);
        return;
    }

    // Get the transition type.
    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    // Test that the reported transition was of interest.
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

        // Get the geofences that were triggered. A single event can trigger multiple geofences.
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

        // Get the transition details as a String.
        String geofenceTransitionDetails = getGeofenceTransitionDetails(
                this,
                geofenceTransition,
                triggeringGeofences
        );

        // Send notification and log the transition details.
        sendNotification(geofenceTransitionDetails);
        Log.d(TAG, geofenceTransitionDetails);
    } else {
        // Log the error.
        Log.e(TAG, "error");
    }
  currentCharacter = intent.getSerializableExtra("char");

}

Solution

  • Ok, I fixed it by converting the object to a Json string and passing it like that. In the intentservice, I created a new object from the Json string.