38

如文档中所述:

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

有人能告诉我激发这种意图的正确方法吗?

4

3 回答 3

61
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);

科特林

val intent = Intent()
val pm : PowerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
if (pm.isIgnoringBatteryOptimizations(context.packageName)) {
    intent.action = Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
} else {
    intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
    intent.data = Uri.parse("package:${context.packageName}")
}
context.startActivity(intent)

有关更多信息,请参阅此答案

于 2015-10-13T23:16:24.443 回答
12

为避免被 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"/>

清单文件中的权限

于 2017-08-09T11:34:54.893 回答
0
    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);
于 2018-04-04T12:47:22.283 回答