Device must be rooted to use this method. Your app does not need to be a system app as we can grant ourselves temporary system app like access. This works in API 21 / 4.*, not sure what else.
Add <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
to AndroidManifest.xml
The internet may tell you that your app must be a system app, but you can ignore that because this method gets around that problem at least in this situation.
Use this code (simplified for this post).
// Grant your app temporary system level like settings access awesomeness
Runtime.getRuntime().exec("su pm grant <yourpackagename> android.permission.WRITE_SECURE_SETTINGS");
// Read the value first to see if you need to set it at all
int curVal = android.provider.Settings.Global.getInt(getContentResolver(),"wifi_suspend_optimizations_enabled",2);
switch( curVal ) {
case 0:
// already disabled
break;
case 1:
// attempt to disable!
boolean success = android.provider.Settings.Global.putInt(getContentResolver(),"wifi_suspend_optimizations_enabled",0);
if( success ) {
// yay worked! maybe check it again to be sure
}
else {
// failed to put
}
break;
case 2:
// Failed to read value, access not granted
break;
}
I derived a lot of this from:
http://muzso.hu/2013/04/07/changing-android-system-settings-eg.-airplane-mode-radios-via-commandline-on-rooted-phone
The method described in this answer can also be used to change other protected system settings, but it may be difficult to track down the exact name of the setting to change.
Useful information is available at android-changing-the-system-settings-of-a-rooted-device-from-inside-the-app namely that you can open /data/data/com.android.providers.settings/databases/settings.db
in a sqlite editor of your choice to look up the table and key names of the setting you want to change.
wifi_suspend_optimizations_enabled
is in the Global table, but that is not the only table available.
Other settings than wifi optimization may require <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
This information may not apply to all devices or situation.