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 network or can we disable any of the network? Like using a function:
connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED);
A complete solution:
Reference: http://amitkumar-android.blogspot.com/p/installation-steps.html
I could not access the context object directly.
My solution is as following:
Also I had to change some writings eg. WIFI_SERVICE vs. WifiService.
add this permission in your manifest and than use the above code to change WiFi state:
To Enable WiFi:
To Disable WiFi:
Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:
I know of enabling or disabling wifi:
where status may be
true
orfalse
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"/>
To enable disable Wifi use the
WifiManager
class to get system(android device) services for Wifi :Now the object
wifi
of theWifiManager
class is used to get the wifi status:And most importantly do not forget to give the following permission in your Android Manifest File:
To get detailed info and full sample code of the project for enable/disable Wifi on android visit my website link.