Run background services on battery saver mode Android
The background services are being worked on since Marshmallow and are not to be used for anything else than foreground usage since Oreo.
The doze mode will forbide any operation while active, the phone will get out of doze for few Ms every X hours, some library will allow you to make some operations during that time.
If you want to do some background operation during the doze & Battery saver you may want to have a look at the JobScheduler for operation that will be executed every 15 minutes or more while the phone is not in doze and if you require operations more often, i would advice you to have a look at the JobDispatcher. Both will execute your task when going out of the doze mode
Add permission
<uses-permission
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
request whitelist your app
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
Mobile applications like Whatsapp must be requesting permission to exempt them from Doze/battery saving and App standby mode.
It is possible to configure this manually by configuring the Whitelist in Settings > Battery > Battery Optimization.
Alternatively from API 23, you can use permissions model to request users to whitelist them (refer this). From API You can also check whether your app is currently on White list by calling isIgnoringBatteryOptimizations()
However you need to satisfy certain criteria for being able to whitelist yourself. Otherwise you face issues while maintaining app on Google Play Store.
But mostly messenger apps like Whatsapp are triggered through high-priority push notifications so they are more likely to be active despite not running background process.