功能實現:控制wifi開關,連上某個特定的wifi。
首先先上個wifi工具類,此類轉載網上一人,出處不明了。
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 wifiManager; //定義幾種加密方式,一種是WEP,一種是WPA,還有沒有密碼的情況 public enum WifiCipherType { WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID }//建構函式public WifiConnect(WifiManager wifiManager){ this.wifiManager = wifiManager;}//開啟wifi功能 private boolean OpenWifi() { boolean bRet = true; if (!wifiManager.isWifiEnabled()) { bRet = wifiManager.setWifiEnabled(true); } return bRet; } //提供一個外部介面,傳入要串連的無線網 public boolean Connect(String SSID, String Password, WifiCipherType Type) { if(!this.OpenWifi()) { return false; } System.out.println(">>>wifiCon=");//開啟wifi功能需要一段時間(我在手機上測試一般需要1-3秒左右),所以要等到wifi//狀態變成WIFI_STATE_ENABLED的時候才能執行下面的語句 while(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING ) { try{ //為了避免程式一直while迴圈,讓它睡個100毫秒在檢測…… 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 {// //進階選項// 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.updateNetwork(wifiConfig); return bRet; } //查看以前是否也配置過這個網路 private WifiConfiguration IsExsits(String SSID) { List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\""+SSID+"\"")) { return existingConfig; } } return null; } private WifiConfiguration CreateWifiInfo(String SSID, String Password, WifiCipherType Type) { 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(WifiConfiguration.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.allowedGroupCiphers.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); config.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.PairwiseCipher.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 [] addr = 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 setIpAssignment(String assign, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {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,IllegalArgumentException,NoSuchFieldException,IllegalAccessException, NoSuchMethodException,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,IllegalArgumentException,NoSuchFieldException,IllegalAccessException, 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, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {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 = getHistoryWifiConfig(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//}}
類中注釋進階選項處,是串連上wifi同時自己設定ip.記得wifiManager.updateNetwork(wifiConfig);
類中boolean bRet = wifiManager.enableNetwork(netID, true); 第二個參數true表示如果當前已經有連上一個wifi,要強制連到自己設定的wifi上,此參數必須為true否則連上的還是原來的wifi.
調用此類樣本
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);WifiConnect wifi = new WifiConnect(wifiManager);wifi.Connect("wifiName", "wifipPassword",WifiCipherType.WIFICIPHER_WPA);
需要的許可權
<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" />
如何在廣播監聽wifi的狀態
廣播接收類
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 --> WIFI_STATE_UNKNOWN@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubBundle bundle = intent.getExtras(); int oldInt = bundle.getInt("previous_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 = (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 = (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 SUSPENDED: Log.e("APActivity", "SUSPENDED"); break; case UNKNOWN: Log.e("APActivity", "UNKNOWN"); break; default: break; } } }}//// 顯示Wifi狀態以及ip地址://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() {// String 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");// //}}
註冊和取消廣播一般在onstart和onstop裡
WifiStateReceiver wifiStateReceiver;@Overrideprotected void onStart() {//註冊網路監聽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();}
關於廣播監控wifi開關還是串連狀態可以看這個串連
http://www.cnblogs.com/wanghafan/archive/2013/01/10/2855096.html