AlarmManager触发得太快

时间:2018-07-31 15:30:07

标签: android kotlin alarmmanager receiver

我试图在我的应用程序中设置AlarmManager,但是我不确定我是否正在做应该做的一切。

我想要实现的是要有一个alaram,它在安装应用程序后获得一次设置,并在每次重新启动后进行重新设置。

我想我已经关闭了,但是现在在将应用程序加载到模拟器上之后,尽管时钟设置为上午11点而不是上午9点,但是警报响起并发出“成功触发”消息。

接收器中的for..else条件可能存在问题,但我不确定,这是我的代码:

App.kt

class App : Application() {

override fun onCreate() {

    CheckExpiryAlarmReceiver.AlarmReceiver.setExpiryAlarmMonitor(applicationContext)

    super.onCreate()
}
}

CheckExpiryAlarmReceiver.kt

private const val REQUEST_CODE = 0
private const val ALARM_HOUR = 9

class CheckExpiryAlarmReceiver : BroadcastReceiver() {

object AlarmReceiver {

    fun setExpiryAlarmMonitor(context: Context?) {

        val alarmMgr: AlarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        val alarmIntent: PendingIntent

        val mIntent = Intent(context, CheckExpiryAlarmReceiver::class.java)

        alarmIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, mIntent, 0)

        // Set the alarm to start at 9:00 AM
        val calendar: Calendar = Calendar.getInstance()

        calendar.timeInMillis = System.currentTimeMillis()

        calendar.set(Calendar.HOUR_OF_DAY, ALARM_HOUR)

        // Every once a day
        alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, alarmIntent)
    }
}

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

    // Check if triggered by system re-boot
    if(intent?.action == "android.intent.action.BOOT_COMPLETED") {

       AlarmReceiver.setExpiryAlarmMonitor(context)

    } else { // Action to be actually performed by Alarm receiver

        Log.i("AlarmMonitor", "Triggered successfully!")

    }
}

}

有什么想法吗?感谢您的帮助! :)

0 个答案:

没有答案