gpt4 book ai didi

android - 广播接收器没有收到额外的东西

转载 作者:行者123 更新时间:2023-12-04 15:00:11 25 4
gpt4 key购买 nike

初始化后,我的 View 模型会创建一个警报。它设置为在应用程序启动后 10 秒响铃。警报管理器收到一个 pendingIntent。 pendingIntent 接收一个 Intent 。 Intent 是一个广播接收器。Intent bundle 含使我遇到问题的额外内容。以下是我的 View 模型的相关代码:

MainActivityViewModel.kt

    init {
val intent =
Intent(app, TimetableAlarmReceiver::class.java).also {
val alarmMessage =
"message"

it.putExtra("message", alarmMessage)
Timber.i("The extra message is $alarmMessage")

it.putExtra("dayOfWeek", getTodayEnumDay())
Timber.i("The extra dayOfWeek is ${getTodayEnumDay()}")
}
Timber.i("The intent is $intent")

val pendingIntent = PendingIntent.getBroadcast(
app,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val alarmManager = app.getSystemService(Context.ALARM_SERVICE) as AlarmManager

alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis().plus(10000L),
pendingIntent
)
}

广播接收器未检测到任何额外内容:

TimetableAlarmReceiver.kt

    override fun onReceive(context: Context, intent: Intent?) {
Timber.i("The receiver has been called")
val notificationManager = ContextCompat.getSystemService(
context,
NotificationManager::class.java
) as NotificationManager

if(intent!=null){
Timber.i("The extras are:${intent.extras}")
val message = intent.getStringExtra("message")
Timber.i("The extra message is $message")
val dayOfWeek = intent.getSerializableExtra("dayOfWeek") as DayOfWeek?
Timber.i("The extra dayOfWeek is $dayOfWeek")
}

日志的讽刺之处:

MainActivityViewModel.kt 日志

2021-04-14 17:42:38.684 5492-5492/com.example.android.mycampusapp I/MainActivityViewModel: The extra message is message
2021-04-14 17:42:38.687 5492-5492/com.example.android.mycampusapp I/MainActivityViewModel: The extra dayOfWeek is WEDNESDAY
2021-04-14 17:42:38.687 5492-5492/com.example.android.mycampusapp I/MainActivityViewModel: The intent is Intent { cmp=com.example.android.mycampusapp/.timetable.receiver.TimetableAlarmReceiver (has extras) }

TimetableAlarmReceiver.kt 日志:

2021-04-14 17:53:38.884 5814-5814/com.example.android.mycampusapp I/TimetableAlarmReceiver: The receiver has been called
2021-04-14 17:53:38.885 5814-5814/com.example.android.mycampusapp I/TimetableAlarmReceiver: The extras are:Bundle[EMPTY_PARCEL]
2021-04-14 17:53:38.886 5814-5814/com.example.android.mycampusapp I/TimetableAlarmReceiver: The extra message is null
2021-04-14 17:53:38.886 5814-5814/com.example.android.mycampusapp I/TimetableAlarmReceiver: The extra dayOfWeek is null

我在这里尝试了各种关于堆栈溢出的解决方案,其中涉及已成功调用的接收器。其中一些涉及更改未决 Intent 标志,但这在这里没有帮助。我使用的是正确的标志 PendingIntent.FLAG_UPDATE_CURRENT。在任何情况下,将标志更改为 Intent.FILL_IN_DATA 或 PendingIntent.FLAG_CANCEL_CURRENT 都不起作用。

最佳答案

啊。您不能将自定义可序列化对象作为“额外”放入发送到 AlarmManagerIntent 中。您只能将已知类型放在那里。如果您需要自定义类型,则需要将自定义对象序列化为字节数组,并将其作为“额外”添加到您的 Intent 中。

关于android - 广播接收器没有收到额外的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67094131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com