How to use Android's Sensor Batching without AlarmManager - android

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.

Related

Efficiency of using AlarmManager to update App Widgets in Android

I have developed an App Widget that requires to be updated every 10 minutes. In Android documentation about App Widgets it is specified that if the widget needs to be updated more frequently than once per hour, it is recommended to use AlarmManager and set the alarm type to either RTC or ELAPSED_REALTIME so the alarm is only delivered when the device is awake.
I have implemented the AlarmManager and my widget is updating correctly every 10 minutes. After several testings, using both RTC and ELAPSED_REALTIME alarm types, I have seen that my widget is still getting updated after the device goes to sleep. I can see in LogCat that my widget is getting updated even after 30 minutes that the device went to sleep (30 minutes after the screen turns off).
My question is, if the alarm is still been delivered and my widget is updated every 10 minutes even after the device has gone to sleep how is using AlarmManager with RTC or ELAPSED_REALTIME as the documentation says more battery efficient than just setting 600,000 milliseconds for updatePeriodMillis property on my widget provider xml file?
A couple of things:
Both RTC and ELAPSE_REAL_TIME have WAKEUP and non WAKEUP versions, so if you do not want you widget updating when the phone is sleeping, you could chose the non WAKEUP version. If you set updatePeriodMillis, it is going to wake the device either way.
When you set your alarm using setInexactRepeating() instead of setRepeating(), Android will bundle multiple inexact alarms and fire them at the same time, which is more battery efficient. Also according to the doc:
As of API 19, all repeating alarms are inexact.
Another thing is that, according to the AppWidgetProviderInfo doc:
Updates requested with updatePeriodMillis will not be delivered more
than once every 30 minutes.
so it probably wouldn't be useful to you if you needed to update every 10 minutes.

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.

Android AlarmManager setReating and setInexactRepeating

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.

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