How to use Android AlarmManager with small intervals like 1 minute?

Piotr Müller picture Piotr Müller · Jun 17, 2014 · Viewed 13.3k times · Source

I want to make some external service monitor and be notified on problems as fast as possible.

I tried to set up AlarmManager with 1-2 minutes interval, but it looks like it fires randomly every several minutes.

Of course, I want to be safe from killing my background task by android, which would stop monitoring if I just use Service.

Is it possible to use AlarmManager in small, accurate intervals?

Which approaches are used in applications like Facebook, Gmail to notify about new messages?

Would it be better to make Service with startForeground and partial WakeLock?

Answer

CommonsWare picture CommonsWare · Jun 17, 2014

I tried to set up AlarmManager with 1-2 minutes interval, but it looks like it fires randomly every several minutes.

Since you decided not to show how you "set up AlarmManager with 1-2 minutes interval", it will be difficult for anyone to help you. Please read the documentation for AlarmManager and note the default-inexact behavior new to Android 4.4.

I want to be safe from killing my background task by android, which would stop monitoring if I just use Service.

AlarmManager does not solve all problems in this regard. For example, if the user elects to force-stop your app (e.g., via Settings), your alarms are removed.

Is it possible to use AlarmManager in small, accurate intervals?

Use setRepeating() on Android 1.0-4.3 and setExact() on Android 4.4+. With setExact(), as part of processing one alarm event, you will need to schedule the next alarm event.

Would it be better to make Service with startForeground and partial WakeLock?

Only if your device is always plugged into power (e.g., industrial process monitor).