Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run background services on battery saver mode Android

I have a service for sending http request that runs on background and works fine on "normal mode". The problem is when I put my phone on "battery saver mode", the service not working. But, apps like Whatsapp still working. Do you have any idea what's going on?

like image 275
Mauricio Ballesteros Avatar asked Apr 03 '18 21:04

Mauricio Ballesteros


3 Answers

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

like image 135
Flowwlol Avatar answered Oct 21 '22 04:10

Flowwlol


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.

like image 10
Sagar Avatar answered Oct 28 '22 14:10

Sagar


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);
            }
        }
like image 8
Anirban Avatar answered Oct 28 '22 13:10

Anirban