Android AlarmManager setReating and setInexactRepeating - android

I was ready through the documentation and i was having some questions about setReating and setInexactRepeating. I was reading some other posts, but i could't find an answere.
The documentation says for both:
Note: as of API 19, all repeating alarms are inexact.
Does is mean that both methods are exactly the same in api 19 and above? Also how inexact is inexact? And if there is any delay, what are the effects for the following alarm?
Thanking in advance.

As one can read at the end of the official documentation as of API 19 [and future versions] all calls to setRepeating() will delegate to setInexactRepeating() instead. So as of KitKat and upcoming versions both methods do the exact same thing.
The delay will not effect the following alarms refering to the official documentation.
Schedule a repeating alarm that has inexact trigger time requirements;
for example, an alarm that repeats every hour, but not necessarily at
the top of every hour. These alarms are more power-efficient than the
strict recurrences traditionally supplied by setRepeating(int, long,
long, PendingIntent), since the system can adjust alarms' delivery
times to cause them to fire simultaneously, avoiding waking the device
from sleep more than necessary.
Your alarm's first trigger will not be before the requested time, but
it might not occur for almost a full interval after that time. In
addition, while the overall period of the repeating alarm will be as
requested, the time between any two successive firings of the alarm
may vary. If your application demands very low jitter, use one-shot
alarms with an appropriate window instead; see setWindow(int, long,
long, PendingIntent) and setExact(int, long, PendingIntent).
As of API 19, all repeating alarms are inexact. Because this method
has been available since API 3, your application can safely call it
and be assured that it will get similar behavior on both current and
older versions of Android.

Related

How to use Android's Sensor Batching without AlarmManager

I want to use Androids sensor batching introduced in Android 4.4 to save some battery power. My testing device can store 184 sensor events in its fifo-queue. Using a sampling rate of 18 events/seconds I have to flush the sensor about every 10 seconds. The section on Sensor Batching in the 4.4 Documentation proposes:
Use that calculation to set wake alarms with AlarmManager that invoke your Service (which implements the SensorEventListener) to flush the sensor.
Since Android 5.1 the minimum wake-up-interval for the AlarmManager is 60 seconds (see here), so this won't work? Is there an alternative for waking up the device in shorter time periods or is even better (in terms of battery efficiency) to hold a wakelock constantly? I guess the 60-seconds-constraint will have its reasons.
The 60 second minimum only applies to repeating alarms. For one-off exact alarms, you can have much smaller delays. The documentation mentions this as well:
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above.
In practice, this means you'll need to schedule an exact alarm (using setExact), and when that alarm has fired, you'll need to take care of rescheduling it yourself.

Is there an accurate repeating-alarm system for Android?

Background
I'm currently developing an application for Android which revolves around an alarm that goes of on an user specified time. My intent for it is that it will be used for waking people up in the morning (and the following morning - aka repeating alarm). When the alarm goes of it will call an Activity that has a couple of options (such as snooze). I've got all of this working but I'm running in to a problem.
Problem
I'm using AlarmManager to handle my alarm needs. There is however something curious going on with the class (in my opinion). There are two adviced ways to handle the setting of the alarm time. Namely setInexactRepeating and setRepeating. The problem with these functions are:
setInexactRepeating is not very accurate. My tests have shown that this gets approximately activated at the specified time, which the documentation indicates, all be it rather vaguely;
the alarm will not fire before this time, but there may be a delay of almost an entire alarm interval before the first invocation of the alarm.
My tests show there is usually something of a 5 minute delay. On this answer the user has an average delay of approximately 12 minutes. This won't do, of course, for a system that is supposed to wake people up at their specified times.
setRepeating does trigger at the specified time. The docs specify however that as of API 19 that all repeating alarms are inexact. Which is exactly what I don't want.
As of API 19, all repeating alarms are inexact. Because this method has been available since API 3, your application can safely call it and be assured that it will get similar behavior on both current and older versions of Android.
There is a setExact method, but this is a bit too specific. Aside from that it does not give me the option to have a certain interval (for repeating the alarm daily). Edit: After trying to go with setExact I found that this would require me to move up to API 19 (currently on 15), which is something I would like to avoid.
Question
Am I using the wrong class for this system? To me it seems like it should be a legit usage, but reading through the docs has left me wondering. Is there perhaps another class which is better suited for this system?
You can separate before API 19 and after API 19. While setting alarm for the first time:
if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mondayIntent);
} else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY * 7, mondayIntent);
}
When you catch the alarm:
if (Build.VERSION.SDK_INT >= 19) {
rescheduleAlarm();
}
You must set the alarm with
setexact
again in rescheduleAlarm.
Hope this helps.

Background wifi scanning in Android

I'd started for about a month or two and I've to develop an Indoor Positioning System based on Wifi fingerprinting. I need an app that periodically scans wifi APs and send the result data to a Server.
So far I created an app that it's able to scan wifi APs and get the results when different connections are detected. I'm doing this in main activity using a broadcast receiver. The app is also able to send the data to the server.
What I want now is move this process to a periodic process in background, even when the smartphone is in sleep mode.
I have already read some topics about how to do it but none was clear. My question is what is the best way to do this? Using a Service/IntentService with a Timer/TimerTask?
Thanks.
Edit: Thanks!! AlarmManager and Services work fine!
I think an AlarmManager fits your needs, use setRepeating to set something to repeat every X time
Schedule a repeating alarm. Note: for timing operations (ticks,
timeouts, etc) it is easier and much more efficient to use Handler. If
there is already an alarm scheduled for the same IntentSender, it will
first be canceled.
Like set(int, long, PendingIntent), except you can also supply a
period at which the alarm will automatically repeat. This alarm
continues repeating until explicitly removed with
cancel(PendingIntent). If the stated trigger time is in the past, the
alarm will be triggered immediately, with an alarm count depending on
how far in the past the trigger time is relative to the repeat
interval.
If an alarm is delayed (by system sleep, for example, for non _WAKEUP
alarm types), a skipped repeat will be delivered as soon as possible.
After that, future alarms will be delivered according to the original
schedule; they do not drift over time. For example, if you have set a
recurring alarm for the top of every hour but the phone was asleep
from 7:45 until 8:45, an alarm will be sent as soon as the phone
awakens, then the next alarm will be sent at 9:00.
If your application wants to allow the delivery times to drift in
order to guarantee that at least a certain time interval always
elapses between alarms, then the approach to take is to use one-time
alarms, scheduling the next one yourself when handling each alarm
delivery.
Note: as of API 19, all repeating alarms are inexact. If your
application needs precise delivery times then it must use one-time
exact alarms, rescheduling each time as described above. Legacy
applications whose targetSdkVersion is earlier than API 19 will
continue to have all of their alarms, including repeating alarms,
treated as exact.
Parameters
type One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC,
or RTC_WAKEUP.
triggerAtMillis time in milliseconds that the alarm
should first go off, using the appropriate clock (depending on the
alarm type).
intervalMillis interval in milliseconds between
subsequent repeats of the alarm.
operation Action to perform when the
alarm goes off; typically comes from IntentSender.getBroadcast().
As the note says
Note: as of API 19, all repeating alarms are inexact. If your
application needs precise delivery times then it must use one-time
exact alarms, rescheduling each time as described above. Legacy
applications whose targetSdkVersion is earlier than API 19 will
continue to have all of their alarms, including repeating alarms,
treated as exact.
But i don't think you care much if it's not precise.
Or you can use setInexactRepeating
Schedule a repeating alarm that has inexact trigger time requirements;
for example, an alarm that repeats every hour, but not necessarily at
the top of every hour. These alarms are more power-efficient than the
strict recurrences traditionally supplied by setRepeating(int, long,
long, PendingIntent), since the system can adjust alarms' delivery
times to cause them to fire simultaneously, avoiding waking the device
from sleep more than necessary.
Your alarm's first trigger will not be before the requested time, but
it might not occur for almost a full interval after that time. In
addition, while the overall period of the repeating alarm will be as
requested, the time between any two successive firings of the alarm
may vary. If your application demands very low jitter, use one-shot
alarms with an appropriate window instead; see setWindow(int, long,
long, PendingIntent) and setExact(int, long, PendingIntent).
As of API 19, all repeating alarms are inexact. Because this method
has been available since API 3, your application can safely call it
and be assured that it will get similar behavior on both current and
older versions of Android.
Parameters
type One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC,
or RTC_WAKEUP.
triggerAtMillis time in milliseconds that the alarm
should first go off, using the appropriate clock (depending on the
alarm type). This is inexact: the alarm will not fire before this
time, but there may be a delay of almost an entire alarm interval
before the first invocation of the alarm.
intervalMillis interval in
milliseconds between subsequent repeats of the alarm.
Prior to API 19,
if this is one of INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR,
INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY then the alarm will
be phase-aligned with other alarms to reduce the number of wakeups.
Otherwise, the alarm will be set as though the application had called
setRepeating(int, long, long, PendingIntent). As of API 19, all
repeating alarms will be inexact and subject to batching with other
alarms regardless of their stated repeat interval. operation Action to
perform when the alarm goes off; typically comes from
IntentSender.getBroadcast().
While my answer aim is to say a general way to repeat an action every X time, as other noticed, you will need Wifi Lock, Wake lock and use RTC_WAKEUP as AlarmManager type.
RTC_WAKEUP:
Alarm time in System.currentTimeMillis() (wall clock time in UTC),
which will wake up the device when it goes off.
Move your code from Activity to Service. Then, start the service periodically using AlarmManager. Service does the scanning and stops self when it is done. Then it is started again when timer elapses.
EDIT: Also look at cpu lock and wifi lock.
EDIT2: Also when creating alarm, use RTC_WAKEUP constant so that your action is triggered even if the device is in sleep mode.

Difference between setRepeating and setInexactRepeating of AlarmManager

What are the parameters of the following:
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent);
And of the following:
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
What is the difference and also how are the two different in terms of functionality?
Both examples schedule a repeating alarm that will send the given alarmIntent. On both cases, the first time it is sent will be immediate (calendar.getTimeInMillis() returns the current time). On both cases, the device will be woken up when the alarm needs to be sent (as evident by AlarmManager.RTC_WAKEUP).
There are two differences between these calls. The simpler one is that the intent will be sent every fifteen minutes on the first call, and every day on the second call (as you can see in the third parameter). The more complicated difference is the function call itself: setRepeating will schedule the first alarm for exactly every fifteen minutes; setInexactRepeating will schedule the second alarm for approximately every 24 hours, meaning it might deviate from that interval - with the advantage of consuming less power.
Do notice that this has changed in API 19, where these two calls are synonymous. See this guide, and this API documentation.
Decide how precise your alarm needs to be
Choosing the alarm type is often the first step in creating an alarm. A further distinction is how precise you need your alarm to be.
For most apps, setInexactRepeating() is the right choice. When you use this method, Android synchronizes multiple inexact repeating alarms and fires them at the same time. This reduces the drain on the battery.
For the rare app that has rigid time requirements as example, the alarm needs to fire precisely at 4:00 p.m. everyday then use setRepeating().
Reference: Decide how precise your alarm needs to be
To augment previous answers, there are a number of other best practices to consider when using repeating alarms, particularly inexact alarms requested using setInexactRepeating().
Alarm Type
Non-WAKEUP alarms are better than WAKEUP alarms from a power management perspective. Using the former your alarm may fire late, but it will still fire either when the device is woken by the user, or when another wakeup alarm fires. Using WAKEUP alarms will wake the device out of sleep, consuming additional battery and potentially causing other inexact alarms to fire that have been delayed that could otherwise have been delayed longer (reducing the batching power-saving benefits that inexact alarms provide).
Prefer alarms using the ELAPSED timebase rather than the RTC timebase. The former are more likely to have a more random distribution across devices than RTC alarms, which reduces the risk of network congestion and on the server if the alarm is triggering some sort of poll. Phones running Gingerbread (or older) suffer from a bug whereby RTC inexact alarms have a tendency to align closely to the real-time clock, e.g. approximately 30s past each quarter of an hour. ELAPSED alarms don't suffer from this bug on these earlier platform versions. Even if your alarm doesn't trigger any network activity, remember that if it is a wakeup alarm it may trigger other alarm non-wakeup intents that may hit the network.
Timebase
Be careful to specify the requested start time in the correct time domain for the alarm type. Failure to do this can result in alarms being set in the past (they fire right away) if setting an RTC alarm with an ELAPSED timebase or far in the future if setting an ELAPSED alarm using the RTC timebase. You can check what alarms an app has scheduled using dumpsys alarm via the adb shell.
Interval
Specifying an inexact alarm interval of anything other than the interval constants defined in the AlarmManager API is redundant on SDK <19: they will be scheduled as exact not inexact alarms, losing all the power-saving benefits that inexact alarms provide.
Edit: here's further explanation of the bug relating to gingerbread and honeycomb 3.0 devices: https://code.google.com/p/android/issues/detail?id=31550
setRepeating is more accurate and setInexactRepeating is for saving battery but no accurate , setInexactRepeating is good for maintenance in background for example and setRepeating is necessary for example for alarm clock .
Use setInexactRepeating() is used when app is not seriously used to required for example wake up early in the morning . if Alarm wake up approximately that time there is no any life dangeous.
like medicine pills app where highly critical patient use that app to reminde nurse or doctor staff the is compulsory to use setRepeating().
When you use setInexactRepeating()
then Android synchronizes repeating alarms from multiple apps and fires them at the same time(once). This reduces the total number of times the system must wake the device.
thus reducing drain on the battery.
repeating alarms are inexact. Note that while setInexactRepeating() is an improvement over setRepeating() also
it can still overwhelm a server if every instance of an app hits the server around the same time. Therefore, for network requests, add some randomness to your alarms.

Why Alarm Manager only updates in 30 minutes?

I wanted to make a widget that updates every sec(more battery consumption) or min(less battery consumption).
I followed as in this thread
, but runs only in every 30mins.
I configured that, once onUpdate is run, it updates in 1mins and
onReceived is run in every 30mins.
Can anyone tell me what I am doing wrong?
From my experience AlarmManager doesn't work well (or at all) with intervals lower than 1 minute. Besides:
Note: The Alarm Manager is intended for cases where you want to have
your application code run at a specific time, even if your application
is not currently running. For normal timing operations (ticks,
timeouts, etc) it is easier and much more efficient to use Handler.
Moreover:
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS
will shift alarms in order to minimize wakeups and battery use. There
are new APIs to support applications which need strict delivery
guarantees; see setWindow(int, long, long, PendingIntent) and
setExact(int, long, PendingIntent). Applications whose
targetSdkVersion is earlier than API 19 will continue to see the
previous behavior in which all alarms are delivered exactly when
requested.
You are doing nothing wrong, the widget service indeed only updates every 30 minutes(minimum).
To make it update faster you need to use AlarmManager, or your own application that will call the service. Unlike soulreaver answer, the alarm manager does work with times less then 1 minute.

Categories

Resources