androidbatterybackground-servicebattery-saver

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();

  @Override
  public void onCreate() {
    super.onCreate();
  }

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

    BatteryLevelAsync async = new BatteryLevelAsync();
    async.execute();

    return START_STICKY;
  }

  @Override
  public void onDestroy() {
    unregisterReceiver(receiver);

    super.onDestroy();
  }

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

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}

Solution

  • 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 :

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      String packageName = context.getPackageName();
      PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
      if (!pm.isIgnoringBatteryOptimizations(packageName)) {
        Intent intent = new Intent();
        intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("package:" + packageName));
        context.startActivity(intent);
      }
    }