How to keep an app since SDK 16 running foreground every time? I’m building an app to monitoring the android device.
I’ve looked in 3 obstacles:
1 - The difference between android under and post 7.0.0 on foreground services
2 - Chinese ROMs, with an agressive kill of apps when user do a simple clean on last apps
3 - which android tool can I use for resolve it.
I’ve seen until now: AlarmManager, permanent notifications, accessibility service… Broadcast receiver to up application when system restart and battery optimization, but all my tries didn’t seem to help me in solving.
For example, the follow tutorial doesn’t work after I clean the lastest apps used in a Chinese ROM (Xiaomi) https://robertohuertas.com/2019/06/29/android_foreground_services/
What does it have to do with kotlin?
The app is full kotlin code…
The question is still completely irrelevant to the Kotlin language. You should ask those in android forums.
I think it’s fine to ask here After all we have an “Android” subject tag for a reason and sometimes it’s hard to know if a question has anything to do with Kotlin or not when it comes to Android.
Although for this I would agree that Kotlin is probably not relevant to answer your question.
Since only a portion of the users here work with Android you might get an answer faster on an Android forum. If you do find an answer elsewhere posting the link here would be much appreciated by future finders of your question.
When searching for Android questions you’ll likely find answers in Java as well as Kotlin-- which is okay since almost all of those answers will apply to Kotlin.
You mean, how to keep your code running even in background?
For instance, you make an app that computes digits of PI and you have this algorithm that outputs one digit at the time to the screen. And you want the algorithm to continue when the app gets in background.
- if api level >= Oreo, ask the user to disable battery optimisation (Doze mode).
- avoid using Services, AlarmManager, Context, Firebase WorkManager or anything that is from Android SDK and is directly controlled by the operating system. For instance, I use pure java threads. Those are not so easily killed on background. On my Pi calculator example, I would create a class PiCalculator extends Thread. Making sure only one PiCalculator thread will run at a given time, I would loop getting the next pi digit, then I would send the digit to the UI via an EventBus library.
Of course, the system cam kill the app whenever it wants, but these two tricks will limit the events. At least that’s how I do it in my apps. But on the other hand, I only do data and file synchronization, thus I can easily avoid Android SDK stuff. What are you trying to do in bacakground, exactly?
The only way to guarantee always running is to modify the Android system according to your needs.