Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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?

like image 403
J.Olufsen Avatar asked Jan 14 '12 16:01

J.Olufsen


People also ask

How do you turn off Wi-Fi on Android?

Go to the AndroidManifest. xml file and add two user-permissions: ACCESS_WIFI_STATE and CHANGE_WIFI_STATE. Below is the code for the AndroidManifest.

How do you check if Wi-Fi is on or off in Android programmatically?

Checking the state of WiFi can be done by obtaining an instance to the WiFi system service as below: WifiManager wifi = (WifiManager)getSystemService(Context. WIFI_SERVICE); from this, the method isWifiEnabled() can be used to determine if WiFi is enabled.

What is Wi-Fi manager in Android?

WiFi Manager is a tool to manage WiFi connections, thanks to which you will not only have the ability to find and connect to networks in your environment, but it also will improve the quality of those connections.

How do I stop Wi-Fi from opening?

To stop your Android device from auto-connecting to open networks, open the settings and go to Network & Internet > Wi-Fi > Wi-Fi preferences. Tap the button next to Connect to open networks to disable it.


1 Answers

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.

like image 170
J. Maes Avatar answered Oct 21 '22 17:10

J. Maes