Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly fire ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS intent?

As stated in the documentation:

"An app holding the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission can trigger a system dialog to let the user add the app to the whitelist directly, without going to settings. The app fires a ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent to trigger the dialog."

Can someone tell me the proper way to fire this intent?

like image 609
A.Sanchez.SD Avatar asked Oct 13 '15 23:10

A.Sanchez.SD


2 Answers

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

Kotlin

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)

See this answer for more information.

like image 61
Buddy Avatar answered Oct 18 '22 10:10

Buddy


To avoid suspension from Google Play Store, Its Better to Take User to Battery Optimization Settings, for Manually Adding Application to White-list

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

Also It doesn't need to have

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>

permission in the manifest file

like image 40
Jamil Avatar answered Oct 18 '22 10:10

Jamil