1

I am making an alarm app using AlarmManager. The problem is, if I kill the app on the task, AlarmManager doesn't work. How do I fix it?

MainAtivity.kt

fun scheduleAlarm(context: Context) {
    val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

    val i = Intent(context, WorkBroadcast::class.java)

    val calendar: Calendar = Calendar.getInstance()
    calendar.timeInMillis = System.currentTimeMillis()
    calendar.set(Calendar.HOUR_OF_DAY, hour)
    calendar.set(Calendar.MINUTE, minute)
    calendar.set(Calendar.SECOND, 0)
    calendar.set(Calendar.MILLISECOND, 0)
    
    i.putExtra("trigger", calendar.timeInMillis)

    val p = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, p)
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, p)
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, p)
    }
}

WorkBroadcast.kt

class WorkBroadcast : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        
        val sdf = SimpleDateFormat("hh:mm:ss", Locale.getDefault())
        val trigger = intent.getLongExtra("trigger", 0)
        val notification = WorkNotification.sendNotification(context, sdf.format(trigger))

        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(0, notification)
    }
}

AndroidManifest.xml

    <receiver
        android:name=".WorkBroadcast"
        android:enabled="true" >
    </receiver>

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
H.JiMan
  • 269
  • 1
  • 2
  • 10
  • Can you please share the snippet to look how `scheduleAlarm` is invoked or getting called from? – Tom Taylor Oct 18 '20 at 16:34
  • When a button is simply pressed in ```MainActivity```, scheduleAlarm() is implemented through setOnClickListener. Actually, I don't need the context that I receive as a small argument value. – H.JiMan Oct 19 '20 at 05:14
  • Hmm may be you are trying to pass activity context - because of which it could have been garbage collected at end of activity lifecycle. Consider passing application context as param for that method – Tom Taylor Oct 19 '20 at 06:02
  • Thank you for the reply. I changed all the ```context``` or ```this``` part in my code to ```applicationContext``` or ```context.applicationContext```. But equally if I kill the app on the task it still doesn't work... – H.JiMan Oct 19 '20 at 06:43

0 Answers0