问题
The expected behavior is that the app will be running all the time when it's in ON state. Some phones put the app in background mode when the app is not active for some time. I want the app to be running all the time even its in standby mode(standby mode means when we press the home button the app will go to background. and it will run for some time).
I found following code and I tried that
PowerManager powerManager = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE);
String packageName = "org.traccar.client";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent i = new Intent();
if (!powerManager.isIgnoringBatteryOptimizations(packageName)) {
i.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
i.setData(Uri.parse("package:" + packageName));
startActivity(i);
}
else{
i.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
i.setData(Uri.parse("package:" + packageName));
startActivity(i);
}
}
Even after working with the code the default state is Battery Saver(recommended)
I want the app in No Restriction mode once the app is opened, any solution for this?
回答1:
The code you use is for battery optimization. Settings-->Batery-->Three Dots Menu Item (...)--->Battery Optimization-->(Choose an app from list)--->Optimize/ Don't optimize.
By choosing Don't optimize
you are essentially bypassing Doze
, not app standby
.
Also be advised that doing this programmatically as you do may result in Google taking your app off the store. It is safer to do it manually following the path i described above.
More on Doze
and App Standby
here
来源:https://stackoverflow.com/questions/53115473/how-force-the-app-to-opt-out-of-battery-saver-mode-when-the-service-is-on