Search code examples
androidkotlinbroadcastreceiveralarmmanager

How to add multiple alarms in android studio Kotlin?


I'm trying to add alarms to my app that trigger a notification; the problem is, whenever I add a new alarm, the previous one doesn't work.

I think it is because of the request code passed (all alarms have the same code(0)), but I don't know how to pass a new request code each time.

This is my setAlarm() function:

    private fun setAlarm() {
        alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
        val intent = Intent(this, AlarmReceiver::class.java)
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)

        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calender.timeInMillis,
            AlarmManager.INTERVAL_DAY,
            pendingIntent
        )
        Toast.makeText(this, "alarm set", Toast.LENGTH_SHORT).show()

    }

And this is my alarm receiver class:

    private lateinit var pendingIntent: PendingIntent
    override fun onReceive(p0: Context?, p1: Intent?) {

        val intent = Intent(p0, MainActivity::class.java)
        p1!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        pendingIntent = PendingIntent.getActivity(p0, 0, intent, 0)

        val builder = NotificationCompat.Builder(p0!!, "androidAlarm")
            .setSmallIcon(drawable.notification_bg)
            .setContentTitle("Your reminder!")
            .setContentText("Your work has to be done now!")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setContentIntent(pendingIntent)


        val notificationManager = NotificationManagerCompat.from(p0)
        if (ActivityCompat.checkSelfPermission(
                p0,
                Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        notificationManager.notify(123, builder.build())
    }

}

I also have no idea how I can repeat an alarm if the user wants to.

I tried using System.currentTimeMillis() in the request code parameter, but it didn't help.

I searched a lot but didn't find much.

This is the code I used when I tried System.currentTimeMillis():

private fun setAlarm() {
    calender = Calendar.getInstance()
    alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager

    val intent = Intent(this, AlarmReceiver::class.java)
    pendingIntent = PendingIntent.getBroadcast(this, System.currentTimeMillis().toInt(), intent, 0)
    alarmManager.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calender.timeInMillis,
        AlarmManager.INTERVAL_DAY,
        pendingIntent)
    Toast.makeText(this, "alarm set", Toast.LENGTH_SHORT).show()

}

And this is the receiver class:

class AlarmReceiver : BroadcastReceiver() {
private lateinit var pendingIntent: PendingIntent
override fun onReceive(p0: Context?, p1: Intent?) {
    val id = System.currentTimeMillis().toInt()
    val intent = Intent(p0, MainActivity::class.java)
    p1!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    pendingIntent = PendingIntent.getBroadcast(p0, System.currentTimeMillis().toInt(), intent, 0)


    val builder = NotificationCompat.Builder(p0!!, "androidAlarm")
        .setSmallIcon(drawable.notification_bg)
        .setContentTitle("Your reminder!")
        .setContentText("Your work has to be done now!")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setDefaults(NotificationCompat.DEFAULT_ALL)
        .setContentIntent(pendingIntent)


    val notificationManager = NotificationManagerCompat.from(p0)
    if (ActivityCompat.checkSelfPermission(
            p0,
            Manifest.permission.POST_NOTIFICATIONS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return
    }
    notificationManager.notify(123, builder.build())
    Log.e("notification: ", "received a notification: ${pendingIntent.toString()}")
}

}

I am using setRepeating because set and setExact don't work, they trigger the alarm as soon as I add it regardless of the time it is set in.

Just for instance, my main goal is to be able to create more than one alarm with different times to be triggered at, and also have the ability to repeat a certain alarm daily if the user wants to


Solution

  • So after more than a week, it turned out that the request code isn't being unique by using System.currentTimeMillis(), or calender.timeInMillis, I tried this:

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

    and the request code is now being unique every single time and I can add different alarms at different times