Reliable repeating background task on android - android

I'm trying to run a background task which runs every minute or so for an android application but I am struggling to ensure that the task actually runs every minute. I've tried a variety of approaches from using SystemClock.sleep() to the AlarmManager (both repeating alarm and a fixed alarm) but it seems that unless the device is charging any kind of repeating system has a variable repeat rate once the device is unplugged. Is there any way to run a stable consistently repeating service?

Have you implemented Timer? It works very well for what I use it for, but then again I haven't worried about the precision at all. For all I know it may be varying a bit but I doubt it. It seems pretty consistent to me.
Edit: I am not liable for your responsible or irresponsible use of this facility ;)

If you need to have a service that runs every minute, on the minute, you have two options:
Use AlarmManager.setRepeating(RTC_WAKEUP, ...). In this case, the phone will sleep, but the RTC inside the phone will wake it up every minute to handle the repeating event. This will work, but will not be terribly exact as a lot of things are happening after the phone wakes up so your code might not get execution time right away.
Obtain a WakeLock from PowerManager and use whatever you want to time your code (Timer, Handler, etc.). This forces the phone to never sleep, which means that it is most likely free to run your code almost exactly when you request.
Both approaches will definitely drain the battery of the phone fast. Normally, the phone can sleep for 4 or even 9 minutes between wakes, so waking up once per minute is a big change from that.

Related

Make an application that starts by itself and executes code in the background

I am developing a flutter application, however I would like a service to be able to run constantly without stopping in order to make an api request every 15 minutes and then send a notification to the user (Android /IOS). I would also like the service to start automatically with the smartphone. I've been stuck on this for more than a week now and I've been browsing the forums looking for a solution but I can't find what I'm looking for. Thank you in advance for any help
You don't do it like that on Android. You cannot count on an application not being killed in the background. Instead, you use JobScheduler or WorkManager to set an alarm and wake you up every so often to perform whatever job you need. These methods can also ensure you're scheduled at startup of the phone.
Also, 15 minutes may or may not happen- Doze mode may cause your app to be delayed and make requests less frequently than that if the phone goes to sleep (although 15 minutes is fairly safe, plus or minus a few).

Scheduling Repeating Events -- Handler.PostDelayed and Doze

Context
I'm working on a screen filter app (like f.lux) for Android. I'm currently working the feature to gradually fade in the filter as the sun sets. The state does not matter when the screen is off, but when the screen is on, it's important that the fade progress be correct (or immediately updated).
Technical requirements
I want to fire a series of intents at semi-regular intervals.
When the screen is off, they can be ignored / discarded, except:
when the screen turns on, the most recent intent must be fired immediately.
I do not want to drain the battery unnecessarily.
Obvious solutions and why they don't work
I could use AlarmManager.setInexactRepeating, which is supposedly the most energy-efficient of the alarms, except:
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.
I think this implies that the first trigger will necessarily happen within the first interval, meaning the device will be woken, causing unnecessary battery drain.
I could use AlarmManager.set to schedule the first alarm. When it goes off, I could update the screen, then schedule the next alarm. This would work, but would wake up older devices (without Doze) on each alarm, instead of waiting until the screen turns on. It's also using AlarmManger as a timer, which the documentation explicitly recommends against:
For timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
Okay, so,
I could set a single alarm to starts up a Handler, which would update the UI periodically. But wait: this relies on postDelayed, which says (emphasis mine):
Time spent in deep sleep will add an additional delay to execution.
I think that means, when the device wakes up from sleep, the next update might not happens for a whole interval. Am I reading this right? Forcing the user to wait a minute or two before the next update is a deal-breaker.
CountDownTimer and ValueAnimator both use this method in their implementations, so if my interpretation of Handler is right, they're both out.
I could use a handler-based method and also receive events when the screen is turned off, at which point I'd cancel the existing animation, then start a new one. This looks to be the best solution, but it seems like there should be a simpler way to do it.
Conclusion
There are a ton of other SO questions on this topic. Everyone and their mother recommends using a Handler, but there's absolutely no information about how it behaves when the device goes to sleep, aside from the quote above. It's really weird that (apparently) nobody else has run into this issue -- am I doing something really unusual, or missing something basic?
Can anybody provide insight about how Handler.postDelayed really behaves when the device goes to sleep, and recommend what I should do in this particular instance?

Android: Scheduling applications for continued execution

I have gone through various discussion threads and tried multiple iterations to have my application scheduled to repeatedly run at fixed intervals. I have been successful too, but starting the thread to get understanding how things work.
I had tried the implementation with ScheduledExecutorService as well as TimerTask and both did not trigger my task at right intervals. But found success with AlarmManager.
Please lead me in right direction to understand why the timing did not work well with ScheduledExecutorService and TimerTask.
The app is required to perform a task on a regular interval. Say, my task takes around 5 minutes to complete, I would like to keep it scheduled so that it runs once in every 30 minutes. When I built the application with ScheduledExecutorService or TimerTask, I found that it does not trigger the task at 30 minutes, but it triggered at 1 hour or even more. So far, with Alarm Manager, it seems to be working fine getting triggered at around 30 minutes(slight variation is still found, but better than the other two).
When I built the application with ScheduledExecutorService or TimerTask, I found that it does not trigger the task at 30 minutes, but it triggered at 1 hour or even more.
More importantly, it will not trigger at all once your process is terminated, which can happen at any point and, from the user's standpoint, should happen quickly, to free up RAM for other apps.
Your trigger delays are probably due to the device falling asleep. Your solution would not only tie up the user's RAM, but also would require you to prevent the device from falling asleep, which is horrible for battery life.
AlarmManager is a far more appropriate solution, as it does not require you to keep a service running or otherwise have a process around. Just be sure to use WakefulBroadcastReceiver as the way you respond to your _WAKEUP event, as the device will want to fall back asleep.

Android Timer/Handler/Thread.sleep() with screen off don't work correctly

I'm developing an application which needs to run small chunks of code frequently (once every two seconds, for example). I've tried to make it work using the simple Thread.sleep() (or android.os.SystemClock.sleep() to avoid interrupts, and finally I've tried with Timer and Handler), but the result is that the time that the program sleeps is random (or it simply doesn't run if I use Timer or Handler as the system discards they messages when the screen is off), as the system goes to a deep sleep mode during screen off.
For example the code works right if I have the phone plugged into the charger, or is playing music (that avoids the deep sleep mode), but when the phone isn't doing anything the time can grow from two seconds sleep up to minutes of sleep.
From https://groups.google.com/forum/#!topic/android-developers/Eqwp8Uiy2f0 seems that the only alternative is to use the AlarmManager to force the wake, but that way will probably cause too much battery drain.
Is there any alternative?
If not, is there any way to detect when the system goes into the deep sleep mode?
It is too late but may be useful for somebody else.
Yes, Timers does not work in deep sleep mode.I think there is no other better way than AlarmManager to run something periodically in deep sleep mode.
Also, as your frequency is just 2 seconds I think you may have to go for exact alamrs (setExact() ) as the regular alarm may not serve you better if your requirement is critical in time. And sometimes even setExact might not capture the wake lock I observed. So you have to acquire your own (PARTIAL_..) wake lock and, do stuff and release the lock.
But is it must that you have to run evvery 2 seconds ?
If not continue using Timers which will continue working automatically after the device wake up.
Take a look at Should I use AlarmManager or Handler?

Run a service in the background forever..? Android

I am doing a Battery Consuming research on the Android phone. I want to run a Battery Check every 10 min till the battery totally dies. I have been having problems to make it work.
At my first try, I use a timer in a service class, and schedule the battery check every 10 mins. But soon I found that the service got paused when the screen goes off.
Then I try to use AlarmService, I use a alarm call to wake my service every 10 mins and to check the battery level and save the data to a file on the sdcard. It works with the screen off. However, I only got data of 9 hours...it seems that the AlarmService stop at some point after several hours. I don't know why it is like this, has the system killed it for memory issues?
So my question is, has anyone written some service to run (like forever) in the background before? How do you do it and I'd appreciate very much for a sample code?
I am currently reading some posts saying that there's a partial wake lock I can use to keep the service alive.. is this the correct way to do it?
Thanks a lot and I hope I can get some useful answers here.
At my first try, I use a timer in a
service class, and schedule the
battery check every 10 mins. But soon
I found that the service got paused
when the screen goes off.
You probably did not hold a WakeLock, so the device fell asleep.
it seems that the AlarmService stop at
some point after several hours
I rather doubt it.
So my question is, has anyone written
some service to run (like forever) in
the background before?
It is not possible to create a service that will run forever. It should be possible to create a scheduled task via AlarmManager that will be invoked "forever".
I am currently reading some posts
saying that there's a partial wake
lock I can use to keep the service
alive.. is this the correct way to do
it?
I'm not sure what "it" is. But, if you want to keep the device awake -- whether for your first approach or just while you are doing work triggered by an AlarmManager -- you need to hold a WakeLock.
Here is a project that does almost exactly what you describe for the AlarmManager, minus checking the battery level, but using a WakefulIntentService to ensure the device stays awake. If you cannot get this code to run until the battery shuts down, join the cw-android Google Group and report your findings, and I'll take a look at it.
http://github.com/commonsguy/cw-advandroid/tree/master/SystemServices/Alarm/

Categories

Resources