Search code examples
androidkotlinandroid-service

Android Alarm manager not working while appliction is killed from recent apps


I am stuck at Reminders in my application. The Reminders with Alarm Manager is working fine when my app is running or is in background (Recent Apps) but the main issue is that when i kill my app the alarm does not trigger. Should i implement any background Service for keeping my alarm alive even when the application is killed ? My Menifest Code :

<receiver android:name=".ui.home.reminders.AlarmReceiver"
        android:process=":remote"
        android:exported="true"
        android:enabled="true"/>

My Receiver Class :

class AlarmReceiver: BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
    p0?.showToast("received")
}

}

My Fragment for setting Alarm :

private val calendar: Calendar by lazy {
    Calendar.getInstance()
}

I am setting Time through TimePickerDialog:

val listener = TimePickerDialog.OnTimeSetListener { p0, p1, p2 ->
                    activity?.showToast(" $p1 $p2")
                    calendar.set(Calendar.HOUR_OF_DAY, p1)
                    calendar.set(Calendar.MINUTE, p2)
                    calendar.set(Calendar.SECOND, 0)
                }
                TimePickerDialog(
                    activity!!,
                    listener,
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                    false
                ).show()

On click of set Alarm Button:

val alarmManager =
                    Constants.context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                val pendingIntent = PendingIntent.getBroadcast(
                    Constants.context,
                    0,
                    Intent(
                        Constants.context,
                        AlarmReceiver::class.java
                    ),
                    0
                )
                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

I have seen various examples but none of them seems to be working for me. If i have to implement a background service or there is another way of implementing Reminder with notification then please suggest some example code snippet. Scenario : I want to show reminder with a notification ( Time / Date / Repetition- Daily/Monthly will also be decided by the user). Any help will be appericiated. Thanks in advance.


Solution

  • Okay, after so much struggling with the above issue I myself found the solution, I tried launching the background Service for the same but the system was shutting it down too after i was removing the app from the recent apps, THE MAIN CULPRIT WAS BATTERY OPTIMIZATION SETTINGS. After i removed the battery optimization setting from the settings, the alarm just worked fine as i wanted :) I am posting this answer so that it can help others and save their time... happy coding...