0

My Alarm manager is working when I set the Alarm, after 2 or 3 minutes. But when I set Alarm for a day after or after 30 minutes it doesn't rings.

Main Activity :

    addTaskIMBTN.setOnClickListener {

        val dialog: AlertDialog.Builder = AlertDialog.Builder(this)
        val view: View = layoutInflater.inflate(R.layout.dialog_task, null)

        //time picker and date picker
        val timepicker: Button = view.findViewById(R.id.timeSelector)
        val datePicker: Button = view.findViewById(R.id.dateSelector)
        val deadlineTXT: TextView = view.findViewById(R.id.dateTimeShower)
        val deadtimeTXT: TextView = view.findViewById(R.id.timeShower)

        todoName = view.findViewById(R.id.taskET2)

        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)

        timepicker.setOnClickListener {
            timePickerDialog =
                TimePickerDialog(
                    this,
                    { _, p1, p2 ->
                        c.set(Calendar.HOUR_OF_DAY, p1)
                        c.set(Calendar.MINUTE, p2)
                        c.set(Calendar.SECOND, 0)
                        deadtimeTXT.text = "Time : $p1:$p2"


                    }, hour, minute, true
                )
            timePickerDialog.show()
        }
        val mYear = c.get(Calendar.YEAR)
        val mMonth = c.get(Calendar.MONTH)
        val mDay = c.get(Calendar.DAY_OF_MONTH)

        datePicker.setOnClickListener {
            datePickerDialog = DatePickerDialog(
                this,
                { _: DatePicker, year, monthOfYear, dayOfMonth ->
                    deadlineTXT.text =
                        "Date : " + dayOfMonth.toString() + "-" + (monthOfYear + 1) + "-" + year
                    c.set(Calendar.YEAR, year)
                    c.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    c.set(Calendar.MONTH, monthOfYear)
                },
                mYear,
                mMonth,
                mDay
            )
            datePickerDialog.show()
        }

        //positive button function
        dialog.setView(view)
        dialog.setTitle("Add a Task")
        dialog.setPositiveButton("Add") { _: DialogInterface, _: Int ->
            if (todoName.toString().isEmpty() || todoName.text.isEmpty()) {
                Toast.makeText(
                    applicationContext,
                    "Please add a name for the task",
                    Toast.LENGTH_LONG
                ).show()
            } else {
                Log.i("today's time", c.time.toString())

                val simpleDateFormat = SimpleDateFormat("d MMM 'at' HH:mm")
                date = c.time
                val string = simpleDateFormat.format(date)
                val newInt : Int = c.timeInMillis.toInt()

                val intent : Intent = Intent(this@TasksActivity, ReminderBroadcast::class.java )
                val pendingIntent = PendingIntent.getBroadcast(this@TasksActivity, newInt, intent, PendingIntent.FLAG_UPDATE_CURRENT)

                val alarmManager : AlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.timeInMillis, pendingIntent)

                tdItem.itemName = todoName.text.toString()
                tdItem.isCreatedAt = string
                tdItem.toDoId = todoID
                tdItem.isCompleted = false
                dbHandler.addTasks(tdItem)
                refreshList()
            }
        }
        dialog.setNegativeButton("Cancel") { _: DialogInterface, _: Int ->

        }
        dialog.show()
    }

    backBTN.setOnClickListener {
        finish()
    }
}

Notification Channel :

fun notificationChannel(){
    val uri  = Uri.parse("android.resource://" + this.packageName + "/" + R.raw.checked_it)

    val audioAttributes = AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build()

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        val name : CharSequence = "NotifyMeForDeadline";
        val description : String = "Channel for Deadline Reminder"
        val importance = NotificationManager.IMPORTANCE_HIGH
        val nc : NotificationChannel = NotificationChannel("notifyDeadline", name, importance)
        nc.setSound(uri, audioAttributes)
        nc.description = description

        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(nc)
    }
}

Broadcast Reciever :

override fun onReceive(p0: Context, p1: Intent) {
    p0.startActivity(p1)
    val intent : Intent = Intent(p0, TasksActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(p0, 0, intent, PendingIntent.FLAG_ONE_SHOT)
    val uri  = Uri.parse(Uri.parse("android.resource://" + p0.packageName + "/" + R.raw.checked_it)
        .toString())
    Toast.makeText(p0, "Recieved", Toast.LENGTH_LONG).show()
    val builder : NotificationCompat.Builder = NotificationCompat.Builder(p0, "notifyDeadline")
        .setSmallIcon(R.drawable.ic_baseline_alarm_24)
        .setContentTitle("Reminder from Checked-It")
        .setContentText("Hey, are you working on your tasks or just procrastinating?")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setSound(uri)
        .setContentIntent(pendingIntent)

    val notificationManagerCompat = NotificationManagerCompat.from(p0)
    notificationManagerCompat.notify((((Date().getTime() / 1000L) % Integer.MAX_VALUE).toInt()), builder.build())

}

I can find the solution for this so please help me out....I'll be pleased to listen your answer. Thank You!!

And Notification also doesn't show up when after scheduling the task I open the app again.

1 Answers1

0

Here is a working sample of the Alarm Manager. This example works consistently for as long as you need it to.

How to use Android AlarmManager in Fragment in Kotlin?

Since all alarms are cancelled on reboot. You will also need to handle Device Reboot with Broadcast receivers. You can find more information on the internet.

In addition to that, here is a working sample of Max Priority Notifications:

private fun sendInternetDaysLeftNotification(context: Context) {
        // This is used for opening application when the notification is clicked
        val intent: Intent = Intent(context, ProfileActivity::class.java)
            .putExtra(INTENT_EXTRA_INTERNET_DAYS_LEFT, contentText)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.action = INTENT_ACTION_INTERNET_DAYS_LEFT_DIALOG
        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )

        val channelId: String = context.resources.getString(R.string.internetDaysLeftNotificationsChannelId)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setPriority(NotificationCompat.PRIORITY_MAX)

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, DEFAULT_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(Random.nextInt(0, 100), notificationBuilder.build())
    }
Vitaliy-T
  • 733
  • 6
  • 23
  • can you please explain me what a max priority notification do? I'm new to android –  Oct 13 '20 at 03:41
  • @SiddharthaSrivastava Since here Notifications are created based on device's API level, you will need to check 2 pieces of docs, here is the one that is used for API 25 and below: https://developer.android.com/reference/android/app/Notification#PRIORITY_MAX and here is for everything newer than API 26 https://developer.android.com/reference/android/app/NotificationManager#IMPORTANCE_HIGH – Vitaliy-T Oct 13 '20 at 05:50
  • Ok bro, I'll do that –  Oct 13 '20 at 08:30
  • and one more thing, the alarm also doesn't rings when I first schedule the alarm and then close the app.........and then again start the app to check my tasks. –  Oct 13 '20 at 08:37
  • I hope you got it –  Oct 13 '20 at 08:37
  • @SiddharthaSrivastava So, the app doesn't right when you close the app. It only rings when you have the app open? – Vitaliy-T Oct 13 '20 at 08:38
  • No, it rings even when the app is closed. –  Oct 14 '20 at 09:03
  • @SiddharthaSrivastava ok, well, that’s exactly how it’s supposed to work though – Vitaliy-T Oct 14 '20 at 09:04
  • And still the the problem is not solved I scheduled the alarm for the next day and it doesn't worked out. –  Oct 14 '20 at 09:04
  • Some of the experts said that android kills the process if it's running for a long time and is not useful to the system. Is that true? –  Oct 14 '20 at 09:06
  • @SiddharthaSrivastava I am not really sure about that, but realistically, this is not a background process since it’s not constantly running. It’s simply an alarm that is scheduled to run once at a specific time – Vitaliy-T Oct 14 '20 at 09:07
  • Then why its not working bro............I've tried today but it doesn't work on long term tasks –  Oct 15 '20 at 16:43
  • do I also have to set autoCancel in broadcast reciever –  Oct 15 '20 at 16:45
  • @SiddharthaSrivastava Well, clearly you're doing something wrong then. I have given you a good chunk of information on how you can achieve what you need. Rest is up to you – Vitaliy-T Oct 15 '20 at 16:46
  • Do I also have to add ""intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)"" this? –  Oct 15 '20 at 16:48
  • Yeah no doubt you've provided me a good info about what I need, but still you're experienced than me –  Oct 15 '20 at 16:50
  • `intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)` is not necessary for you to add and only depends on your need. – Vitaliy-T Oct 15 '20 at 16:51
  • Thank You, if you still find something to help me out in this code please tell me. –  Oct 15 '20 at 16:53