How to know programmatically if 'Put unused apps to sleep" is enabled on Samsung devices

238 Views Asked by At

I have an alarm clock app. In case the users have a Samsung device I explain to them how the "Put unused apps to sleep" feature might affect the performance of the clock and refer them to the battery manager to disable it using the next code:

  Intent intent = new Intent();
  intent.setComponent(new ComponentName("com.samsung.android.sm", 
    "com.samsung.android.sm.ui.battery.BatteryActivity"));
   try {
      getActivity().startActivity(intent);
   } catch (ActivityNotFoundException exception) {}

Then I need to know whether the user disabled the "Put unused apps to sleep" feature. How can I do that?

1

There are 1 best solutions below

1
Jodes On

This should work:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isPutAppsToSleepEnabled = pm.isIgnoringBatteryOptimizations(getPackageName());

You'll need this in the AndroidManifest.xml:

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

Hope that helps.

If you're calling the code from an activity, you can directly use getPackageName() since the Activity class extends Context and provides this method.

Otherwise, you'll need to pass a Context object to the method that contains the code or something.