Я пытаюсь запланировать уведомление на будущее, но по какой-то причине задание не выполняется.
Я тестирую на Huawei P20 Pro с Android / Emui 9
здесь я добавляю свои вакансии:
events.forEach {
val sdf = SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.GERMANY)
val date = Calendar.getInstance()
date.time = sdf.parse(it.date)
if (date.time > Calendar.getInstance().time) {
//only schedule notification when the event is in future
NotificationHelper.scheduleNotification(context!!, date.time.time, it)
} else {
println(false)
}
}
это мой метод scheduleNotification (), где я создаю задание и планирую его:
fun scheduleNotification(context: Context, triggerTime: Long, eventItem: EventItem) {
val time = triggerTime.minus(Calendar.getInstance().timeInMillis)
if (time > 0) {
val pb = PersistableBundle()
pb.putInt("eventId", eventItem.eventId)
pb.putString("eventName", eventItem.name)
pb.putString("eventTime", eventItem.date)
val jobInfo =
JobInfo.Builder(eventItem.eventId, ComponentName(context, MyNotificationPublisher::class.java))
.setPersisted(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setOverrideDeadline(time)
.setMinimumLatency(time)
.setExtras(pb)
.build()
val jobScheduler = context.applicationContext
.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.schedule(jobInfo)
}
}
и MyNotificationPublisher, который должен показывать уведомление:
class MyNotificationPublisher : JobService() {
override fun onStopJob(params: JobParameters?): Boolean {
return true
}
override fun onStartJob(params: JobParameters?): Boolean {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val bundle = params?.extras ?: PersistableBundle.EMPTY
val notificationId = bundle.getInt("eventId")
val eventName = bundle.getString("eventName", "") +
" at " +
bundle.getString("eventTime", "")
val notification = buildNotification(this, eventName, notificationId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(
NotificationChannel(
NOTIFICATION_CHANNEL,
NOTIFICATION_CHANNEL,
NotificationManager.IMPORTANCE_HIGH
)
)
}
notificationManager.notify(notificationId, notification)
return true
}
private fun buildNotification(context: Context, eventName: String, id: Int): Notification? {
val notificationIntent = Intent(context, MyNotificationPublisher::class.java)
val notification = Notification.Builder(context)
.setContentTitle("a new event has triggered")
.setContentText(eventName)
.setSmallIcon(R.drawable.ic_stat_baseline_date_range_black_48)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification.setChannelId(NOTIFICATION_CHANNEL)
}
notificationIntent.putExtra(NOTIFICATION, notification.build())
notificationIntent.putExtra(NOTIFICATION_ID, id)
return notification.build()
}
companion object {
const val NOTIFICATION_ID = "notification_id"
const val NOTIFICATION = "notification"
const val NOTIFICATION_CHANNEL = "Test Channel"
}
}