It seems that the only way to time actions based on the actual elapsed time (as opposed to uptime, which stops when the device sleeps) is the AlarmManager.
Is there an an easy way to do "wallclock"-based delayed exectuion, for example through an open-source wrapper around AlarmManager?
For normal timing operations, you can use a handler, which is as easy as such a simple task should be:
- Implement the handler callback (no registration necessary)
- Instantiate a Handler
- Call sendEmptyMessageDelayed or similar functions
- To clean up all your set delays, just call
removeCallbacksAndMessages(null)
However, Handler only supports uptime-based delays, which sometimes are not sufficient (e.g. if you want to check the server for new messages every 15 minutes).
If you want those, it seems that you have to use the AlarmManager, which is not very comfortable:
- Define an action for your alarm
- Create a receiver (either by creating a dedicated receiver class and declaring it the manifest, or implementing the interface, registering the receiver using registerReciever, and unregistering it when done)
- Create an intent for your action
- Wrap said intent in a pending intent, and store the pending intent if you want to cancel the alarm
- Fetch an alarm manager (this requires a context)
- Set the alarm
- When you want to cancel the alarm, cancel it using the stored pendingIntent
- Should you decide to have multiple intents or intents with changing data, you will have to save them all to clean up the alarm manager afterwards
startForeground
) and collects/exchanges data, but does not hold a wake lock all the time. I want it to upload logs every X minutes. postDelayed would upload it every X minutes of uptime (i.e. if the device slept a lot, maybe once a day). I prefer using existing wrappers because they are usually tested quite a bit and cover things that are easily forgotten. By define an action, I meant a constant with an action name, not something in the manifest. Is there some kind of "catch-all" action that should be used instead? – Essequibo