Services getting killed on custom OS Devices - android

I'm a newbie android developer.. I have trouble keeping the background services broadcast receivers etc alive on no stock android devices.. i have tried many solutions and couldn't find one that works... Please help.

Unfortunately, many of Android devices will have issues with staying alive in the background due to aggressive battery-saving policies of their manufacturers. This leaves you with two options: either instruct your users how to "white-list" your app to not get killed because of battery consumptions.
See here: Don't kill my app.
Or, have it done automatically by special permission.
See here: Optimize for Doze and App Standby
You should know that there are some issues with the second option, as it does not solve the case with all of the manufacturers and also, your app might be banned from Play Store if you request it and unless the core function of the app is adversely affected.

Related

Problems with background execution on Android 11 devices

Recently I have discovered that about 2 months ago there was released Android 11 update for Samsung devices.
Samsung has in this version of OS decided to really strictly suspend the apps/services running in the background (more info)
So e.g. when app I am working on goes to background and phone is locked, all BT communication is almost immediately suspended. When I unlock the screen, in that exact moment all threads are not suspended anymore and execution continues.
OS therefore completely ignores the foreground service mechanism.
Official documentation
Also when I try to add my app to the list of "Never sleeping apps" (some alternative to battery optimization whitelist on Android 11) - app is still getting suspended + this whitelisting mechanism appears to be unstable and even when I add my app to the whitelist, app disappears from the list after few hours.
My questions:
Have you seen similar issues on Android 11 too ? What helped to resolve the issue?
Is this only Samsung specific issue or even Pixel devices do the same optimization (ignoring foreground service and whitelist)?
Thanks for any input.
sadly this is a huge and common problem and my repsonse will probably not fix it for you, but give you some more insights and possible work-arounds. Have a look at dontkillmyapp.com.
Especially dontkillmyapp.com/samsung:
On Android 11 Samsung will prevent apps work in background by default unless you exclude apps from battery optimizations. This is a severe divergence from standard Android process management policies.
Yes, this is a long way to go! Devs cannot ask for it automatically as they risk being kicked out from Play Store due to policy violations.
Also I can highly recommend very insightful the fun talk fron Droidcon Berlin 2021.

Battery drain via Google Play Services persists after location services are used in Android

I'm using location & activity recognition features of android. Used for realtime location tracking. Currently using the latest ConnectionLess APIs. I have encountered the following problem:
After starting the location, activity services, once in a while, the battery starts to get drained. The behavior is pretty strange as the entire drain is showed under Google Play Services. The drain persists even if the app is stopped, killed, etc. To my surprise, the drain persisted even when the app was uninstalled and it took a couple of full battery re-charges to come out of the situation.
I'm more or less sure that the drain is triggered by my app as multiple devices have recorded the issue and these devices are from different manufacturers and across multiple android OS versions. In ADB shell, I find com.google.android.gms taking up 126% CPU permanently as seen below:
Next, I listed all the threads under that process. Result attached below:
As seen there's one thread, CastSocketMulti running. All other threads are sleeping.Didn't get much on castSocketMulti other than some basic information like it is related to casting in android, etc. We aren't using anything related to casting in our app.
After, killing the process, the drain stops.
Note: I found same question here, however unanswered.
Edit: Every time the battery drain happens, as above, com.google.android.gmsis listed as the number one process taking 100%+ CPU and the castSocketMulti, the only thread of that process in R status
Update: I have opened an issue here.
Pls leave a star so that it may go high on priority
I have found the exact same thing here on a OnePlus 3. I'm not rooted and can't kill the process, but using adb to clear the cache of com.google.android.gms makes the process crash and alleviates the problem for a few days.
Do you use Android Auto or Android Pay? It seems to happen more frequently when I use those two apps in particular.
OK, Google claims to have fixed the issue and they have marked the issue as 'Fixed'. Details here

Android doze mode and foreground service

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.

Android app closing automatically

I have an android app installed on device (4.2.2).
The device will never go to power save mode.
If i leave the app open for more than 30 minutes, the app closes automatically.
And no exception found in the log.
Is this default android behaviour?
If possible please share any links about this issue.
That is just part of how Android manages memory for activities using the Low Memory Killer, even if as of today devices running Android have vast amounts of memory, the same rules are still applied as when it was designed, and it was designed to run on devices with low memory, if you want to keep it alive without user interaction you might have to either use a Service, or maybe find a way to simulate user interaction.
If you have this behaviour just only 4.x, but under 4.x don't, try in Manifest to turn true largeHeap. You have to turn it on in apllications tag attribute. I hope it will help.

Samsung "App optimisation" feature kills background applications after 3 days

We are currently developing an Android app that is a fitness-tracker application. It runs constantly in the background, and it works fine on most devices, but we've been having issues with the application dying completely on some Samsung devices. After some investigation, it seems like some Samsung devices has a completely custom "App Optimisation" feature (http://forums.androidcentral.com/samsung-galaxy-s6/599408-app-optimisation-after-updating.html), which is basically a (very) primitive version of the Doze feature that exists in later versions of Android which basically just murders apps if they haven't been used for three days.
As this app is more or less only doing logging, and doesn't open the activity, it presents a big problem for us, because this feature is pre-enabled on many Samsung devices. The problem is solved by using a foreground service, but that is a sledgehammer of a solution that requires disturbing the user with a constant notification, and we really don't need the app to be in the foreground - we are fine with the normal power management of Android.
The Samsung App Optimisation feature clearly states that it will "optimise" apps if they have not been used for three days. Does anyone have insight in what Samsung considers to be "used" and can I somehow trigger that?
Side-rant: In my opinion, this is a badly implemented feature that makes development on Android more hostile. Besides our use case, it will any messenger applications break. If it were not for the fact that Facebook Messenger and Whatsapp are hard-wired to be exempt for the app, users would be going crazy because it would be breaking their experiences.
I've owned (and currently own) Samsung devices, so I know a little as to how it works from the user's point of view. The technical specifications and how it works on the inside is an entirely separate issue, and one I can't answer.
The system can detect if you open an app. Samsung uses that in their app optimization, and will save power on apps that haven't been used in over three days. It is a terrible system though.
It ignores background-processes that may be critical to apps, and even if it is an app you actively use, like a fitness tracker, it will have issues. To quote what it says inside the app optimization-list:
"To save battery power, apps that haven't been used for more than 3 days will be designated to save power. Apps designated to save power may not show notifications"
(Rough translation from Norwegian, originally taken from an S6 running Android 6)
Therefore, apps that have been manually, or automatically set (3 days of no use) may give various issues with background processes. But remember that the user can set any app to never save battery, and ignoring the automatic setting. So with this in mind, let's consider possible solutions.
There is one scenario where you do not need to worry about the app and app optimization: When app optimization is disabled entirely.
Looking aside that, there is really only two things you can do:
Ask users on Samsung to disable battery optimization for your app to prevent issues
As #MinaSamy suggested (in their now deleted answer), SyncAdapter and having a periodic synchronization. Note that I haven't tested this, so I don't know whether it works or not.
And there's also a third option, which really isn't a solution, but you can ignore it and gamble on app optimization being disabled, or just not care about it at all.
Does anyone have insight in what Samsung considers to be "used" and can I somehow trigger that?
As far as I know, unless Samsung added some safeguards against accidental opening or added some kind of minimum activity requirement, opening is enough. It appears to be a "stupid" feature, which runs on hard-coded rules rather than a dynamic system that actually detects app use and sets power saving relative to that. It's "easy to enable", but fortunately easy to disable as well.
Meaning you cannot trigger an event that will keep it alive (unless SyncAdapter does the trick)
And to make the facts clear, from #Neil's answer:
It does seem like the user can do this, so there must be some database or setting somewhere that controls it.
There kinda is. There are a total of four settings, three of which are app-specific, and it is stored in a database (or some other form of data storage). These four settings can be used, although extremely shallow, to alter the behavior of the app optimization:
Always optimize
Automatic optimization
Never optimize
Disable app optimization
The first three options are on a per-app basis, which means each app can have separate settings. Disabling app optimization is exactly what you'd expect: it disables the entire feature for all apps. If it's disabled entirely, nothing is optimized.
There's also a website listing ways of bypassing optimizations on a per-brand basis. The entry for Samsung is more or less what I've said: tell the user to manually disable optimization. There are no developer solutions.
In settings>device health>battery there's an option to "put unused apps to sleep". You can turn it off, or change the amount of time it takes, which is 3 days by default.
Sounds like that's your problem.
https://forums.androidcentral.com/samsung-galaxy-s10-s10-plus/964083-whats-disabling-some-my-apps-background.html
Is there a reason you can't add your service to the 'don't optimise' list?
It does seem like the user can do this, so there must be some database or setting somewhere that controls it.
Alternatively, if you detect you are installing on one of the devices, open the optimise activity page, and show a message saying "Don't optimise us!".
As a workaround, i implemented the SyncAdapter mechanism, using this link as a good starting point: https://github.com/bmeike/MiniSync
It doesn't work perfectly (for testing, in my app i write a log every 1h, and after 3 days, it starts not respecting this scheduling), but at least it doesn't stop after 3 days, without the need to put the app in ignored optimization mode.
UPDATE: After the update to android PIE, scheduling stopped again after 3 days.
On another device, same app with android Oreo, scheduling is working (even if not completely respected).
On Samsung phones, the culprit is this Sleep setting:
You have got to take your users to this system settings screen and ask them to turn the feature off.
In my opinion you should implement a 'Broadcast Receiver' that listens to a custom 'Intent' and this 'Intent' to be Broadcasted by the 'Service' from 'onDestroy()' method of the 'Service' because when the 'System' kill the 'Service' this method will be called definitely.
And when the 'Broadcast Receiver' receives the 'Intent' you should start the 'Service' again.
And to distinguish between you stopping the 'Service' or the 'System' stopping the 'Service' just use some 'booleans' stored in 'SharedPreferences' and then in the 'Broadcast Receiver' you decide whether to activate the 'Service' or not
we are fine with the normal power management of Android
Are you? From the Android docs
However, since the user is not directly aware of a background service, in that state it is considered a valid candidate to kill, and you should be prepared for this to happen. In particular, long-running services will be increasingly likely to kill and are guaranteed to be killed (and restarted if appropriate) if they remain started long enough.
Three days seems like it would fall under "long-running...guaranteed to be killed".
If the problem is not that your service is killed but that it isn't restarted, you could use the AlarmManager to regularly check the status of your service and restart, if necessary.

Categories

Resources