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;
}
}
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 :
And add below code to your Activity :