We develop some android applications with foreground services that execute tasks for a long time. But from Android M or Android 6 or Marshmellow or API v23+, Android decided to put optimize for doze and app standby That causes the app to go to standby mode. The app cannot communicate with a server or do any tasks from foreground services if the device is locked or turned the display off because the app is in standby mode.
But our business is to put alive the foreground service and keep it running. Then we should use REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
permission and ignore battery optimization for the app.
Please follow below code snippet (Java and Kotlin both given below)
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
@RequiresApi(api = Build.VERSION_CODES.M)
private void ignoreBatteryOptimization() {
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null && !pm.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
Or
@RequiresApi(api = Build.VERSION_CODES.M)
open fun ignoreBatteryOptimization() {
val intent = Intent()
val packageName = packageName
val pm = getSystemService(POWER_SERVICE) as PowerManager
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:$packageName")
startActivity(intent)
}
}
Click here to learn how to create a foreground service in android, Kotlin.