如何正确触发ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS意图?

时间:2015-10-13 23:07:05

标签: android android-intent optimization android-6.0-marshmallow android-doze

如文件中所述:

  

"持有REQUEST_IGNORE_BATTERY_OPTIMIZATIONS权限的应用可以触发系统对话框,让用户直接将应用添加到白名单,而无需进行设置。应用程序触发ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS意图以触发对话框。"

有人可以告诉我解雇这个意图的正确方法吗?

3 个答案:

答案 0 :(得分:38)

Intent intent = new Intent();
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isIgnoringBatteryOptimizations(packageName))
    intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
else {
    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setData(Uri.parse("package:" + packageName));
}
context.startActivity(intent);

有关详细信息,请参阅this answer

答案 1 :(得分:8)

为避免从Google Play商店暂停,最好将用户带到电池优化设置,手动将应用程序添加到白名单

Intent myIntent = new Intent();
myIntent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
startActivity(myIntent);

此外,它不需要

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
清单文件中的

权限

答案 2 :(得分:1)

    Intent myIntent = new Intent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        myIntent.setData(Uri.parse("package:" + getActivity().getPackageName()));
    }
    startActivity(myIntent);