Intent extras are lost with a broadcast PendingInt

2019-02-19 08:31发布

问题:

I create a PendingIntent like this:

Intent intent = new Intent(context, AlarmReceiver.class);
intent.setAction("Foobar");
intent.putExtra(EXTRA_ALARM, alarm);
intent.putExtra(EXTRA_TRYTWO, tryTwo);
intent.putExtra(EXTRA_BEGAN_TIME, beganTime);

return PendingIntent.getBroadcast(
        context, (int) alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT
);

The alarm variable is a Parcelable. I schedule the PendingIntent like this:

PendingIntent alarmModifyPendingIntent = PendingIntent.getActivity(
        context, 0, editIntent, PendingIntent.FLAG_CANCEL_CURRENT
);

am.setAlarmClock(
    new AlarmManager.AlarmClockInfo(time, alarmModifyPendingIntent), pendingIntent
);

Where the variable pendingIntent is created as shown above.

The AlarmReceiver object receives an Intent in onReceive at the correct time. However, this Intent does not contain the extras that I have set. For instance intent.getParcelableExtra(EXTRA_ALARM) returns null.

This problem occurs with Android 7.0 (API level 24) at least, using an LG G5.

Using FLAG_CANCEL_CURRENT or FLAG_ONE_SHOT does not work either.

回答1:

The alarm variable is a Parcelable.

It is not safe to put a custom Parcelable in an Intent that is delivered to another process. This is particularly true with AlarmManager on Android 7.0.

You need to replace that Parcelable with something else, such as a byte[], where you manually convert your Parcelable to/from that byte[].