Function implementation: control the WiFi switch and connect to a specific wifi.
First, let's start with a WiFi tool class. This class is reposted to one person on the Internet, and the source is unknown.
Package rodar. RGS. conference. utils; import Java. lang. reflect. constructor; import Java. lang. reflect. field; import Java. lang. reflect. invocationtargetexception; import java.net. inetaddress; import Java. util. arraylist; import Java. util. list; import android.net. wiFi. scanresult; import android.net. wiFi. wificonfiguration; import android.net. wiFi. wifimanager; public class wificonnect {wifimanager; // number of definitions One is WEP, the other is WPA, and public Enum wificiphertype {wificipher_wep, wificipher_wpa, wificipher_nopass, wificipher_invalid} // constructor public wificonnect (wifimanager) {This. wifimanager = wifimanager;} // enable the WiFi function private Boolean openwifi () {Boolean Bret = true; If (! Wifimanager. iswifienabled () {Bret = wifimanager. setwifienabled (true);} return Bret;} // provides an external interface to pass in the public Boolean connect (string SSID, string password, wificiphertype) {If (! This. openwifi () {return false;} system. out. println (">>> wificon ="); // it takes some time to enable the WiFi function (it usually takes about 1-3 seconds to test on my mobile phone ), so the following statement while (wifimanager. getwifistate () = wifimanager. wifi_state_enabling) {try {// to prevent the program from having a while loop, let it sleep for 100 milliseconds for detection ...... Thread. currentthread (); thread. sleep (100);} catch (interruptedexception IE) {}} wificonfiguration wificonfig = This. createwifiinfo (SSID, password, type); // If (wificonfig = NULL) {return false;} wificonfiguration tempconfig = This. isexsits (SSID); If (tempconfig! = NULL) {wifimanager. removenetwork (tempconfig. networkid);} // try {// advanced options // string IP = "192.168.1.201"; // int networkprefixlength = 24; // inetaddress intetaddress = inetaddress. getbyname (IP); // int intip = inetaddresstoint (intetaddress); // string DNS = (intip & 0xff) + ". "+ (intip> 8) & 0xff) + ". "+ (intip> 16) & 0xff) + ". 1 "; // setipassignment (" static ", wificonfig); //" static "or" DHCP "for Dynamic Setting // setipaddress (intetaddress, networkprefixlength, wificonfig); // setgateway (inetaddress. getbyname (DNS), wificonfig); // setdns (inetaddress. getbyname (DNS), wificonfig); //} catch (exception e) {// todo: handle exception // E. printstacktrace (); //} int netid = wifimanager. addnetwork (wificonfig); Boolean Bret = wifimanager. enablenetwork (netid, true); // wifimanager. updatene Twork (wificonfig); Return Bret;} // check whether the network private wificonfiguration isexsits (string SSID) {list <wificonfiguration> existingconfigs = wifimanager has been configured before. getconfigurednetworks (); For (wificonfiguration existingconfig: existingconfigs) {If (existingconfig. SSID. equals ("\" "+ SSID +" \ "") {return existingconfig ;}} return NULL;} private wificonfiguration createwifiinfo (string SSID, string Password, Wificiphertype) {wificonfiguration Config = new wificonfiguration (); config. allowedauthalgorithms. clear (); config. allowedgroupciphers. clear (); config. allowedkeymanagement. clear (); config. allowedpairwiseciphers. clear (); config. allowedprotocols. clear (); config. SSID = "\" "+ SSID +" \ ""; if (type = wificiphertype. wificipher_nopass) {config. wepkeys [0] = ""; config. allowedkeymanagement. set (WIF Iconfiguration. keymgmt. none); config. weptxkeyindex = 0;} If (type = wificiphertype. wificipher_wep) {config. presharedkey = "\" "+ password +" \ ""; config. hiddenssid = true; config. allowedauthalgorithms. set (wificonfiguration. authalgorithm. shared); config. allowedgroupciphers. set (wificonfiguration. groupcipher. CCMP); config. allowedgroupciphers. set (wificonfiguration. groupcipher. TKIP); config. allowedgroupc Iphers. set (wificonfiguration. groupcipher. wep40); config. allowedgroupciphers. set (wificonfiguration. groupcipher. wep104); config. allowedkeymanagement. set (wificonfiguration. keymgmt. none); config. weptxkeyindex = 0;} If (type = wificiphertype. wificipher_wpa) {config. presharedkey = "\" "+ password +" \ ""; config. hiddenssid = true; config. allowedauthalgorithms. set (wificonfiguration. authalgorithm. open); Conf IG. allowedgroupciphers. set (wificonfiguration. groupcipher. TKIP); config. allowedkeymanagement. set (wificonfiguration. keymgmt. wpa_psk); config. allowedpairwiseciphers. set (wificonfiguration. pairwisecipher. TKIP); // config. allowedprotocols. set (wificonfiguration. protocol. WPA); config. allowedgroupciphers. set (wificonfiguration. groupcipher. CCMP); config. allowedpairwiseciphers. set (wificonfiguration. pairwisecip Her. CCMP); config. status = wificonfiguration. status. enabled;} else {return NULL;} return config ;} /***** convert a IPv4 address from an inetaddress to an integer * @ Param inetaddr is an inetaddress corresponding to the IPv4 address * @ return the IP address as an integer in network byte order */public static int inetaddresstoint (inetaddress inetaddr) throws illegalargumentexception {byte [] DDR = inetaddr. getaddress (); If (ADDR. length! = 4) {Throw new illegalargumentexception ("not an IPv4 address");} return (ADDR [3] & 0xff) <24) | (ADDR [2] & 0xff) <16) | (ADDR [1] & 0xff) <8) | (ADDR [0] & 0xff );} public static void Merge (string assign, wificonfiguration wificonf) throws securityexception, writable, writable {setenumfield (wificonf, assign, "ipassignment");} public static void setenumfield (Object OBJ, string Value, string name) throws securityexception, nosuchfieldexception, illegalargumentexception, illegalaccessexception {field F = obj. getclass (). getfield (name); F. set (OBJ, enum. valueof (class <Enum>) F. getType (), value);} public static void setipaddress (inetaddress ADDR, int prefixlength, wificonfiguration wificonf) throws securityexception, expiration, classnotfoundexception, instantiationexception, invocationtargetexception {object linkproperties = getfield (wificonf, "linkproperties"); If (linkproperties = NULL) return; Class laclass = Class. forname ("android.net. linkaddress "); constructor laconstructor = laclass. getconstructor (new class [] {inetaddress. class, Int. class}); object linkaddress = laconstructor. newinstance (ADDR, prefixlength); arraylist mlinkaddresses = (arraylist) getdeclaredfield (linkproperties, "mlinkaddresses"); mlinkaddresses. clear (); mlinkaddresses. add (linkaddress);} public static void setgateway (inetaddress gateway, wificonfiguration wificonf) throws securityexception, expiration, nosuchfieldexception, expiration, classnotfoundexception, nosuchmethodexception, instantiationexception, invocationtargetexception {object linkproperties = getfield (wificonf, "linkproperties"); If (linkproperties = NULL) return; Class routeinfoclass = Class. forname ("android.net. routeinfo "); constructor routeinfoconstructor = routeinfoclass. getconstructor (new class [] {inetaddress. class}); object routeinfo = routeinfoconstructor. newinstance (GATEWAY); arraylist mroutes = (arraylist) getdeclaredfield (linkproperties, "mroutes"); mroutes. clear (); mroutes. add (routeinfo);} public static void setdns (inetaddress DNS, wificonfiguration wificonf) throws securityexception, response, nosuchfieldexception, response {object linkproperties = getfield (wificonf, "linkproperties "); if (linkproperties = NULL) return; arraylist <inetaddress> mdnses = (arraylist <inetaddress>) getdeclaredfield (linkproperties, "mdnses"); mdnses. clear (); // or add a new DNS address, Here I just want to replace dns1mdnses. add (DNS);} public static object getfield (Object OBJ, string name) throws securityexception, nosuchfieldexception, illegalargumentexception, illegalaccessexception {field F = obj. getclass (). getfield (name); object out = f. get (OBJ); Return out;} public static object getdeclaredfield (Object OBJ, string name) throws securityexception, nosuchfieldexception, illegalargumentexception, illegalaccessexception {field F = obj. getclass (). getdeclaredfield (name); F. setaccessible (true); object out = f. get (OBJ); Return out;} // public void editstaticwificonfig (final scanresult Sr, string PWD, string IP, string gateway, int prefixlength, string DNS) throws exception {// wificonfiguration historywificonfig = gethistorywificonfig (Sr. SSID); // If (historywificonfig = NULL) {// historywificonfig = createcomwificonfig (Sr. SSID, PWD); // int netid = mwifimanager. addnetwork (historywificonfig); // mwifimanager. enablenetwork (netid, true); //} // setipassignment ("static", historywificonfig ); // "static" or "DHCP" for Dynamic Setting // setipaddress (inetaddress. getbyname (IP), prefixlength, historywificonfig); // setgateway (inetaddress. getbyname (GATEWAY), historywificonfig); // setdns (inetaddress. getbyname (DNS), historywificonfig); // mwifimanager. updatenetwork (historywificonfig); // apply the setting //} // public void editdhcpwificonfig (final scanresult Sr, string PWD) throws exception {// wificonfiguration historywificonfig = reverse (Sr. SSID); // If (historywificonfig = NULL) {// historywificonfig = createcomwificonfig (Sr. SSID, PWD); // int netid = mwifimanager. addnetwork (historywificonfig); // mwifimanager. enablenetwork (netid, true); // setipassignment ("DHCP", historywificonfig ); // "static" or "DHCP" for Dynamic Setting /// mwifimanager. updatenetwork (historywificonfig); // apply the setting //}}
Note the advanced options in the class. Set the IP address when connecting to wifi. Remember wifimanager. updatenetwork (wificonfig );
Boolean Bret = wifimanager. enablenetwork (netid, true); the second parameter "true" indicates that if you have already connected to a wi-fi, you must force the connection to your own Wi-Fi, this parameter must be set to true. Otherwise, the original WiFi is connected.
Call this example
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);WifiConnect wifi = new WifiConnect(wifiManager);wifi.Connect("wifiName", "wifipPassword",WifiCipherType.WIFICIPHER_WPA);
Required Permissions
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /><uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" /><uses-permission android:name="android.permission.WAKE_LOCK" />
How to monitor the status of WiFi in Broadcast
Broadcast receiving Class
Package rodar. RGS. conference. utils; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android.net. networkinfo; import android.net. wiFi. wifiinfo; import android.net. wiFi. wifimanager; import android. OS. bundle; import android. OS. parcelable; import android. util. log; public class wifistatereceiver extends broadcastreceiver {// 0 --> wifi_state_disabling/ /1 --> wifi_state_disabled // 2 --> wifi_state_enabling // 3 --> wifi_state_enabled // 4 --> reply @ overridepublic void onreceive (context, intent) {// todo auto-generated method stubbundle bundle = intent. getextras (); int oldint = bundle. getint ("previus_wifi_state"); int newint = bundle. getint ("wifi_state"); system. out. println (">>> oldint =" + oldint + ", newint =" + newint); // string Oldstr = (oldint> = 0 & oldint <wifi_states.length )? Wifi_states [oldint]: "? "; // String newstr = (newint> = 0 & oldint <wifi_states.length )? Wifi_states [newint]: "? "; // Log. E ("", "olds =" + oldstr + ", news =" + newstr); // If (newint = wifimanager. wifi_state_disabled | newint = wifimanager. wifi_state_enabled) {// onwifistatechange (); // define this function elsewhere! //} Else if (newint = wifimanager. wifi_state_disabling | // newint = wifimanager. wifi_state_enabling) // {// chkbox_wifi.settext (newstr); //} else {// newstr + = "(is wpa_supplicant.conf readable ?) "; // Chkbox_wifi.settext (newstr); //} wifimanager = (wifimanager) context. getsystemservice (context. wifi_service); wifiinfo info = wifimanager. getconnectioninfo (); system. out. println (">>> onreceive. wifiinfo = "+ info. tostring (); system. out. println (">>> onreceive. SSID = "+ info. getssid (); // If (! Info. getssid (). equals ("rodar") {// wificonnect WiFi = new wificonnect (wifimanager); // wifi. connect ("rodar", "rodar.5779858", // wificiphertype. wificipher_wpa); // system. out. println (">>> onreceive. ssid1 = "+ info. getssid (); //} If (wifimanager. network_state_changed_action.equals (intent. getaction () {parcelable parcelableextra = intent. getparcelableextra (wifimanager. extra_network_info); If (null! = Parcelableextra) {networkinfo = (networkinfo) parcelableextra; Switch (networkinfo. getstate () {case connected: log. E ("apactivity", "connected"); break; Case connecting: log. E ("apactivity", "connecting"); break; Case disconnected: log. E ("apactivity", "disconnected"); break; Case disconnecting: log. E ("apactivity", "disconnecting"); break; Case susponded: log. E ("apactivity", "suspende D "); break; Case unknown: log. E ("apactivity", "unknown"); break; default: Break ;}}/// display the WiFi status and IP Address: // public static string stringizeip (int ip) {// int ip4 = (ip> 24) & 0x000000ff; // int IP3 = (ip> 16) & 0x000000ff; // int ip2 = (ip> 8) & 0x000000ff; // int IP1 = IP & 0x000000ff; // return integer. tostring (IP1) + ". "+ ip2 + ". "+ IP3 + ". "+ ip4; //} // Private void onwifistatechange () {// strin G ip_str = ""; // wifiinfo info = mmainwifi. getconnectioninfo (); // If (info! = NULL) {// int ipaddr = info. getipaddress (); // ip_str = "(IP =" + stringizeip (ipaddr) + ")"; //} // If (mmainwifi. iswifienabled () = true) // chkbox_wifi.settext ("WiFi is on [" + ip_str + "]"); // else // chkbox_wifi.settext ("WiFi is off "); ////}}
Generally, registering or canceling a broadcast is in onstart and onstop.
Wifistatereceiver listener; @ overrideprotected void onstart () {// register the network listener wifistatereceiver = new wifistatereceiver (); intentfilter filter = new intentfilter (); filter. addaction (wifimanager. wifi_state_changed_action); filter. addaction (wifimanager. network_state_changed_action); registerreceiver (wifistatereceiver, filter); super. onstart () ;}@ overrideprotected void onstop () {// unregisterreceiver (wifistatereceiver); super. onstop ();}
You can check whether the Wi-Fi switch or connection status of broadcast monitoring is enabled.
Http://www.cnblogs.com/wanghafan/archive/2013/01/10/2855096.html