0

我想创建一个每天晚上 20 点发出通知的应用程序。为此,我需要为每天晚上 20 点执行的函数计时。解决这个问题的最佳方法是什么?我应该使用什么?
这是我要执行的功能:

private fun throwNotification() {
    notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    val intent = Intent(applicationContext, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
    notificationChannel.enableLights(true)
    notificationChannel.lightColor = Color.RED
    notificationChannel.enableVibration(true)
    notificationManager.createNotificationChannel(notificationChannel)

    builder = Notification.Builder(this, channelId)
        .setContentTitle("Test")
        .setContentText("This is a test notification")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .setChannelId(channelId)

    notificationManager.notify(0, builder.build())
}
4

1 回答 1

0

您应该关注以下任务。

  1. 该函数应在晚上 20 点准确执行。
  2. #1 应该每天重复。
  3. 即使应用程序关闭,也应该推送通知。
  4. 上述问题与设备是否重启无关。

我找到的解决方案如下,要求应用程序至少启动一次。

#1~3 可以通过AlarmManager实现。在应用程序首次启动时,调用以下注册alarmIntent的代码。

private var alarmMgr: AlarmManager? = null
private lateinit var alarmIntent: PendingIntent

alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmIntent = Intent(context, YourAlarmReceiver::class.java).let { intent ->
    PendingIntent.getBroadcast(context, 0, intent, 0)
}

// Set the alarm to start at 20:00.
val calendar: Calendar = Calendar.getInstance().apply {
    timeInMillis = System.currentTimeMillis()
    set(Calendar.HOUR_OF_DAY, 20)
    set(Calendar.MINUTE, 0)
    set(Calendar.SECOND, 0)
}

// setRepeating() lets you specify a precise custom interval--in this case,
// 1 day.
alarmMgr?.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        1000 * 60 * 60 * 24,
        alarmIntent
)

在这里,YourAlarmReceiver的 onReceive() 将在每 20 点被alarmIntent 调用。所以你要做的只是在这个 onReceive() 中调用throwNotification( )。

#4 也很简单,也就是说,它可以通过监听 BOOT_COMPLETED 事件来实现。

于 2020-10-09T09:50:58.210 回答