How to debug an AlarmManager-activated service - android

I am implementing a widget that checks on-line train departure times between every minute and every hour, depending on the time of day.
Calling the service with
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() - 10000, 60000, pendingIntent)
works fine, but for debugging I would like to reduce the interval to about 10 seconds which cannot be done because of the 1-minute limit in more recent versions of Android. Clearly, I don't care about battery life in the emulator.
As far as I understand, using an Hander/Timer is not an option, because it required the task to be in the foreground. Is a visible widget "in the forground"?
What is the recommended practice in this case?

you actually have to tasks
configure the alarmmanager to add/remove trigger events via intents
interprete the events with intents in a service
If you seperate both you can easily create a very simple gui/activity that does the same as the alarmmanager would do when being triggerd and that you can debug:
* onSendButtonClick: create and send pendingIntent
for the alarmmanager-handling i would implement logging into a text file each time alarmmanager is added/removed/triggered.
Be prepared that newer android versions may postpone alarmmanager events to save energy until the device is already active and that intervals less than 15 minutes may not work.
you may also need on_boot_complete to reconfigure alarmmanager after device-shutdown

Related

Periodic background work using AlarmManager

Is it possible to use AlarmManager to set periodic works? For instance, could I set an alarm for say every 15min for 24 hours? Or put an alarm that schedules another alarm to awaken the app with some delay? Is there any reason for it to no work as expected?
I've tried using periodic workers with WorkManager but the workers consistently failed to wake up after several hours (I've used 15min periods).

Repeating Alarm in Android

What is the best way to implement repeating alarm in my android application? Every user selects a specific time and I want to notify them when this time approaches on daily bases. I have come across this, but I am wondering whether this is the best way?
The alarm manager should meet your needs. There is no better way except for maybe having a server ping your client.
Since android really doesn't like things that repeat on a predictable interval, and since recent versions don't let you repeat on an exact fixed interval anyway, you'll need to schedule the alarm at the time you want, and then when that alarm fires, schedule a new one for the next day at the time you want.
use
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarm_time,
intervel, pendingIntent);
in your activity

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.

How can I minimize a wakeup alarm's running time overhead?

My code logic is like
Set a repeated wakeup alarm.
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pIntent);
during onReceive() of the receiver. do something very quick, may just need 100ms at most.
The operation will repeat every minute and it will be battery burden somehow ( since we want to the background service run as long as possible).
Now, according to our power monitoring tool, even if we do just some logging in onReceive(). It still takes around 1.5 seconds.
I have done some research and I conjecture it may related to the waiting in
alarm_suspend of android enhanced linux kernel.
However, I am not sure about it. Looks like there is no reason android need to keep the alarm running time that long, so I am asking if someone has some good experience on setting up the alarm and make the overhead as small as possible?
Thanks.

Android AlarmManager Rescheduling Logic

I have an app which allows users to schedule alarms to sound at certain times, repeating at intervals of their choosing. I am using JSON to persist the alarm details, using SharedPreferences as storage.
I am using AlarmManager to schedule when my app should be notified that an alarm should sound to notify the user. I am currently using the setRepeating() method of AlarmManager, supplying the interval provided by the user. This works well, and in theory the app would never need to update the JSon which stores the next alarm time, as AlarmManager will just reschedule the next alarm time using the interval.
However, my thinking is that when the device is rebooted, I will need to supply a up to date alarm time to AlarmManager to avoid AlarmManager thinking an alarm has been missed as this is not necessarily the case.
So, what's the best way to do this?
update the JSon next alarm time when the alarm is sounded, even though this may not be necessary (setRepeating() handles this as long as there is no reboot)?
register for and listen for shutdown broadcasts and update JSon then (this raises questions - just how long will the app get to calculate and write alarm details to storage given that the phone is shutting down)?
don't update the JSon but add logic to the object which is woken by the AlarmManager to decide if the alarm just broadcast is valid and the user should be alerted?
I'm sure any of the above will work, but I can't decide which is the nicest way to do it.
This seems mostly a matter of choice. The problem you note parallels a general problem seen in Linux laptops and solved by anachrond. In my opinion, I would simply update the time and store it in SharedPreferences every time the event is received. Trying to listen for when the system shuts down might not be entirely reliable (what happens when your users -- probably drunk college students -- drop their device and the battery flies out?). Instead, I believe the best thing to do in this scenario would be to -- each time the alarm fires -- recalculate the time to send the next one, store it somewhere, and upon boot schedule appropriately.

Categories

Resources