My app needs to execute a specific task every hour. It does not matter if app is runing, suspended, or even closed.
When app is running or suspended, I can do it by just scheduling an AlarmManager broadcastreceiver. But when the application is closed, I have to call “unregisterReceiver” to not leak an intent, and app will never be wake up (or something) to process the task.
Then, the question is: how to schedule an alarmmanager task that I don’t need to unregister, so it will be called even if my application is closed?
Use
AlarmManager.setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)for this. Set the type toAlarmManager.RTC_WAKEUPto make sure that the device is woken up if it is sleeping (if that is your requirement).Something like this:
You pass a PendingIntent to this method. You don’t need to worry about leaking Intents.
Remember to turn the alarm off by calling
AlarmManager.cancel()when you don’t need it anymore.Don’t register a Receiver in code for this. Just add an
<intent-filter>tag to the manifest entry for your BroadcastReceiver, like this: