I need to turn off the WiFi a while after pressing the "Turn off the Screen" button. There is a need for this app for my tablet because sometimes I just forget to turn off the WiFi and this discharges the battery very fast. It lives 10x+ times less than I would without WiFi. Is there any solution available as .apk? Can I track when the screen turned off and 5 min elapsed? Can I programmatically turn off WiFi on Android device? How?
Asked
Active
Viewed 1.2e+01k times
107
-
2If it's just for you, then Android got "WiFi sleep policy" setting under "WiFi Settings" -> "Advanced". You enable turning off WiFi after 15min. – Māris Kiseļovs Jan 14 '12 at 16:25
-
I have not got this feature, in advanced settings of my WiFi I have only protocol configuration (DNS, static ip, MAC, etc.) – J.Olufsen Jan 14 '12 at 17:24
1 Answers
240
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
-
12
-
Yes it works without WAKLE_LOCK and UPDATE_DEVICE_STATS, why where they included? – powder366 May 23 '13 at 09:06
-
2Well I assume the extra permissions were just the result of directly copying the code from from the link he provided, but even so, UPDATE_DEVICE_STATS is reserved for system apps only, the application won't even compile with that permission. – Jasjit Singh Marwah May 25 '13 at 18:05
-
-
3It seems that only `CHANGE_WIFI_STATE` is needed while `ACCESS_WIFI_STATE` isn't. – hata Feb 19 '16 at 18:44
-
it works fine, if device is on but when device goes to sleep WIFI enabled but not connecting to the WIFI until device is on. If you have any idea please help me.. – user512 Apr 02 '16 at 10:53
-
3Note that this no longer works in Android 10. You need to use `Settings.Panel.ACTION_WIFI` there. – Mygod Jul 20 '19 at 17:01
-
The WIFI_SERVICE must be looked up on the Application context... As the error suggest it seems that WiFiManager must use Application Context (not Activity Context), otherwise a memory leak can occur. – The Black Horse Sep 24 '19 at 14:38
-
-
7From Android 10(Q) onwards, applications are not allowed to enable/disable Wi-Fi. So, whenever we executes wifiManager.setWifiEnabled(true) from android 10 or above, it will not allow to enable/disable wifi. – Dhaval Shah Feb 03 '21 at 13:36
-
@RushabhShah see Mygod's comment above in this thread and this answer https://stackoverflow.com/questions/57203653/how-to-open-settings-panel-in-android-q-programmatically – nbonbon Aug 06 '21 at 18:23