I saw a great speech from Commonsware's Mark about multithreading and using wakeful services yesterday at AppsWorld London. He recommends using WakefulIntentService or WakeFulBroadcastReceiver in some situations to ensure your app will be able to continue some long processing and prevent the device to go to sleep.
I have an app that does some background processing regularly when the device screen is off. I use AlarmManager to have it get the stuff done regularly.
Since I have a large user base (200.000 active users), I get to see all kind of weird cases when users send me some logfile. Among others I could see that on some devices after the alarm will be triggered, the app starts doing his job and then suddenly just doesn't do anything for many seconds, or even minutes (no entry in the logfile for a while). I assume this is because the phone goes to sleep.
What bugs me is that this happens only on some devices, for instance it would happen a lot on Samsung SGS2+, but not on SGS2, SGS3 or SGS4.
So what I'm wondering is: what is the policy to decide when to put the phone to sleep? Is it Android deciding or is it lower at the Linux level?
How much tweaking from the manufacturer is allowed? Shouldn't the sleep policy be part of the Android Compatibility definition?
Extra question: Are there some levels of being asleep, like several levels of CPU speed, or is it just boolean sleeping / not sleeping?
what is the policy to decide when to put the phone to sleep?
Generally speaking, if nothing is holding a WakeLock, the device is free to go into "opportunistic suspend" mode, where the CPU stops executing instructions.
Is it Android deciding or is it lower at the Linux level?
The Linux kernel -- via Android extensions originally, now rolled into the stock kernel -- handles opportunistic suspend. Userland apps, like SDK apps, can use WakeLock to block opportunistic suspend..
In terms of how the kernel is configured in terms of opportunistic suspend, I have no idea.
Shouldn't the sleep policy be part of the Android Compatibility definition?
Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.
Are there some levels of being asleep, like several levels of CPU speed, or is it just boolean sleeping / not sleeping?
From the standpoint of an Android SDK app, and with respect to the CPU, right now, it is "boolean sleeping/not sleeping", as compared to Intel SpeedStep-style CPU frequency changes. Certain multi-core CPUs may turn on and off cores to save power, but this is generally independent from opportunistic suspend.
Related
I read many questions here about doze mode like Android doze mode, Android N Doze mode - how to keep background download and processing?, Wakelock and doze mode and many others. But in many replies, opinions is different. I can't test it by myself (emulator does not support my processor, and my only test device is android 5.1). I would like to know the next situation. I have an activity, which controls the media player. On devices with android 6.0 and higher it wouldn't work as expected cause of doze mode. As many solutions says to prevent doze mode it should start a service in separate process in foreground and control media player from there. The question is: if i start foreground service with partial wake lock in separate process, which would do nothing except showing notification, and leave controls to media player in my activity, should it prevent the doze mode? Or maybe there any other ways except keep the screen on from window manager?
According to this SO question and answer:
In this post's comments on Sep 17 Dianne Hackborn writes:
Apps that have been running foreground services (with the associated notification) are not restricted by doze.
- Source (sec_aw)
It looks like using a foreground service prevents the app from being killed by Doze.
Please note though, that some vendors (I know of Samsung, but there are probably others) create their own RAM conservation/battery saving tools. These may exhibit patterns completely different from Doze, and there's usually a bunch of other hoops to jump through. You are not guaranteed to get the same behavior on these devices either - they may be more or less aggressive, and the more aggressive ones tend to be worse for keeping services or whatever alive.
There's also no universal way to deal with these, but someone has made an entire website dedicated to showing what vendors are problematic, as well as potential workarounds. Note that the majority of the problematic vendors only yield end-user solutions, which means you (the developer) have no way to fix it without the user doing something.
While this is unfortunate, that's pretty much what happens when companies implement their own versions of Android. Also, from my own experience (primarily as a user rather than a dev) on a Samsung phone, the settings aren't always respected and still causes annoying behavior.
Anyway, as long as Doze is present, foreground services should be fine. On other vendors, however, all bets are off and you're at the mercy of the vendor's implementation of some type of optimization system. On certain exposed operating systems (again, see the website linked earlier), you also have no choice but to ask the user to fix certain settings to keep stuff alive.
I am writing an app to evaluate the feasibility of a Bluetooth P2P network on Android.
I noticed that on a Galaxy Nexus, it uses very little battery, while on a Nexus S, it drains the battery very quickly. This is directly caused by high CPU load due to Bluetooth.
Now, I would like to collect information about how much battery drain my app causes on the devices it is installed upon. Simply logging time vs. battery level is useless since I don't know when the device is in use, and even if I logged that, I would not know if the user is playing 3D games while Torrenting over WiFi or reading an eBook on a dimmed screen.
To make the problem worse, not all battery usage caused by my app is attributed to it in the battery screen - some is listed as "Bluetooth", for example (again, device-dependent).
Is there any easy, privacy-preserving way to get useful information on non-rooted devices? The devices are not under my control. I cannot simply go look in the menu, I cannot use ADB.
The Android API doesn't support this currently. The only available documentation is the one describing how to use BatteryManager's broadcasts, which only supply the overall battery level and no per-application details.
I suppose that even if there are undocumented ways to emulate what the System Settings battery manager shows, they would require rooting.
AFAIK there is no way to do this. The closest you can get to doing this is to hook up the device to a monitoring tool like little eye labs which does draw the battery consumed by your app over time on a graph. It also supports marking key events in the app's lifetime like turning on WIFI / bluetooth etc.
There is no support for doing this remotely, but you can get the data on your own test devices.
This approach is quite crude, but it may help. You can use the existing BatteryManager broadcasts to track changes to the overall battery level while your app is active.
Knowing when your app is active is a separate issue. If your app consists entirely of Activities, then you can get good results by starting to track whenever any of your Activities' onResume() methods is called, and stopping tracking in onPause(). If you can have all your Activities derive from a single base Activity class, then this is quite easy. See How to detect when an Android app goes to the background and come back to the foreground for suggestions on how to track this.
If your app is more complex, and the smart stuff happens in a longer-running component like a Service, then it's much harder.
This is crude, but at least it would help you distinguish "playing 3D games" from "using my app".
I've recently ported an application that is known to run with uptime of months (DIY Zoning Project) to Android (the accessory driver, the core process and the remote control). And, unfortunately, though techniques to keep running services alive were used (START_STICKY, startForeground()), sometimes the system^H service app just freezes up - until the user initiates an interaction with the service, after which it resumes normal operation. Most problematic is the fact that it is happening intermittently, and mostly after several days of uptime. The remote control works on the emulator for days at a time with no noticeable degradation, so the problem is most probably either in the service or in the accessory driver.
Currently, the system is targeted at API 10, so advanced service scheduling features are not available - that is, if they're related to the problem to begin with.
Now, what is the realistic way to debug and/or profile such a system? Remember, adb is not available for the Android hardware is connected to an ADK accessory.
Quite a late answer, however, did you try to use Wakelocks?
http://developer.android.com/reference/android/os/PowerManager.WakeLock.html
Possibly the system just hibernates the processor in some cases and it seems like "freezing up"
I observed that I can download a file faster if I use wget with the screen on application,
that acquires a screen dim wake lock than doing the same without this application and
having the screen turned off.. I downloaded exactly the same file (from my apache web server) and the time is almost two times faster when I used the screen on application. To download the file I use a ported versions of wget.. And here is my question:
Does Android lower the download rate when the screen turns off?
Or due to the fact that the screen on app acquires a wake lock, forces the CPU to be always on, so more CPU cycles are spent for the download process.. I am a little bit confused..
Short answer is yes, Android sometimes does lower the download rate when the screen turns off. According to this Android bug report (starred by 90 users),
It seems that, even with "Wifi Sleep Policy" set to "Never", the wifi on some Android devices will enter Power Save mode (a.k.a. PSP mode) when the screen turns off.
PSP mode apparently causes the wifi device to sleep, but wake up periodically and ask its access point to deliver packets that were addressed to to the device while it was asleep. This necessarily causes additional, "spiky" network latency. This additional latency means that some network-oriented applications experience problems when the screen turns off.
This more or less correlates with the behavior you're describing. This issue affects only some phones, not all, and only some versions of Android. I suggest you visit the bug report above, there is a long discussion of this issue.
How to solve this issue
There is a workaround for Android 2.3 at least: You need to acquire WIFI_MODE_HIGH_PERF lock:
In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode WIFI_MODE_FULL but it operates at high performance with minimum packet loss and low packet latency even when the device screen is off. This mode will consume more power and hence should be used only when there is a need for such an active connection.
CPU clock scaling in Android
Android is based on Linux kernel, and uses CPUFreq Governors to adjust CPU frequency to conserve the battery. Exact policies and frequencies vary from vendor to vendor and are subject to change. There are also utilities that let you adjust these policies, but they all require rooted phone. Usually, Android phones lower CPU frequency and use "powersave" governor when the screen is turned off.
However, I don't think network traffic on a phone is CPU-bound. That is, even when in power-safe mode, network throughput is a bottleneck, not CPU speed.
Is there an Android API for stop charging even though physically the charging is on?
Reading previous answers, it looks like there's no way to do this exclusively in software. However, it should be relatively easy to do it with a little hardware help - i.e. by using any Bluetooth- or WiFi-enabled smart electrical switch with open API. The phone could then switch the charger on or off programmatically whenever it feels like it.
Is there an Android API for stop charging even though physically the charging is on?
AFAIK no.
Justification:
android.intent.action.BATTERY_CHANGED is a protected intent that can only be sent by the system. Therefore you cannot duplicate or override the functionality.
You guys are all missing the point - the purpose of limiting charging is to increase battery lifespan by keeping it away from fully charged conditions (and near empty but that's a different issue). If you anticipate needing a full charge then tell it to charge to 100.
If you can't set a charge limit then the battery would rarely be idle and ideally charged when on the charger. It probably requires device level support though.
https://play.google.com/store/apps/details?id=es.guille.stopcharge uses echo "0" > /sys/class/power_supply/battery/device/charge. It works for me on a nexus 4 (rooted), as long as the device isn't fully charged (in a charging state).
Also relevant: https://android.stackexchange.com/questions/15001/how-can-i-avoid-the-battery-charging-when-connected-via-usb
Contrary to some answers indicating it's not possible, it is, indeed possible with ROOT. You can find some apps on the Play Store that will allow you to do this (with root permission, of course).
The best app that works on every phone I've tried it on is Battery Charge Limit. You can download it from the Play Store or the XDA discussion thread. The app is under active development so, if you find that your phone isn't supported, just submit an issue on its GitHub page.
NB: I am not the developer of this application.
This is unfortunately not possible. Android only have read APIs for battery data.
Battery charging control is internal to the Android kernel and battery IC modules. Manufacturers do change it from time to time, like HTC is having small cycles from 95-100% (a bad idea IMO), Samsung does stop charges as soon as it reaches 100%, but I've never seen a device able to stop charging before 100% to reduce battery aging :(.
At best if we're lucky, a sysfs interface might help do that, but it requires root and will differ from device to device.
Just to add to this. Samsung phones do not stop charging after 100%. As far as I'm aware they "trickle" charge past this point however they recommend you do not charge your phone past 100% for over 1 hour. Battery manufacturers like Anker also state the same so the idea of stopping the charge at 100% would be really useful. The risks of leaving the phone on charge are battery bloat and eventually cell rupture. I wasn't aware of this to start off with an killed my samsung battery within 3 months of owning the phone.
To expand on the original question. I've noticed some kernels allow fast charging. If they are able to alter the charge rate up could we alter the charge rate down (trickle) to meet a desired finish time (when your morning alarm goes off)??
I have installed a timer on the AC receptacle where I plug my Moto E's charger into. After guestimating how much time the battery needs to charge to about 85%, I set the timer. This is not my idea of a solution, but at least it keeps my phone from being charged to 100%, as I usually err on the short side when setting the timer.
I dont think there would be such an api. If it does exist it needs to be supported by the device manufacture as its not a pure OS lever feature. The same reason would make it a bad idea to use it as not all devices will support it.
That being said it would be a bad idea to use/implement it , mobile devices are not built to directly run from the power supply and a user will not plug in the cable if he/she did not want to actually charge the device.