应用程序在REQUEST_IGNORE_BATTERY_OPTIMIZATIONS上暂停一秒钟

时间:2018-02-14 05:25:32

标签: android android-doze battery-saver

我正在处理需要有效工作服务的应用,以避免Doze Mode我编写的代码会显示默认对话框,要求此应用消耗更多电量和所有。但这里的主要问题是在显示对话框应用程序冻结一两秒然后继续之前。我想知道出了什么问题。这是我写的代码 -

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

1 个答案:

答案 0 :(得分:-1)

你在UI线程中调用了这个batteryOptimisationIntent()方法,这就是为什么UI被冻结了。

请尝试这样 - >

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