This site finally got its much-needed overhaul.
I tried to keep existing pages at their original URLs.
Should you find an error, please do tell me at
contact@aspyct.org.
Feel free to visit the new website, which may contain more documentation pertaining to your search.
Thank you for visiting aspyct.org, I hope you'll find what you're looking for.
Sometime you simply need more than HTTP requests or buttons. Sometimes you need to play with device state, switch the wifi on for example. Android provide a very easy API to do that.
And to do that, we need to use the WifiManager. As any other system service, we can get it through the context, usually our activity.
Let’s write some code to toggle the wifi state. It involves 1. getting the current state and 2. changing it to the other state. But first things first, we need the permissions.
123
<!-- Add these permissions to your android manifest --><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/><uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE"/>
And now that we have the permissions, finally, the code!
1234567891011121314
publicvoidtoggleWifi(){// Get the WifiManager service from the contextWifiManagerwm=(WifiManager)this.getSystemService(Context.WIFI_SERVICE);// Read the current state. True is On, False is OffbooleancurrentState=wm.isWifiEnabled();// And now, switch to the other statewm.setWifiEnabled(!currentState);// You're done :)// Note that it can take some time for the wifi to reconnect// when you switch it on.}