如何以编程方式关闭棉花糖设备中特定应用的打do模式 [英] how to turn off doze mode for specific apps in marshmallow devices programmatically

查看:72
本文介绍了如何以编程方式关闭棉花糖设备中特定应用的打do模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

棉花糖API与以前的Android OS有很大不同.屏幕关闭时,设备处于打do模式且无法同步网络.因此,要使用网络进行后台操作,我们必须防止打ze睡模式.

Marshmallow APIs are very different from previous android OS. When screen is off, devices are in doze mode and unable to sync network. So for doing background operations with network we have to prevent from doze mode.

推荐答案

将以下权限添加到manifest.xml

Add below permission to manifest.xml

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

在下面的方法中调用

public void turnOffDozeMode(Context context){  //you can use with or without passing context
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent();
            String packageName = context.getPackageName();
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (pm.isIgnoringBatteryOptimizations(packageName)) // if you want to desable doze mode for this package
                intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            else { // if you want to enable doze mode
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
            }
            context.startActivity(intent);
        }
    }

或者您也可以在以下情况下使用...

以编程方式将Android应用程序列入白名单可以通过以下方式完成:

Whitelisting an Android application programmatically can be done as follows:

boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(getPackageName());
if(!isIgnoringBatteryOptimizations){
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setData(Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, MY_IGNORE_OPTIMIZATION_REQUEST);
}

可以通过以下代码验证开始上述活动的结果:

The result of starting the activity above can be verfied by the following code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_IGNORE_OPTIMIZATION_REQUEST) {
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(getPackageName());
        if(isIgnoringBatteryOptimizations){
            // Ignoring battery optimization
        }else{
           // Not ignoring battery optimization
        }
    }
}

这篇关于如何以编程方式关闭棉花糖设备中特定应用的打do模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆