Background service stops in battery saver mode in android R


I wrote an android app that checks battery level by changing level and gives an alarm when the level reaches a certain value.
I made use of broadcast receiver and background service in my app.
It works properly in all android versions but in android R service stops when battery saver mode is turned on.
I tested my app on several emulator and real device with different android versions and works properly but has problem in android R.
Is there a way to prevent the service from stopping? 

my Service class :

public class BatService extends Service {

  private BatReceiver receiver = new BatReceiver();

  public void onCreate() {

  public int onStartCommand(Intent intent, int flags, int startId) {

    BatteryLevelAsync async = new BatteryLevelAsync();

    return START_STICKY;

  public void onDestroy() {


  private class BatteryLevelAsync extends AsyncTask<Void,Void,Void>
    protected Void doInBackground(Void... voids) {
      registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      return null;

  public IBinder onBind(Intent intent) {
    return null;


Google has imposed restrictions on Android 8 to optimize the battery.
This restricts background work even when using services.
I found an solution to solve this problem: use PowerManager.

Add permission to manifest :

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

And add below code to your Activity :

  String packageName = context.getPackageName();
  PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
  if (!pm.isIgnoringBatteryOptimizations(packageName)) {
    Intent intent = new Intent();
    intent.setData(Uri.parse("package:" + packageName));

Answered By – homayounKh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published