重复警报在特定时间准确触发不能正常工作

时间:2017-09-04 10:03:00

标签: android kotlin alarmmanager

我试图在特定时间(每天上午8:00)设置闹钟 但是警报管理员在特定时间的2分钟之后的某个时间并且在某个时间之后的某个时间不会在准确的时间点火。

我的代码

class AlarmReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {

    val builder = NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle("notification title")
            .setContentInfo("info")
            .setDefaults(NotificationCompat.DEFAULT_SOUND)


    val notifManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    notifManager.notify(0, builder.build())
}

companion object {

    fun startAlarmManager(context: Context, hour: Int, minute: Int = 0) {
        // set time for alarm manager
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = System.currentTimeMillis()
        calendar.set(Calendar.HOUR_OF_DAY, hour)
        calendar.set(Calendar.MINUTE, minute)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        if (calendar.timeInMillis < System.currentTimeMillis())
            calendar.timeInMillis += 1000 * 60 * 60 * 24

        // set up alarm manager
        val alarmReceiver = Intent(context, AlarmReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiver, PendingIntent.FLAG_UPDATE_CURRENT)
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY,
                pendingIntent)

        context.toast("started")
    }

    fun stopAlarmManager(context: Context) {
        // set up alarm manager
        val alarmReceiver = Intent(context, AlarmReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiver, 0)
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)

    }


}

}

当我使用

alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis,pendingIntent)

工作正常,通知在特定时间发送 还有一件事,我已经读过这个问题,但没有解决我的问题。

Using Alarmmanager to start a service at specific time

Alarm Manager not working at specific given time interval

以及

Scheduling Repeating Alarms

0 个答案:

没有答案