代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Java
】
Android WIFI工具类
作者:
/ 发布于
2018/9/1
/
749
import java.net.Inet4Address; import java.util.List; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.util.Log; import com.jczb.smartlife.common.WifiConnect.WifiCipherType; import com.jczb.smartlife.ui.PhoneRouteActivity; /** * Class Name: WifiAdmin.java * Function:Wifi连接管理工具类 * * Modifications: * * @author ZYT DateTime 2014-5-14 下午2:24:14 * @version 1.0 * */ public class WifiAdmin { // 定义一个WifiManager对象 private WifiManager mWifiManager; // 定义一个WifiInfo对象 private WifiInfo mWifiInfo; // 扫描出的网络连接列表 private List<ScanResult> mWifiList; // 网络连接列表 private List<WifiConfiguration> mWifiConfigurations; private ConnectivityManager cm; WifiLock mWifiLock; //定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况 // public enum WifiCipherType { // WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID // } public WifiAdmin(Context context) { // 取得WifiManager对象 mWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); // 取得WifiInfo对象 mWifiInfo = mWifiManager.getConnectionInfo(); } /** * Function:关闭wifi * www.javaapk.com更改 * @author ZYT DateTime 2014-5-15 上午12:17:37 * @return */ public boolean closeWifi() { if (mWifiManager.isWifiEnabled()) { return mWifiManager.setWifiEnabled(false); } return false; } /** * Gets the Wi-Fi enabled state.检查当前wifi状态 * * @return One of {@link WifiManager#WIFI_STATE_DISABLED}, * {@link WifiManager#WIFI_STATE_DISABLING}, * {@link WifiManager#WIFI_STATE_ENABLED}, * {@link WifiManager#WIFI_STATE_ENABLING}, * {@link WifiManager#WIFI_STATE_UNKNOWN} * @see #isWifiEnabled() */ public int checkState() { return mWifiManager.getWifiState(); } // 锁定wifiLock public void acquireWifiLock() { mWifiLock.acquire(); } // 解锁wifiLock public void releaseWifiLock() { // 判断是否锁定 if (mWifiLock.isHeld()) { mWifiLock.acquire(); } } // 创建一个wifiLock public void createWifiLock() { mWifiLock = mWifiManager.createWifiLock("test"); } // 得到配置好的网络 public List<WifiConfiguration> getConfiguration() { return mWifiConfigurations; } // 指定配置好的网络进行连接 public void connetionConfiguration(int index) { if (index > mWifiConfigurations.size()) { return; } // 连接配置好指定ID的网络 mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId, true); } public void startScan() { //openWifi(); mWifiManager.startScan(); // 得到扫描结果 mWifiList = mWifiManager.getScanResults(); // 得到配置好的网络连接 mWifiConfigurations = mWifiManager.getConfiguredNetworks(); } // 得到网络列表 public List<ScanResult> getWifiList() { return mWifiList; } // 查看扫描结果 public StringBuffer lookUpScan() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < mWifiList.size(); i++) { sb.append("Index_" + new Integer(i + 1).toString() + ":"); // 将ScanResult信息转换成一个字符串包 // 其中把包括:BSSID、SSID、capabilities、frequency、level sb.append((mWifiList.get(i)).toString()).append("\n"); } return sb; } public String getMacAddress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } /** * Return the basic service set identifier (BSSID) of the current access * point. The BSSID may be {@code null} if there is no network currently * connected. * * @return the BSSID, in the form of a six-byte MAC address: * {@code XX:XX:XX:XX:XX:XX} */ public String getBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } public String getSSID(){ return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID(); } public int getIpAddress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } /** * Each configured network has a unique small integer ID, used to identify * the network when performing operations on the supplicant. This method * returns the ID for the currently connected network. * * @return the network ID, or -1 if there is no currently connected network */ public int getNetWordId() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } /** * Function: 得到wifiInfo的所有信息 * * @author ZYT DateTime 2014-5-14 上午11:03:32 * @return */ public String getWifiInfo() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString(); } /** * 获得指定SSID的保护类型 * @return */ public String getWifiType(String strSSID){ startScan(); for(int i=0;i<mWifiList.size();i++){ if(mWifiList.get(i).SSID.equals(strSSID)){ String strType=mWifiList.get(i).capabilities; return strType; } } return ""; } // 添加一个网络并连接 public void addNetWork(WifiConfiguration configuration) { int wcgId = mWifiManager.addNetwork(configuration); mWifiManager.enableNetwork(wcgId, true); } // 断开指定ID的网络 public void disConnectionWifi(int netId) { mWifiManager.disableNetwork(netId); mWifiManager.disconnect(); } /** * Function: 打开wifi功能 * * @author ZYT DateTime 2014-5-14 上午11:01:11 * @return true:打开成功;false:打开失败 */ public boolean openWifi() { boolean bRet = true; if (!mWifiManager.isWifiEnabled()) { bRet = mWifiManager.setWifiEnabled(true); } return bRet; } /** * Function: 提供一个外部接口,传入要连接的无线网 * * @author ZYT DateTime 2014-5-13 下午11:46:54 * @param SSID * SSID * @param Password * @param Type * * 没密码:{@linkplain WifiCipherType#WIFICIPHER_NOPASS} * WEP加密: {@linkplain WifiCipherType#WIFICIPHER_WEP} * WPA加密: {@linkplain WifiCipherType#WIFICIPHER_WPA} * @return true:连接成功;false:连接失败 */ public boolean connect(String SSID, String Password, WifiCipherType Type) { if (!this.openWifi()) { return false; } // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句 while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { try { // 为了避免程序一直while循环,让它睡个100毫秒在检测…… Thread.currentThread(); Thread.sleep(100); } catch (InterruptedException ie) { } } WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type); // if (wifiConfig == null) { return false; } WifiConfiguration tempConfig = this.isExsits(SSID); int tempId = wifiConfig.networkId; if (tempConfig != null) { tempId = tempConfig.networkId; mWifiManager.removeNetwork(tempConfig.networkId); } int netID = mWifiManager.addNetwork(wifiConfig); // 断开连接 //mWifiManager.disconnect(); // 重新连接 // netID = wifiConfig.networkId; // 设置为true,使其他的连接断开 boolean bRet = mWifiManager.enableNetwork(netID, true); //mWifiManager.reconnect(); return bRet; } // 查看以前是否也配置过这个网络 private WifiConfiguration isExsits(String SSID) { List<WifiConfiguration> existingConfigs = mWifiManager .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.status = WifiConfiguration.Status.ENABLED; // 修改之后配置 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); } else { return null; } return config; } /** * Function:判断扫描结果是否连接上 * * @author ZYT DateTime 2014-5-14 上午11:31:40 * @param result * @return */ public boolean isConnect(Context context,ScanResult result) { if (result == null) { return false; } //获得当前已连接网络 cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); //获得网络信息 android.net.NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi==android.net.NetworkInfo.State.CONNECTING) { mWifiInfo = mWifiManager.getConnectionInfo(); String g2 = "\"" + result.SSID + "\""; if (mWifiInfo.getSSID() != null && mWifiInfo.getSSID().endsWith(g2)) { return true; } } return false; } /** * 判断指定的SSID是否已连接成功,调用该方法前提是要连接的网络enableNetwork的返回值为true * @param SSID * @return */ public boolean isWifiConnected(Context context,String SSID){ //获得当前已连接网络 cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); //获得网络信息的连接状态 android.net.NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); //如果正在连接,则让它进入循环,并睡个100ms再检测 while(wifi == android.net.NetworkInfo.State.CONNECTING ){ try { // 为了避免程序一直while循环,让它睡个100毫秒再检测…… Thread.currentThread(); Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(); } wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); } //如果连接成功,则返回真 if (wifi == android.net.NetworkInfo.State.CONNECTED ) { return true; } return false; } /** * 判断指定的SSID是否已连接成功,调用该方法前提是要连接的网络enableNetwork的返回值为true * @param SSID * @return */ public boolean isConnected(Context context,String SSID){ //获得当前已连接的网络信息 //如果不是指定的,就循环并重新获得,直到已连接的网络是指定的 //获得当前已连接网络 cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); //获得已连接的WIFI信息 //获得网络信息的连接状态 android.net.NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); System.out.print(wifi.toString()); while(wifi == android.net.NetworkInfo.State.CONNECTING ){ try { // 为了避免程序一直while循环,让它睡个100毫秒再检测…… Thread.currentThread(); Thread.sleep(100); } catch (InterruptedException ie) { } wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); } if (wifi == android.net.NetworkInfo.State.CONNECTED ) { return true; } return false; } /** * Function: 将int类型的IP转换成字符串形式的IP * * @author ZYT DateTime 2014-5-14 下午12:28:16 * @param ip * @return */ public String ipIntToString(int ip) { try { byte[] bytes = new byte[4]; bytes[0] = (byte) (0xff & ip); bytes[1] = (byte) ((0xff00 & ip) >> 8); bytes[2] = (byte) ((0xff0000 & ip) >> 16); bytes[3] = (byte) ((0xff000000 & ip) >> 24); return Inet4Address.getByAddress(bytes).getHostAddress(); } catch (Exception e) { return ""; } } public int getConnNetId() { // result.SSID; mWifiInfo = mWifiManager.getConnectionInfo(); return mWifiInfo.getNetworkId(); } /** * Function:信号强度转换为字符串 * * @author ZYT DateTime 2014-5-14 下午2:14:42 * @param level * */ public static String singlLevToStr(int level) { String resuString = "无信号"; if (Math.abs(level) > 100) { } else if (Math.abs(level) > 80) { resuString = "弱"; } else if (Math.abs(level) > 70) { resuString = "强"; } else if (Math.abs(level) > 60) { resuString = "强"; } else if (Math.abs(level) > 50) { resuString = "较强"; } else { resuString = "极强"; } return resuString; } /** *添加到网络 * @param wcg */ public boolean addNetwork(WifiConfiguration wcg) { if (wcg == null) { return false; } //receiverDhcp = new ReceiverDhcp(ctx, mWifiManager, this, wlanHandler); //ctx.registerReceiver(receiverDhcp, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); int wcgID = mWifiManager.addNetwork(wcg); boolean b = mWifiManager.enableNetwork(wcgID, true); mWifiManager.saveConfiguration(); System.out.println(b); return b; } public boolean connectSpecificAP(ScanResult scan) { //标志要连接的网络是否已经配置过 boolean networkInSupplicant = false; //连接结果 boolean connectResult = false; //得到所有网络的配置信息的集合 List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks(); // 重新连接指定AP //mWifiManager.disconnect(); //如果集合为空 if(list==null){ return false; } /********************执行连接命令************************/ //遍历配置信息的集合,如果要连接的网络的配置信息已存在,则连接该网络 for (WifiConfiguration w : list) { // 将指定AP 名字转化 // String str = convertToQuotedString(info.ssid); // if (w.BSSID != null && w.BSSID.equals(scan.BSSID)) { connectResult = mWifiManager.enableNetwork(w.networkId, true); // mWifiManager.saveConfiguration(); networkInSupplicant = true; break; } } //如果没有配置过,设置和添加配置并连接 if (!networkInSupplicant) { //配置网络信息,密码为空 WifiConfiguration config = CreateWifiInfo(scan, ""); //添加配置好的网络并连接 connectResult = addNetwork(config); } /**************以上只是根据配置执行连接指令,并不代表能够连接成功************/ return connectResult; } // 然后是一个实际应用方法,只验证过没有密码的情况: public WifiConfiguration CreateWifiInfo(ScanResult scan, String Password) { WifiConfiguration config = new WifiConfiguration(); config.hiddenSSID = false; config.status = WifiConfiguration.Status.ENABLED; if (scan.capabilities.contains("WEP")) { config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.allowedAuthAlgorithms .set(WifiConfiguration.AuthAlgorithm.OPEN); config.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.WEP104); config.SSID = "\"" + scan.SSID + "\""; config.wepTxKeyIndex = 0; config.wepKeys[0] = Password; // config.preSharedKey = "\"" + SHARED_KEY + "\""; } else if (scan.capabilities.contains("PSK")) { // config.SSID = "\"" + scan.SSID + "\""; config.preSharedKey = "\"" + Password + "\""; } else if (scan.capabilities.contains("EAP")) { config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); config.allowedAuthAlgorithms .set(WifiConfiguration.AuthAlgorithm.OPEN); config.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.TKIP); config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); config.SSID = "\"" + scan.SSID + "\""; config.preSharedKey = "\"" + Password + "\""; } else { config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.SSID = "\"" + scan.SSID + "\""; // config.BSSID = info.mac; config.preSharedKey = null; // } return config; } }
试试其它关键字
同语言下
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
可能有用的
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
贡献的其它代码
Label
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3