Marvil
Marvil

Reputation: 31

How to schedule recurring notifications in kotlin?

I've been looking for this for a couple of hours but I haven't found anything helpful. Right now, I have an activity (called other_recurringreminder) that sets a time (fomartted calendar, HH:mm; string), repetition frequency (int), repetition unit (like minutes, hours, days; string), whether it's on or off (bool), and a name (string)

In other_recurringreminder.kt, I have this function:

fun sendnotification()
{
     val channelID = "channel1"
     val notificationID = 1
     val sharedPreferences: SharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
     val builder = NotificationCompat.Builder(this, "channelID")
         .setSmallIcon(R.drawable.centr)
         .setColor(resources.getColor(R.color.purple))
         .setContentTitle(sharedPreferences.getString("Alarm1Name_USERPREFS", "Reminder 1"))
         .setContentText(getString(R.string.notif_recurringreminders))
         .setPriority(NotificationCompat.PRIORITY_DEFAULT)
         .setAutoCancel(true)

     with(NotificationManagerCompat.from(this)) {
         notify(notificationID, builder.build())
     }
 }

Which sends the notification when called. How can I make it so that my app sends this notification at a time from SharedPreferences, with a title from SP, and repeats every x units from SP? Should this function be in another kotlin file? Can this work even after a restart, when my app hasn't yet been opened?If I want to schedule more than one notif with different values, do I need to duplicate anything? Sorry if it's a dumb question, I'm fairly new to kotlin. and thanks!

Upvotes: 0

Views: 3177

Answers (1)

Niaj Mahmud
Niaj Mahmud

Reputation: 469

you can use alarm manager for it. first create a class with broadcast receiver like

                class AlarmReceiver : BroadcastReceiver() {
                
                    override fun onReceive(context: Context, intent: Intent?) {
                        Log.d("this", "notify")
                
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                
                            val intent = Intent(context, AlarmActivity2::class.java)
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                            val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
                
                            val builder = NotificationCompat.Builder(context, "111")
                                .setSmallIcon(R.drawable.blue_stringart)
                                .setContentTitle("Alarm is running")
                                .setAutoCancel(true)
                                .setDefaults(NotificationCompat.DEFAULT_ALL)
                                .setDefaults(NotificationCompat.DEFAULT_SOUND)
                                .setDefaults(NotificationCompat.DEFAULT_VIBRATE)
                                .setPriority(NotificationCompat.PRIORITY_HIGH)
                                .addAction(R.drawable.ic_baseline_stop_24,"Stop",pendingIntent)
                                .setContentIntent(pendingIntent)
                
                            val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
                            val r = RingtoneManager.getRingtone(context, notification)
                            r.play()
                
                            val notificationManagerCompat = NotificationManagerCompat.from(context)
                            notificationManagerCompat.notify(123, builder.build())
                
                        }
                
                    }
                
                } 
        

after that go to your activity class make 2 method and call in oncreate

            private fun setAlarm1() {
            var calender: Calendar
          calender = Calendar.getInstance()
                        calender.set(Calendar.HOUR_OF_DAY, PUT_YOUR_ALARM HOUR)
                        calender.set(Calendar.MINUTE, PUT_YOUR_ALARM MINUTE)
                        calender.set(Calendar.SECOND, 0)
                    alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    val thuReq: Long = Calendar.getInstance().timeInMillis + 1
                    var reqReqCode = thuReq.toInt()
                    if (calender.timeInMillis < System.currentTimeMillis()) {
                        calender.add(Calendar.DAY_OF_YEAR, 1)
                    }
                    val alarmTimeMilsec = calender.timeInMillis
                    val intent = Intent(this, AlarmReceiver::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
                    val pendingIntent = PendingIntent.getBroadcast(this, reqReqCode, intent, 0)
            
                    alarmManager.setRepeating(
                        AlarmManager.RTC_WAKEUP,
                        calender.timeInMillis,
                       HERE_PUT_YOUR_HOUR * 60 * 60 * 1000,
                        pendingIntent
                    )
    
    
        private fun createNotificationChannel() {
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val name = "Alarmclock Channel"
                val description = " Reminder Alarm manager"
                val importance = NotificationManager.IMPORTANCE_HIGH
                val notificationChannel = NotificationChannel(CHANNELID, name, importance)
                notificationChannel.description = description
                val notificationManager =
                    getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(notificationChannel)
            }
        }

Note - Must to do(go to your app setting and give notification permission on) 1.alarmManager.setRepeating here you can use your alarm type as your wish. 2.requestcode must be unique for each alarm. 3. you must take a alarm time and keep in calender.timeInMillis which is you expecting alarm time.

still problem comments below

Upvotes: 1

Related Questions