android开发 wifi开发工具类

时间:2021-02-15 06:16:54
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
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.util.Log; public class CusWifiUtil { // private static CusWifiUtil mWifiUtils = null;
private List<WifiConfiguration> mWifiConfiguration;
private WifiInfo mWifiInfo;
private DhcpInfo mDhcpInfo;
private List<ScanResult> mWifiList;
private WifiManager.WifiLock mWifiLock;
public WifiManager mWifiManager;
private NetworkInfo mNetworkInfo; private String TAG = "WifiUtils";
private Context mContext; public CusWifiUtil(Context paramContext) {
mContext = paramContext;
mWifiManager = (WifiManager) paramContext
.getSystemService(Context.WIFI_SERVICE);
mDhcpInfo = mWifiManager.getDhcpInfo();
mWifiInfo = mWifiManager.getConnectionInfo();
mNetworkInfo = ((ConnectivityManager) paramContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
} public void setNewWifiManagerInfo() {
mWifiInfo = mWifiManager.getConnectionInfo();
mDhcpInfo = mWifiManager.getDhcpInfo();
} // public static WifiUtils getInstance(Context paramContext) {
// if (mWifiUtils == null)
// mWifiUtils = new WifiUtils(paramContext);
// return mWifiUtils;
// } private WifiConfiguration isExsits(String paramString) {
Iterator<WifiConfiguration> localIterator = mWifiManager
.getConfiguredNetworks().iterator();
WifiConfiguration localWifiConfiguration;
do {
if (!localIterator.hasNext())
return null;
localWifiConfiguration = (WifiConfiguration) localIterator.next();
} while (!localWifiConfiguration.SSID.equals("\"" + paramString + "\""));
return localWifiConfiguration;
} /**
* 获取热点状态
*
* @return boolean值,对应热点的开启(true)和关闭(false)
*/
public boolean getWifiApState() {
try {
int i = ((Integer) mWifiManager.getClass()
.getMethod("getWifiApState", new Class[0])
.invoke(mWifiManager, new Object[0])).intValue();
return (3 == i) || (13 == i);
} catch (Exception localException) {
}
return false;
} /**
* 判断是否连接上wifi
*
* @return boolean值(isConnect),对应已连接(true)和未连接(false)
*/
public boolean isWifiConnect() {
return mNetworkInfo.isConnected();
} public void AcquireWifiLock() {
mWifiLock.acquire();
} public void CreatWifiLock() {
mWifiLock = mWifiManager.createWifiLock("Test");
} // public void OpenWifi() {
// Log.v(TAG, "OpenWifi");
// if (!mWifiManager.isWifiEnabled())
// mWifiManager.setWifiEnabled(true);
// } public void ReleaseWifiLock() {
if (mWifiLock.isHeld())
mWifiLock.release();
} public void closeWifi() {
mWifiManager.setWifiEnabled(false);
} public void connectConfiguration(int paramInt) {
if (paramInt > mWifiConfiguration.size())
return;
mWifiManager
.enableNetwork(
((WifiConfiguration) mWifiConfiguration.get(paramInt)).networkId,
true);
} public void removeNetwork(int netId) {
if (mWifiManager != null) {
mWifiManager.removeNetwork(netId);
}
} public void createWiFiAP(WifiConfiguration paramWifiConfiguration,
boolean paramBoolean) {
try {
Class<? extends WifiManager> localClass = mWifiManager.getClass();
Class[] arrayOfClass = new Class[2];
arrayOfClass[0] = WifiConfiguration.class;
arrayOfClass[1] = Boolean.TYPE;
Method localMethod = localClass.getMethod("setWifiApEnabled",
arrayOfClass);
WifiManager localWifiManager = mWifiManager;
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = paramWifiConfiguration;
arrayOfObject[1] = Boolean.valueOf(paramBoolean);
localMethod.invoke(localWifiManager, arrayOfObject);
return;
} catch (Exception localException) {
localException.printStackTrace();
}
} /**
* 用户创建热点的时候用
* @param SSID
* @param Password
* @param Type
* @return
*/
public WifiConfiguration CreateWifiInfo(String SSID, String Password,
int Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
// config.SSID = "\"" + SSID + "\"";
config.SSID = SSID; WifiConfiguration tempConfig = this.IsExsits(SSID);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
} if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 2) // WIFICIPHER_WEP
{
config.hiddenSSID = true;
// config.wepKeys[0] = "\"" + Password + "\"";
config.wepKeys[0] = Password;
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 == 3) // WIFICIPHER_WPA
{
// config.preSharedKey = "\"" + Password + "\"";
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;
}
return config;
}
/**
* 用于创建wifi并连接wifi热点,跟CreateWifiInfo差别在于双引号
* @param SSID
* @param Password
* @param Type
* @return
*/
public WifiConfiguration CreateWifiInfoForConnectAP(String SSID, String Password,int Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\""; WifiConfiguration tempConfig = this.IsExsits(SSID);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
} if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 2) // WIFICIPHER_WEP
{
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + Password + "\"";
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 == 3) // 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;
}
return config;
} public void disconnectWifi(int paramInt) {
mWifiManager.disableNetwork(paramInt);
} public String getApSSID() {
try {
Method localMethod = mWifiManager.getClass().getDeclaredMethod(
"getWifiApConfiguration", new Class[0]);
if (localMethod == null)
return null;
Object localObject1 = localMethod.invoke(mWifiManager,
new Object[0]);
if (localObject1 == null)
return null;
WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
if (localWifiConfiguration.SSID != null)
return localWifiConfiguration.SSID;
Field localField1 = WifiConfiguration.class
.getDeclaredField("mWifiApProfile");
if (localField1 == null)
return null;
localField1.setAccessible(true);
Object localObject2 = localField1.get(localWifiConfiguration);
localField1.setAccessible(false);
if (localObject2 == null)
return null;
Field localField2 = localObject2.getClass()
.getDeclaredField("SSID");
localField2.setAccessible(true);
Object localObject3 = localField2.get(localObject2);
if (localObject3 == null)
return null;
localField2.setAccessible(false);
String str = (String) localObject3;
return str;
} catch (Exception localException) {
}
return null;
} public String getBSSID() {
if (mWifiInfo == null)
return "NULL";
return mWifiInfo.getBSSID();
} public String getSSID() {
if (mWifiInfo == null)
return "NULL";
return mWifiInfo.getSSID();
} public List<WifiConfiguration> getConfiguration() {
return mWifiConfiguration;
} public String getLocalIPAddress() {
if (mWifiInfo == null)
return "NULL";
return intToIp(mWifiInfo.getIpAddress());
} public String getServerIPAddress() {
if (mDhcpInfo == null)
return "NULL";
return intToIp(mDhcpInfo.serverAddress);
} public String getMacAddress() {
if (mWifiInfo == null)
return "NULL";
return mWifiInfo.getMacAddress();
} public int getNetworkId() {
if (mWifiInfo == null)
return 0;
return mWifiInfo.getNetworkId();
} public int getWifiApStateInt() {
try {
int i = ((Integer) mWifiManager.getClass()
.getMethod("getWifiApState", new Class[0])
.invoke(mWifiManager, new Object[0])).intValue();
return i;
} catch (Exception localException) {
}
return 4;
} public WifiInfo getWifiInfo() {
return mWifiManager.getConnectionInfo();
} public List<ScanResult> getWifiList() {
return mWifiList;
} public StringBuilder lookUpScan() {
StringBuilder localStringBuilder = new StringBuilder();
for (int i = 0;; i++) {
if (i >= 2)
return localStringBuilder;
localStringBuilder.append("Index_"
+ Integer.valueOf(i + 1).toString() + ":");
localStringBuilder.append(((ScanResult) mWifiList.get(i))
.toString());
localStringBuilder.append("/n");
}
} public void setWifiList() {
mWifiList = mWifiManager.getScanResults();
Log.v(TAG, "mWifiList.size()=" + mWifiList.size());
} public void startScan() {
mWifiManager.startScan();
} public String intToIp(int paramIntip) {
return (paramIntip & 0xFF) + "." + ((paramIntip >> 8) & 0xFF) + "."
+ ((paramIntip >> 16) & 0xFF) + "."
+ ((paramIntip >> 24) & 0xFF);
} /***********************************/
// 打开WIFI
public boolean openWifi() {
mWifiManager = (WifiManager) mContext
.getSystemService(Context.WIFI_SERVICE);
if (!mWifiManager.isWifiEnabled()) {
Log.v(TAG, "打开wifi");
return mWifiManager.setWifiEnabled(true);
}
return true;
} // 添加一个网络并连接
public boolean addNetwork(WifiConfiguration wcg) {
if (!this.openWifi()) {
Log.v("addNetwork", "openWifi is false");
return false;
}
// 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
// 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
try {
// 为了避免程序一直while循环,让它睡个200毫秒在检测…… Thread.currentThread();
Thread.sleep(200);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
if (wcg == null) {
Log.v("addNetwork", "wcg == null");
return false;
} WifiConfiguration tempConfig = this.IsExsits(wcg.SSID); if (tempConfig != null) {
Log.v("addNetwork", "tempConfig != null");
mWifiManager.removeNetwork(tempConfig.networkId);
} int netID = mWifiManager.addNetwork(wcg);
Log.v("addNetwork", "netID:" + netID);
boolean bRet = mWifiManager.enableNetwork(netID, true);
if (bRet)
Log.v("addNetwork", "enableNetwork:" + bRet);
boolean bConn = mWifiManager.reconnect();
if (bConn)
Log.v("addNetwork", "reconnect:" + bConn);
long startTime = System.currentTimeMillis();
boolean IsConn = false;
while (true) {
mNetworkInfo = ((ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mNetworkInfo.isConnected()) {
IsConn = true;
break;
} else if (System.currentTimeMillis() - startTime > 3 * 1000) {
IsConn = false;
break;
}
}
return IsConn;
} private WifiConfiguration IsExsits(String SSID) {
List<WifiConfiguration> existingConfigs = mWifiManager
.getConfiguredNetworks();
if (existingConfigs == null)
return null;
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID!=null && existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
/**
* wifi热点开关
*
* @param enabled
* true:打开 false:关闭
* @return true:成功 false:失败
*/
// public boolean setWifiApEnabled(boolean enabled) {
// System.out.println(TAG + ":开启热点");
// if (enabled) { // disable WiFi in any case
// //wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi
// mWifiManager.setWifiEnabled(false);
// System.out.println(TAG + ":关闭wifi");
// }else{
// mWifiManager.setWifiEnabled(true);
// }
// try {
// //热点的配置类
// WifiConfiguration apConfig = new WifiConfiguration();
// //配置热点的名称(可以在名字后面加点随机数什么的)
// apConfig.SSID = WIFI_HOST_SSID;
// //配置热点的密码
// apConfig.preSharedKey = WIFI_HOST_PRESHARED_KEY;
// //安全:WPA2_PSK
// apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
// //通过反射调用设置热点
// Method method = wifiManager.getClass().getMethod(
// "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
// //返回热点打开状态
// return (Boolean) method.invoke(wifiManager, apConfig, enabled);
// } catch (Exception e) {
// return false;
// }
// }
}

注意:CreateWifiInfoForConnectAP 和 CreateWifiInfo的关键区别,使用时注意。不知道为什么创建热点不需要双引号,但是到连接wifi热点时却需要,有知道的童鞋麻烦告知下