简体   繁体   中英

Kotlin - WorkManager notification before an event

How to create a notification that will be sent some days before the start date of an event?

The start date was created with a date range picker and I need to receive a notification that reminds me that in 3 days I have something to do.

Assuming your question is primarily in triggering a notification at a specific time , I think something like this will do:

  • Setting up an alarm using the AlarmManager
  • Configure a BroadcastReceiver to handle the alarm

The code below is somewhat modified version of how I implemented it for a daily notification (which can be switched on and off). I use a custom Handler to send a message, which leads to processing the message for creating a notification. The basics for the actual notifications are in the code, but you'll need some effort to configure this. Let me know if you need more detail.

class EventNotificationManager(ctx: Context) {

    private val context: WeakReference<Context> = WeakReference(ctx.applicationContext)
    private val flags = FLAG_UPDATE_CURRENT.let { if (SDK_INT < M) it else it or FLAG_IMMUTABLE }
    private val alarmIntent =
        getBroadcast(ctx, 1486, Intent(ctx, EventWakeUpJob::class.java), flags)

    private fun getContext() = context.get() ?: AppName.app.applicationContext

    fun startTask() {
        val ctx = getContext()
        val alarmManager = ctx.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return

        if (!isEventAlertingActive()) {
            alarmManager.cancel(alarmIntent)
        } else {
            var alertIt = customPickedDate.minDays(3)
            // Make sure it is at least after now
            alarmManager.setExact(RTC, alertIt.millis, alarmIntent)
        }
    }

    fun alertEvents() {
        // This is only the basics. Please see other examples for this.
        // Custom handler which does sendMessage + handleMessage
        // In handleMessage (SDK_INT >= O): 
        // NotificationManager.createNotificationChannel
        // msg = Notification.Builder(ctx, yourChannelId).apply { ... }.build()
        // NotificationManager.notify(customMessageId, msg)
    }
}

class EventWakeUpJob : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        context?.let { EventNotificationManager(it).alertEvents() }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM