Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify Wi-Fi Sleep policy programmatically?

Tags:

android

I want to keep Wi-Fi enabled when device goes to sleep mode, I tried several options, but nothing has worked out like acquire Wi-Fi lock and set wi-fi enabled. These options are not working then I tried with wake lock, this is working perfectly when my application running in the foreground, but when application is running in background, after some time excess wake lock error comes and application is getting destroyed and on top of that I can't use wake lock all the time because it dried out the battery.actual requirement is my application should run 24/7 and connectivity with the server always stays on because server can send data any time, but when device goes to sleep mode wi-fi is getting turned off so I need to set the wi-fi sleep policy to never upon starting of my application and will set back to normal policy when application gets destroyed. I tried following code in my main activity and runs the application and allow device to go to sleep mode and after some time connection is still getting closed:

Settings.System.putInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY, 
Settings.System.WIFI_SLEEP_POLICY_NEVER);

So please do help me to resolve this issue.

like image 622
piks Avatar asked Feb 15 '26 01:02

piks


2 Answers

Use import static android.provider.Settings.System.WIFI_SLEEP_POLICY; instead of the name string Settings.System.WIFI_SLEEP_POLICY.

It works perfectly.

like image 189
android fan Avatar answered Feb 17 '26 13:02

android fan


In my case Settings.System.WIFI_SLEEP_POLICY does not work. I was able to keep wi-fi on with the PowerManager

final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();

Then in the OnDestroy() I call

wl.release();
like image 45
peregrinus Avatar answered Feb 17 '26 13:02

peregrinus