1

I'm working on an app that requires active working service so to avoid Doze Mode I've write code that'll show a default dialog to ask that this app will consume more battery and all. But the main problem here is before showing that dialog app freezes for a second or two and then continue. I'm wondering what is wrong. Here is the code I've written -

private void batteryOptimisationIntent() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager != null && powerManager.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));
            startActivity(intent);
        }
    }
}
Ashutosh Sagar
  • 981
  • 8
  • 20

1 Answers1

-1

You call this batteryOptimisationIntent() method in UI thread thats why you UI are freezes.

Please try like this ->

protected void onCreate(Bundle savedInstanceState) {

    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            // Your Method name
            batteryOptimisationIntent();

        }
    };

    Thread thread = new Thread(runnable);
    thread.start();
}

private void batteryOptimisationIntent() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager != null && powerManager.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));
            startActivity(intent);
        }
    }
}
Sabbir Ahmed
  • 351
  • 1
  • 13