安卓版本:4.4.2 运行平台:广州微嵌安卓工业平板
1、安卓使用wifi模块需在AndroidMainfest.xml声明权限:允许程序改变Wi-Fi连接状态 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>允许程序访问Wi-Fi网络状态信息 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>2、获取WifiManager的实例,用于操作wifi:wifiManager = (WifiManager)getSystemService(Service.WIFI_SERVICE);3、打开或关闭wifi//isChecked为true表示打开wifi,false关闭WiFiif(!wifiManager.wifiEnable(isChecked)){ Toast.makeText(MainActivity.this,"WifisetEnabledfaled", Toast.LENGTH_SHORT).show();;}//获取WiFi当前的状态switch(wifiManager.getWifiState()){ //wifi处于关闭状态 case WifiManager.WIFI_STATE_DISABLED: enableSwitch.setChecked(false); break; //wifi处于打开状态 case WifiManager.WIFI_STATE_ENABLED: enableSwitch.setChecked(true); //该方法用于开始扫描附近的wifi热点 wifiManager.startScan(); break;}4、注册wifi的相应广播监听wifi的状态改变://扫描到可用的wifi热点WifiManager.SCAN_RESULTS_AVAILABLE_ACTION//wifi状态改变WifiManager.WIFI_STATE_CHANGED_ACTION//wifi请求连接成功或失败WifiManager.SUPPLICANT_STATE_CHANGED_ACTION//wifi连接或断开状态改变,ConnectivityManager.CONNECTIVITY_ACTION//wifi热点状态改变"android.net.wifi.WIFI_AP_STATE_CHANGED"定义BroadcastReceiver接收广播:class WifiReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { //扫描到可用热点 if (intent.getAction().equals( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { //获取最近一次扫描到的wifi列表 resultList = wifiManager.getScanResults(); String[] result = mywifi.getString(resultList); int i=0; for(ScanResult scan:resultList){ //判断是否已保存了连接信息 if(mywifi.isSaveConfigtion(scan.SSID)!=null){ result[i] += ":已保存"; } i++; } } //wifi或热点的状态发生改变 else if(intent.getAction() .equals(WifiManager.WIFI_STATE_CHANGED_ACTION)|| intent.getAction() .equals("android.net.wifi.WIFI_AP_STATE_CHANGED")) { //获取wifi或热点当前的状态 switch(intent.getIntExtra("wifi_state", 0)){ //wifi状态变成关闭 case 1: adapter.clear(); stateText.setText("Wifi已关闭"); break; //WiFi状态变成打开 case 3: stateText.setText("Wifi已打开"); break; //热点状态变成打开 case 13 apstateText.setText("热点已打开"); break; //热点状态变成关闭 case 11: apstateText.setText("热点已关闭"); break; default: Log.d("STATE",String.valueOf(intent.getIntExtra("wifi_state", 0))); break; } } //连接状态发生改变 else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { boolean b = false; //获取当前的连接状态 boolean a = intent.getBooleanExtra("noConnectivity", b); if(!a) { //wifi连接成功,获取连接的wifi属性 System.out.println("连接成功"); } else { //wifi已断开连接 System.out.println("断开连接"); } } //wifi连接请求成功或失败 else if(intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { //获取连接wifi属性跟请求连接状态 WifiInfo info = wifiManager.getConnectionInfo(); SupplicantState state = info.getSupplicantState(); int flag =0; boolean connectflag = false; //连接请求成功 if (state == SupplicantState.COMPLETED) { Log.i("WifiReceiver", "(验证成功)"); SSIDText.setText(info.getSSID().substring(1,info.getSSID().length()-1)); //保存连接wifi信息 wifiManager.saveConfiguration(); flag =1; } //获取请求失败的错误值,判断是否属于验证失败 int errorCode = intent.getIntExtra( WifiManager.EXTRA_SUPPLICANT_ERROR, -1); if (errorCode == WifiManager.ERROR_AUTHENTICATING) { Log.i("WifiReceiver", "(验证失败)"); } } } }5、在扫描到wifi后获取wifi的具体属性://参数:扫描到的wifi列表public String[] getString(List<ScanResult> wifiList) { ArrayList<String> listStr = new ArrayList<String>(); for (int i = 0; i < wifiList.size(); i++) { /*SSID:wifi的标示符,也就是名字 *capabilities:描述接入点支持的身份验证、密钥管理和加密方案 *level:wifi的信号强度 *WifiManager.calculateSignalLevel:将信号强度转换成信号等级 */ listStr.add(scan.SSID+":" +scan.capabilities+":" +String.valueOf(WifiManager.calculateSignalLevel(scan.level, 5))); } return listStr.toArray(new String[0]); }6、获取当前wifi连入点的一些常用信息WifiInfo connectInfo = wifiManager.getConnectionInfo();//连接wifi的名字connectInfo.getSSID();//wifi的连接速度跟单位connectInfo.getLinkSpeed();connectInfo.LINK_SPEED_UNITS;//连接wifi的ip地址connectInfo.getIpAddress();//用下面的转换方法将connectInfo.getIpAddress()转换成Stringpublic String intToIp(int i) {return ((i >> 24 ) & 0xFF ) + "." + ((i >> 16 ) & 0xFF) + "." + ((i >> 8 ) & 0xFF) + "." + ( i & 0xFF) ; } 7、创建wifi信息用于wifi连接,分为无密码、WPA两种: /*无密码连接: *SSID:wifi的标识符 *config:用于wifi连接的wifi信息 */ String SSID = ssid; WifiConfiguration config = new WifiConfiguration(); config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); config.SSID = "\"" + SSID + "\""; 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); /*有密码连接: *SSID:wifi的标识符 *password:wifi密码 *config:用于wifi连接的wifi信息 */ String gol_password = password; WifiConfiguration config = new WifiConfiguration(); config.SSID = "\"" + ssid + "\""; config.preSharedKey = "\"" + gol_password + "\""; config.hiddenSSID = true; config.status = WifiConfiguration.Status.ENABLED; config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.TKIP); config.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.CCMP); config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); //使用上面新建的WifiConfiguration config连接wifi: int wcgID = wifiManager.addNetwork(wifiConfig); //连接成功返回true,失败返回false boolean flag = wifiManager.enableNetwork(wcgID, true);8、wifi断开连接://SSID:wifi的标示符public boolean disconnectWifi(String SSID){ List<WifiConfiguration> existingConfigs = null; existingConfigs = wifiManager.getConfiguredNetworks();; for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\"" + SSID + "\"")) { if(wifiManager.disableNetwork(existingConfig.networkId)) { return true; }else break; } } return false;}9、判断wifi信息是否已保存:public WifiConfiguration isSaveConfigtion(String SSID){ List <WifiConfiguration> existingConfigs = null; existingConfigs = wifiManager.getConfiguredNetworks();; for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\"" + SSID + "\"")) { return existingConfig; } } return null;}10、删除保存的wifi信息:public boolean removeWifi(String SSID){ List<WifiConfiguration> existingConfigs; existingConfigs= wifiManager.getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\"" + SSID + "\"")) { return wifiManager.removeNetwork(existingConfig.networkId); } } return false;}至此wifi的打开、关闭、扫描、连接、断开等基本功能的开发就基本结束了,但是在日常的wifi使用中,我们不仅仅只是连接热点,有时也会开启安卓上的本地热点供其它安卓设备连接,所以下面的部分就是设置本地的wifi热点信息并打开等功能。11、热点跟wifi不能同时使用,所以在打开热点前需先关闭掉wifi//先判断wifi是否处于打开的状态,如果是则先关闭再打开热点if(wifiManager.isWifiEnabled()){ wifiManager.setWifiEnabled(false); Toast.makeText(MainActivity.this, "关闭当前wifi,创建热点", Toast.LENGTH_SHORT).show();}创建热点信息:分为有密码、无密码/*无密码热点:*SSID:热点名字*config:热点信息*/WifiConfiguration config = new WifiConfiguration();config.SSID = ssid;config.wepTxKeyIndex = 0; config.wepKeys[0] = "";config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);config.wepTxKeyIndex = 0;/*有密码热点:*SSID:热点名字*password:热点密码*config:热点信息*/config.hiddenSSID = true;config.preSharedKey = password;config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);使用上面创建的热点信息打开热点//config:热点信息,打开热点Method method1 = null; try { method1 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); method1.invoke(wifiManager, config, true); } catch (Exception e) { e.printStackTrace(); }//判断热点是否处于打开状态:try { Method method = wifiManager.getClass().getMethod("isWifiApEnabled"); method.setAccessible(true); return (Boolean) method.invoke(wifiManager); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace();} catch (Exception e) { e.printStackTrace();}//关闭热点,先判断热点是否已被打开,是则关闭 if (isWifiApEnabled(wifiManager)) { Method method = wifiManager.getClass().getMethod("getWifiApConfiguration"); method.setAccessible(true); WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager); Method method2 =wifiManager.getClass() .getMethod("setWifiApEnabled",WifiConfiguration.class, boolean.class); method2.invoke(wifiManager, config, false);}到了这里安卓的wifi使用就已完成了,包括了wifi跟热点两大部分,wifi部分主要包括扫描、配置、连接断开等,热点部分主要是配置热点信息并打开。