1、如何正确使用WIFI工具类WifiAdmin.java:
网上很多关于WifiAdmin.java这个工具类的使用,在这里我就不多说了。这个类是一个很方便的WIFI管理工具类,很容易使用这个类来连接指定的SSID的WIFI热点,并且得到连接状态。
首先来看下这个工具类:WifiAdmin.java
package com.example.testmywifi;
import java.util.List;
import android.content.Context;
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;
public class WifiAdmin {
// 定义WifiManager对象
private WifiManager mWifiManager;
// 定义WifiInfo对象
private WifiInfo mWifiInfo;
// 扫描出的网络连接列表
private List<ScanResult> mWifiList;
// 网络连接列表
private List<WifiConfiguration> mWifiConfiguration;
// 定义一个WifiLock
WifiLock mWifiLock;
private static final String TAG = "WifiAdmin";
// 构造器
public WifiAdmin(Context context) {
// 取得WifiManager对象
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// 取得WifiInfo对象
mWifiInfo = mWifiManager.getConnectionInfo();
}
// 打开WIFI
public boolean openWifi() {
if (!mWifiManager.isWifiEnabled()) {
Log.i(TAG, "openWifi...s");
mWifiManager.setWifiEnabled(true);
Log.i(TAG, "openWifi...e");
}
startScan();
return mWifiManager.isWifiEnabled();
}
// 关闭WIFI
public void closeWifi() {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}
}
// 检查当前WIFI状态
public int checkState() {
return mWifiManager.getWifiState();
}
// 锁定WifiLock
public void acquireWifiLock() {
mWifiLock.acquire();
}
// 解锁WifiLock
public void releaseWifiLock() {
// 判断时候锁定
if (mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
// 创建一个WifiLock
public void creatWifiLock() {
mWifiLock = mWifiManager.createWifiLock("Test");
}
// 得到配置好的网络
public List<WifiConfiguration> getConfiguration() {
return mWifiConfiguration;
}
// 指定配置好的网络进行连接
public void connectConfiguration(int index) {
// 索引大于配置好的网络索引返回
if (index > mWifiConfiguration.size()) {
return;
}
// 连接配置好的指定ID的网络
mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
}
public void startScan() {
mWifiManager.startScan();
// 得到扫描结果
mWifiList = mWifiManager.getScanResults();
// 得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
}
// 得到网络列表
public List<ScanResult> getWifiList() {
return mWifiList;
}
// 查看扫描结果
public StringBuilder lookUpScan() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < mWifiList.size(); i++) {
stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
// 将ScanResult信息转换成一个字符串包
// 其中把包括:BSSID、SSID、capabilities、frequency、level
stringBuilder.append((mWifiList.get(i)).toString());
stringBuilder.append("/n");
}
return stringBuilder;
}
// 得到MAC地址
public String getMacAddress() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
}
// 得到接入点的BSSID
public String getBSSID() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
}
// 得到IP地址
public int getIPAddress() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
}
// 得到连接的ID
public int getNetworkId() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
}
// 得到WifiInfo的所有信息包
public String getWifiInfo() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
}
// 添加一个网络并连接
public void addNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
boolean b = mWifiManager.enableNetwork(wcgID, true);
System.out.println("a--" + wcgID);
System.out.println("b--" + b);
}
// 断开指定ID的网络
public void disconnectWifi(int netId) {
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
// 然后是一个实际应用方法,只验证过没有密码的情况:
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 + "\"";
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;
}
private WifiConfiguration IsExsits(String SSID) {
List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
}
其次看下这个工具类的使用:
/**
* 子类实现网络状态监听
*/
class NetworkStateChangeReceiver extends BroadcastReceiver {
private static final String TAG = "NetWorkStateChangeReceiver";
Context mContext;
public NetworkStateChangeReceiver(Context context) {
this.mContext = context;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "action:" + action);
if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
Log.i("WIFI状态", "wifiState" + wifiState);
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(ssid, password, 3));
break;
case WifiManager.WIFI_STATE_DISABLED:
showView(2);
break;
default:
Log.i(TAG, "undo");
break;
}
}
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
Log.i(TAG, "2222222222222222");
Parcelable parcelableExtra = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (parcelableExtra != null) {
NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
State state = networkInfo.getState();
boolean isConnected = state == State.CONNECTED;// 当然,这边可以更精确的确定状态
Log.i(TAG, "isConnected:" + isConnected);
if (isConnected) {
Log.i(TAG, "wifi test succ");
showView(3);
} else {
Log.i(TAG, "1111wifi test failed");
showView(2);
}
} else {
Log.i(TAG, "1111wifi test failed parcelableExtra is null");
showView(2);
}
}
}
public void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mContext.registerReceiver(this, filter);
}
}
2、注意事项:
打开WIFI后注册广播会监听到WIFI状态WifiManager.WIFI_STATE_ENABLED,于是就去使用wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(ssid, password, 3));去连接WIFI。
WIFI连接成功后通过广播监听返回WIFI状态如程序所示。
值得注意的是许多人在这里使用判断SSID的方法来判断是否连接上WIFI网络如:
if (mNetworkUtils.wifiEnabled()) {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "wifiInfo2:" + wifiInfo.toString());
Log.d(TAG, "SSID2:" + wifiInfo.getSSID());
// TODO 应用起来之后,在点击wifi测试按钮之后才插入网卡设备,apk应该放在/system/app下面才可以
if (ssid != null && ssid.replace("\"", "").equalsIgnoreCase(ConfigInfo.ssid)) {
Log.i(TAG, "Q succ");
// wifi测试成功
} else {
Log.i(TAG, "wifi disconnect! register network broadcast!");
}
}
提醒大家使用这种方法时有时连接的WIFI热点不存在也会显示成功,建议使用广播监听判断WIFI是否连接成功。
3、WIFI相关广播这里有一篇博客已经说的很清楚了,这里我就不多说了:
http://www.blogjava.net/liuyanbo/archive/2012/09/17/387882.html
4、次方法已经经过测试验证。