使用putExtra()

时间:2017-01-26 12:45:32

标签: android android-intent intentservice geofencing

我在尝试将对象传递给GeofenceTransitionIntentService时遇到了麻烦。每当我使用putExtra()时,geofenceTransition为-1,所以我总是得到一个错误,其余代码被跳过。如果我不使用putExtra(),通知确实有效。 有什么方法可以解决这个问题吗?

这是我想要添加额外内容的代码段,currentCharacter是一个Character并且实现了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);
}

以下是出错的代码。这是一个扩展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");

}

2 个答案:

答案 0 :(得分:2)

您可以使用&#34;共享偏好设置&#34;来绕过问题。而不是intent.putExtra();.这是指向另一个StackOverflow问题的链接。 How to bypass intent extras in Android?接受的答案解释了如何使用它。

编辑:这是处理&#34;共享偏好&#34;的另一个来源。 https://developer.android.com/training/basics/data-storage/shared-preferences.html

答案 1 :(得分:2)

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