Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 437
Piotr Müller Avatar asked Jun 17 '14 12:06

Piotr Müller


1 Answers

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).

like image 132
CommonsWare Avatar answered Sep 22 '22 17:09

CommonsWare