How to programmatically turn off WiFi on Android device?

Android

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ.OlufsenView Question on Stackoverflow
Solution 1 - AndroidJ. MaesView Answer on Stackoverflow