使用 putExtra() 时地理围栏事件出错

Error on Geofencing event when I use putExtra()

我在尝试将对象传递给 GeofenceTransitionIntentService 时遇到问题。每当我使用 putExtra() 时,geofenceTransition 为 -1,因此我总是会收到错误消息,其余代码将被跳过。如果我不使用 putExtra(),通知会起作用。 有什么办法可以解决吗?

这是我要放置额外内容的代码段,currentCharacter 是一个 Character 并且确实实现了可序列化。

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);
}

这是出错的那段代码。这是在扩展 IntentService

的 class 中
 @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");

}

您可以使用 "Shared Preference's" 而不是 intent.putExtra(); 来绕过该问题。这是另一个 Whosebug 问题的 link。 How to bypass intent extras in Android? 接受的答案解释了如何使用它。

编辑: 这是处理 "Shared Preference's" 的另一个来源 https://developer.android.com/training/basics/data-storage/shared-preferences.html

好的,我通过将对象转换为 Json 字符串并像这样传递它来修复它。 在 intentservice 中,我从 Json 字符串创建了一个新对象。