Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

Using the Connectivity Manager Class we can get access to either wifi or Internet Network:

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  // ARE WE CONNECTED TO THE NET if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||   connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {   // ... } 

where 0 and 1 respectively refers to mobile and wifi connection

If my Android device is connected to both, can we switch between any of the networks or can we disable any of the networks? Like using a function:

connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED); 
like image 305
Rohit Sharma Avatar asked Oct 14 '10 07:10

Rohit Sharma


People also ask

How do I enable Wi-Fi disabled on Android?

Go to settings, then on Wireless and Network check to ensure that the WiFi icon is turned on. Alternatively, draw down the notification bar menu, then enable WiFi icon if it's off. Many users have reported having fixed android wifi problem by simply disabling airplane mode.

How do you enable Wi-Fi after disabling it?

If you disabled the connection within Windows, then go to Control Panel | Network and on the left click "change adapter settings" and then you can right click on the wireless connection and choose enable.

What is enable and disable mobile data in Android programmatically?

For your find Information, unless you have a rooted phone I don't think you can enable and disable data programmatically because in order to do so we have to include MODIFY_PHONE_STATE permission which is only given to system or signature apps. setMobileDataEnabled() method is no longer callable via reflection.

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.


1 Answers

I know of enabling or disabling wifi:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(status); 

where status may be true or false as per requirement.

Edit:

You also need the following permissions in your manifest file:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>  
like image 118
viv Avatar answered Oct 13 '22 00:10

viv