问题
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.
回答1:
Add below permission to manifest.xml
<uses-permission
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
Call below method
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);
}
}
Or you can use below scenario also...
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
}
}
}
来源:https://stackoverflow.com/questions/37568246/how-to-turn-off-doze-mode-for-specific-apps-in-marshmallow-devices-programmatica