How to programmatically turn off WiFi on Android device? [duplicate]
Asked Answered
H

1

108

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?

Hyaena answered 14/1, 2012 at 16:21 Comment(2)
If it's just for you, then Android got "WiFi sleep policy" setting under "WiFi Settings" -> "Advanced". You enable turning off WiFi after 15min.Poster
I have not got this feature, in advanced settings of my WiFi I have only protocol configuration (DNS, static ip, MAC, etc.)Hyaena
P
242

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.

Parvis answered 14/1, 2012 at 16:25 Comment(11)
why is wake-lock necessary for this?Dentalium
Yes it works without WAKLE_LOCK and UPDATE_DEVICE_STATS, why where they included?Carborundum
Well 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.Whiteside
@J. Maes It require user intervention, it showing dialog?Slapbang
It seems that only CHANGE_WIFI_STATE is needed while ACCESS_WIFI_STATE isn't.Polivy
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..Stater
Note that this no longer works in Android 10. You need to use Settings.Panel.ACTION_WIFI there.Isagogics
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.Khachaturian
wifiManager.isWifiEnabled is now DEPRECATED. Any other solution?Asphyxia
From 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.Drugi
@RushabhShah see Mygod's comment above in this thread and this answer #57204153Ankylostomiasis

© 2022 - 2024 — McMap. All rights reserved.