【问题标题】:Schedule Android function when App is closed at specific time在特定时间关闭 App 时安排 Android 功能
【发布时间】:2020-10-09 09:22:18
【问题描述】:

我想创建一个每天晚上 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())
}

【问题讨论】:

  • 您需要一个后台服务,该服务每次都运行,如果是晚上 20 点,则每小时检查一次并执行您的任务。
  • 如果您想保证在我看来任务已执行,这就是解决方案。
  • 不喜欢后台服务一直运行,有没有更好的解决方案?
  • 如果您想要有保证的执行,这是正确的方法,或者尝试一下警报管理器。

标签: android kotlin push-notification notifications background-task


【解决方案1】:

您应该关注以下任务。

  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事件来实现。

【讨论】:

    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多