创建PendingIntent。
fun createPendingIntent(context: Context, record: Record): PendingIntent {
// create the intent using a unique type
val intent = Intent(context.applicationContext, AlarmReceiver::class.java).apply {
action = Constants.actionShowRecord
type = record.uuid.toString()
putExtra(Record::class.java.simpleName, record)
putExtra("test", "23")
}
return PendingIntent.getBroadcast(context, (0..10).random(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun scheduleAlarmForRecord(context: Context, record: Record) {
// get the AlarmManager reference
val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// get the PendingIntent for the alarm
val alarmIntent = createPendingIntent(context, record)
// for testing
notific(context, alarmIntent)
// schedule the alarm
scheduleAlarm(record, alarmIntent, alarmMgr)
}
创建警报:
private fun scheduleAlarm(record: Record, alarmIntent: PendingIntent, alarmMgr: AlarmManager) {
// Set up the time to schedule the alarm
val date = DateAndTimeUtility()
val datetimeToAlarm = date.getDateAndTimeForRecord(record)
alarmMgr.set(AlarmManager.RTC, datetimeToAlarm.timeInMillis, alarmIntent)
}
BroadcastReceiver:
class AlarmReceiver : BroadcastReceiver() {
private val TAG = AlarmReceiver::class.java.simpleName
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive() called with: context = [$context], intent = [$intent]")
val test = intent.getStringExtra("test")
if (intent.action != null) {
if (intent.action.equals(Constants.actionShowRecord, ignoreCase = true)) {
val record = intent.getSerializableExtra(Record::class.java.simpleName) as? Record
if (record != null) {
NotificationHelper.createRecordTimeNotification(context, record)
}
}
}
}
}
在正确的时间捕捉信号,但在收到来自意图的额外信号时 intent.getStringExtra("test")
或 intent.getSerializableExtra(Record::class.java.simpleName) as? Record
变成了空的。
我认为问题出在AlarmManager上,因为当通过点击通知来调用Intent时,数据被正确地接收到了
fun notific(context: Context, pendingIntent: PendingIntent) {
val channelId = "${context.packageName}-${context.getString(R.string.time_to_record)}"
val notificationBuilder = NotificationCompat.Builder(context, channelId).apply {
setSmallIcon(R.drawable.ic_stat_dp)
setContentTitle("test")
setContentText("test")
setAutoCancel(true)
setStyle(NotificationCompat.BigTextStyle().bigText("test"))
priority = NotificationCompat.PRIORITY_HIGH
setContentIntent(pendingIntent)
}
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(1002, notificationBuilder.build())
}
我到底做错了什么?
原来问题是AlarmManager无法正常传输Serializable对象(也是用Parcelable,实验发现).解决方法是将对象作为字节流传递,在这里找到。将Serializable对象传递给Pending Intent。