Tips for reducing battery drain for android services? - android

I wrote an app recently and, well I'm quite disappointed about how much battery the service consumes. I go to make a call yesterday to find my battery is at 9%; I check the android system statics for the battery and find that my app is responsible for 60% of the battery drainage
My question is, what can one do to reduce the battery usage on an app that runs and then sleeps for 60 seconds? The service is reading from a SQLite database; I could cache the data, but would that really account for that much battery usage? What are some standard ways to reduce battery drainage in a service?

You should look into using AlarmManager to schedule your app or service to be called when necessary. This has a big advantage over your current wake lock method, because even a partial wake lock will keep the CPU running. An AlarmManager alarm can wake the phone even from CPU sleep.
Basically, get rid of your existing wake lock and schedule an AlarmManager alarm—which can repeat once a minute, if that's what you need—to wake up the device, if necessary, and send you a message.
The AlarmManager itself will take out a wake lock while calling an onReceive() method to notify you of the alarm, and relinquish it when onReceive() finishes, letting the phone go back into deep sleep if it wants to.
Note that this means that if you want to do extended work—e.g. firing something off on a background thread—you'll probably want to take your own wake lock out in onReceive() and relinquish it when your work is done, otherwise the phone may go to sleep while you're in the middle of the work.
This is all pretty well-explained in the AlarmManager docs, but the best explanation I've seen is in Mark Murphy's The Busy Coder's Guide to Android Development; he also provides a library for exactly this pattern on Github. Definitely worth a look.

Related

Does need Broadcast receiver to WakeLock

I have two questions.
I want fire a Broadcast receiver using AlarmManager and show a notification in onReceive method. Should I use from WakeLoke for this?
What is different between setAlarmClock() and setExactAndAllowWhileIdle() ?
I use (as you wrote) the onReceive method to start a newWakeLock and it works fine for me.
The difference lies in the behavior in doze mode (Doze Mode: https://developer.android.com/training/monitoring-device-state/doze-standby).
I do not know your exact problem, but I worked very hard to develop an app which contains few timers and every timer should make a notification at the exact time even the screen is locked and the device is in the doze mode. My solution is to fire an Broadcast over an AlarmManager with the setExact(...) method.
Answer your question in reverse order
.2. setExactWhileIdle guarantees that if the system is not sleeping and not in doze, the alarm will go off within 1 minute of the given time. if the system is in doze mode, the alarm will go off within 15 minutes of the given time. In practice, if the system is not in doze mode or low on battery, the alarm will go off on time. On the other hand, setAlarmClock is the closest one can get to a guarentee that the system will deliver the alarm at a specific time; this does come at a relatively large drain on battery. So, if your goal is to implement highly time sensitive notifications such as an alarm clock, then use setAlarmClock. Otherwise try to avoid it.
.1. according to the documentation, upon an alarm being dispatched from setExactAndAllowWhildIdle or setAlarmClock:
the app will also be added to the system's temporary power exemption list for approximately 10 seconds to allow that application to acquire further wake locks in which to complete its work.
My suggestion is that if all you are doing is posting a notification, then a wake lock is not necessary. Otherwise, if you are doing longer running work, use a wake lock
Obligatory Disclaimer: battery drain is a real thing. please don't make an app that drains the battery. do everything in your power to design your app not to disturb the systems power optimization. All exact alarms and especially setAlarmClock disrupt the systems attempts to optimize battery. If its necessary, then its necessary. Otherwise, do not do it.

Battery Impact: Background Service+BroadcastReceiver VS Polling Every Minute with AlarmManager?

I'm writing an application which needs to detect when the screen turns on or off from the background (with the precision of about 1 minute). Ideally, I'd just statically register for Intent.ACTION_SCREEN_ON and Intent.ACTION_SCREEN_OFF, but unforuntately, that's not allowed.
This leaves me with two not-so-great---actually-pretty-horrible options (unless there's something I'm unaware of, which is likely):
Run a omnipresent Service + BroadcastReceiver which registers for the ACTION_SCREEN_ON and OFF intents OR
Use the AlarmManager to schedule some code to run every minute, and check if the display is on/off with isInteractive()
#1 isn't great because it can be killed, it wastes memory, it needs to be run onboot which doesn't work when installed on the SD card, etc.. the list goes on.
#2 isn't great because it's less precise and... let's face it- polling is almost never the right answer
But worst of all, they will both have a negative impact on battery life. This is actually the most important factor IMHO.
TL;DR
Which is the lesser of the two evils with respect to battery life impact?
I'm not an android developer (but it would be fun) but when reading the AlarmManager class overview, it says that it will periodically launch an application if it is not running already. This isn't polling as the code isn't running and not affecting performance or keep the processor awake (consuming energy). I'm sure the AlarmManager class itself isn't polling either.
You might also look at suspending your applications process instead and periodically waking it up. Launching a process is typically an expensive operation. Though suspending the application doesn't consume processor resources (and so affect power consumption) it does have a memory footprint.

Acquire wake lock, release it and acquire it again while the phone is sleeping

I think this is pretty much the standard case already described in other SO question but I still need a clarification on this matter:
So I have an Android app with an Actvity and a Service. The Activity is not of interest but the Service. The Service has to send some message to a remote server every minute. From what I understand, I need to use WakeLocks to keep the CPU running while allowing the screen to go off (so that I can fix the problem where the service stops when the screen is powered off). So far so good.
My question is: can I acquire the lock, send the message to the server, release the lock AND acquire it again after one minute so that during this one minute pause the CPU is sleeping, too. With the ultimate goal to save the battery. I fear the answer is "no" because once you let the CPU to sleep, you cannot wake it up unless from a lower level (OS and not app).
Best regards
The response is simple: no. What you can do in this case is set a PendingIntent and use the Android Alarm manager to be woken up every minute.
The alarm manager is the way to go - but you also need to delegate from the alarm receiver to a WakefulIntentService to do the work (as the receiver will ANR after 5 seconds). See PowerManager.PARTIAL_WAKE_LOCK android for links.

Should I use AlarmManager or Handler?

I'm writing an app that constantly polls the device's sensors and every so often should write down some statistics to a file. This could be as fast as once a second or as slow once a minute. Should I use Handler's postDelayed()method or just schedule it with the AlarmManager?
This should help you discriminate between Handler and AlarmManager.
[source]
Though it is agreed these mostly work for API 23. It's a new release.
If the app should work in standby then AlarmManager. If not then Handler.
AlarmManager will wake CPU therefore it will drain battery more, while Handler will not work on standby.
Decide your design based on the below key points:
AlarmManager:
The advantage with the AlarmManager is that it works even if the device is in deep sleep mode (CPU is off). When the alarm fires, it hits the BroadcastReceiver and in onReceive, it acquires the wake lock (if you have used WAKEUP types of alarms like RTC_WAKEUP or ELAPSED_TIME_WAKEUP). After finishing the onReceive() it releases the wake lock.
But most of the times it DID NOT WORK for me. So I have acquired my own wake locks in onReceive() and released them at the end to make sure I really get CPU.
The reason why it DID NOT WORK is that when multiple applications simultaneously use a resource (such as wake locks that prevent the system from suspending), the framework spreads CPU consumption across those applications, although not necessarily equally. So, if it is critical, it is always better to acquire wake locks and do the stuff.
Timers and Handlers:
Handler and Timers do not work in deep sleep mode meaning the task/runnable will not run as per the schedule when the device is asleep. They do not count the time in sleep which means that the delay given to execute task will be calculated only during active mode. So, actual delay will be delay-given + time-spent-in-deep-sleep.
I'd say that it depends on the polling interval. I guess it's quite low in your case (around a few secs), so you should go the Handler way, or by using the Timer class.
AlarmManger is a much higher level service and it involves a larger overhead to handle this use case. When an alarm triggers, you need to handle it with BroadcastReceivers. This means that every time you handle one of these alarm, you needs to register listeners for the sensors you're interested in, which is immensely inefficient imho.

android: service behaved differnat when not connected to pc

I believe it's because of some power saving option or whatever but I cant debug it since it only fails when it's on battery
I have a service that checks on a webpage every 60 seconds
I use an asyncTask in the service to do this
and I make it Thread.thisThread.sleep(60000); before checking
am I doing something wrong? could the sleep function cause the server to be stopped by android?
I have a service that checks on a webpage every 60 seconds I use an asyncTask in the service to do this and I make it Thread.thisThread.sleep(60000); before checking
Please don't do that.
First, make the period configurable, including a "don't do this, ever" option. Users really do not like it when developers write apps whose primary purpose appears to be to use up a ton of battery life. Keeping the device awake and polling a Web server every minute is going to use up a ton of battery life. It is behavior like this that is causing users to run to every task killer they can find.
Second, particularly for periods greater than a minute or so, please use AlarmManager and a [WakefulIntentService][1]. Schedule the AlarmManager to invoke your application at the user-chosen period (ideally via setInexactRepeating()). Have the WakefulIntentService poll your Web page. If you follow the documented WakefulIntentService recipe, the device will stay awake long enough for you to get your data, then will fall back asleep. Your service will not remain in memory all of the time. You get your functionality, and the user gets better device performance.

Categories

Resources