Search code examples
androidbroadcastreceiveralarmmanager

How to manage alarmManager when an app is killed (Android)


I have got an alarm that hit every 2 minutes (when the phone is not sleeping) and update a widget, it works good, but when the app is killed there isn't any alarm remaining so it doesn't work anymore. What can I do to manage this kill and keep my alarm working after that.

If you need more information, tell me. If you don't understand all, tell me too.

Thank's for answers!


Solution

  • Configure your alarm to be initialized on system boot complete intent (android.intent.action.BOOT_COMPLETED) or similar intent that is dependable.

    Create a broadcast receiver that consumes the following intent

    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
    {
        AlarmManager aMgr = (AlarmManager) cx.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getBroadcast(cx, 0, new Intent(cx, ScheduleReceiver.class), 0);
        aMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, Thoth.Settings.ALARM_TRIGGER_AT_TIME, Thoth.Settings.ALARM_INTERVAL, pi);
    }
    

    ScheduleReceiver is the class that starts a service that updates the widget.