简体   繁体   中英

BroadcastReceiver Intent delivered without extras

My BroadcastReceiver is not receiving the Intent extras when it gets delivered.

Here's how I create the PendingIntent

private fun getPendingIntent(type: ReminderType, date: DateTime): PendingIntent {
    val context = App.appContext
    val intent = Intent(context, TimeBasedRemindersBroadcastReceiver::class.java)
    intent.putExtra(ARG_REMINDER_TYPE, type)
    intent.putExtra(ARG_DATE_TIME, date)
    val intentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
    } else {
        PendingIntent.FLAG_UPDATE_CURRENT
    }
    val requestCode = date.dayOfWeek * 100 + type.ordinal
    return PendingIntent.getBroadcast(
        context,
        requestCode,
        intent,
        intentFlags
    )
}

As you can see, the extras are clearly appended as soon as the Intent is initialised. When the BroadcastReceiver gets fired, the intent.extras is empty.

After researching this, I can only assume this has something to do with Android 12 and mutability intent flags. All of the older answers to this question seem to fix it by just adding the FLAG_UPDATE_CURRENT flag.

I have also tried the same code running with PendingIntent.FLAG_IMMUTABLE but the result is the same.

Not sure if it matters, but I am using AlarmManager to deliver the PendingIntent .

After @ShlomiKatriel commented above and pointed me to a similar question, I have come to a solution.

The reason this happens is because Intent does not know how to serialize and deserialize every type of object.

In my case, the problematic line was:

intent.putExtra(ARG_REMINDER_TYPE, type)

Because the type that I was trying to pass as extra was actually an enum . What makes this very confusing is that if a single serialization fails, it loses ALL of the data, not just the one that failed. That's why my ARG_DATE_TIME was being lost as well.

After I've replaced the enum extra with a primitive type, it started to work as expected and I could access my other extras as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM