问题
Android 6 and 7 have some power optimizations (doze mode) which restrict app networking when device is not used.
User may disable optimization mode for any app in Battery settings:
Is it possible to check if optimization is enabled for my app or not? I need to ask user to disable optimization for better app functionality, but I don\'t know how to check it programatically.
回答1:
This one was a bit tricky to track down: here's what you are looking for
PowerManager.isIgnoringBatteryOptimizations()
回答2:
Add this permission in your manifest.
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
Request White-list / optimization enabled 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);
}
}
回答3:
Kotlin
/**
* return false if in settings "Not optimized" and true if "Optimizing battery use"
*/
fun checkBatteryOptimized(): Boolean {
val pwrm = applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
val name = applicationContext.packageName
if (VERSION.SDK_INT >= VERSION_CODES.M) {
return !pwrm.isIgnoringBatteryOptimizations(name)
}
return false
}
and this to show optimizations activity
fun checkBattery() {
if (isBatteryOptimized() && VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) {
val name = resources.getString(R.string.app_name)
Toast.makeText(applicationContext, "Battery optimization -> All apps -> $name -> Don't optimize", Toast.LENGTH_LONG).show()
val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
startActivity(intent)
}
}
回答4:
Sample Code :
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) {
askIgnoreOptimization();
} else {
accepted;
}
} else {
accepted;
}
Declare static variable
private static final int IGNORE_BATTERY_OPTIMIZATION_REQUEST = 1002;
show dialog for BATTERY_OPTIMIZATIONS
private void askIgnoreOptimization() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, IGNORE_BATTERY_OPTIMIZATION_REQUEST);
} else {
openNextActivity();
}
}
May be this code is helpful to you !
来源:https://stackoverflow.com/questions/39256501/check-if-battery-optimization-is-enabled-or-not-for-an-app