【发布时间】:2021-07-09 15:27:56
【问题描述】:
在初始化时,我的视图模型会创建一个警报。它设置为在应用程序启动后 10 秒响铃。警报管理器接收到一个挂起的Intent。 pendingIntent 接收到一个意图。意图是广播接收器。意图包含让我遇到问题的额外内容。以下是我的视图模型的相关代码:
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
我在这里尝试了多种解决堆栈溢出问题的方法,其中涉及已成功调用的接收器。其中一些涉及更改待处理的意图标志,但这在这里没有帮助。我正在使用正确的标志 PendingIntent.FLAG_UPDATE_CURRENT。在任何情况下,将标志更改为 Intent.FILL_IN_DATA 或 PendingIntent.FLAG_CANCEL_CURRENT 都不起作用。
【问题讨论】:
-
getTodayEnumDay()返回什么? -
尝试在
putExtra()调用中使用getTodayEnumDay().toString()
标签: android kotlin android-intent broadcastreceiver