0

I was trying to setup AlarmManager in my application but I am not sure if I am doing everything how it should be.

What I want to achieve is to have an alaram which gets setup once after installation of application and re-setup after every re-boot.

I think I am close but now just after loading application on emulator, alarm goes off and gives "Successully triggered" message although clock is set to 11 AM, not 9 AM...

It might be an issue with for..else condition in my Receiver but I am not sure, here is my code:

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!")

    }
}

}

Any thoughts? Thanks for all help! :)

0 Answers0