private boolean isIntentAvailable(@NonNull Context context, @NonNull Intent intent) { return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0; }
try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); String packageName = getPackageName(); Intent batteryIgnoreIntent = new Intent("android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS"); batteryIgnoreIntent.setData(Uri.parse("package:" + packageName)); boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(packageName); if (!isIgnoringBatteryOptimizations) { if (isIntentAvailable(MainActivity.this, batteryIgnoreIntent)) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent); } else { Intent intent = new Intent(); intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); startActivity(intent); } } } } catch (Exception ex) { ex.printStackTrace(); MyLog.ex(ex); }
Testing your app with Doze
adb shell dumpsys deviceidle enable
Force the system into idle mode by running the following command:
adb shell dumpsys deviceidle force-idle
When ready, exit idle mode by running the following command:
adb shell dumpsys deviceidle unforce
Force the app into App Standby mode by running the following commands:
adb shell dumpsys battery unplug adb shell am set-inactive <packageName> true
Simulate waking your app using the following commands:
adb shell am set-inactive <packageName> false adb shell am get-inactive <packageName>
References
https://www.bignerdranch.com/blog/choosing-the-right-background-scheduler-in-android/
https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases
https://developer.android.com/topic/performance/scheduling
https://www.bignerdranch.com/blog/diving-into-doze-mode-for-developers/
https://stackoverflow.com/questions/48805376/how-solve-a-fatal-exception-in-android-content-activitynotfoundexception-error
https://stackoverflow.com/questions/32627342/how-to-whitelist-app-in-doze-mode-android-6-0
https://stackoverflow.com/questions/36457524/can-not-switch-to-doze-mode
https://stackoverflow.com/questions/33709046/wake-lock-disabled-in-foreground-service-with-doze-mode-new-battery-optimizati