I'm trying to setup an AlarmManager in my Kotlin Android app, but it triggers immediately if the alarm is in the past

Viewed 109

I am currently trying to make an app that sends the user a message every morning. However, my alarm triggers immediately when I open my app if the alarm's trigger time is earlier than the current time.

This is my code:

This in my onCreate:

// Get AlarmManager instance
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        // Intent part
        val intent = Intent(this, AlarmReceiver::class.java)
        intent.action = "FOO_ACTION"
        intent.putExtra("KEY_FOO_STRING", "Alarm triggered!")

        val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)

        val calendar: Calendar = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, 21)
            set(Calendar.MINUTE, 42)
        }

        alarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP,
                calendar.timeInMillis,
                AlarmManager.INTERVAL_DAY,
                pendingIntent
        )

And my receiver just in my MainActivity:

class AlarmReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            // Is triggered when alarm goes off, i.e. receiving a system broadcast
            if (intent.action == "FOO_ACTION") {
                val fooString = intent.getStringExtra("KEY_FOO_STRING")
                Toast.makeText(context, fooString, Toast.LENGTH_LONG).show()
                val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                vibrator.vibrate(200)
            }
        }
    }
1 Answers

I found a solution to one of the major problems I was having in this question. I found a way to keep my alarm from triggering if the date I want it to trigger is in the past-

if (calendar.timeInMillis < System.currentTimeMillis()) { // checks if alarm time is earlier than system time
            calendar.add(Calendar.DAY_OF_YEAR, 1) // goes to next day
        }

I had another problem here initially, but I realized this was probably too many things to cram into a single StackOverflow question. I edited my question to just include this issue, and am leaving this code snippet here for people who might have this issue in the future.

Related