How to keep an app since SDK 16 running foreground every time?

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.

  1. if api level >= Oreo, ask the user to disable battery optimisation (Doze mode).
  2. 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.