Is there any way to keep AlarmManager in android even if task dies?

39 views Asked by At

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>
0

There are 0 answers