Я не могу получить дополнительные данные из намерения, отправленного AlarmManager - PullRequest
0 голосов
/ 04 мая 2020

Создание 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())
    }

Что я делаю не так?

1 Ответ

0 голосов
/ 04 мая 2020

Оказывается, проблема была в том, что AlarmManager не мог нормально передавать Serializable объекты (также с Parcelable, это было найдено экспериментально). Решение состоит в том, чтобы передать объект в виде потока байтов, найденного здесь: Передача сериализуемого объекта ожидающему намерению

...