在网上参阅相关资料后,简单修改提炼,完成自己想要的简单开发实例,记之以备查阅。
主要功能:turn on wifi,scan wifi 热点,锁定wifi连接,监听wifi打开/关闭及网络连接/断开的系统消息,根据wifi加密类型自动连接(注:存在的问题有,1.在Android 4.x的设备上,无密码与WPA加密类型验证OK,但Android5.x的设备上却没有成功,不确定什么原因;2. WPA2的密码类型还没弄 )。
package com.example.wifitest;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
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 {
private static final String TAG = "wifi";
private static final int NOPASSWORD = 0;
private static final int PASSWORD_WPA = 1;
private static final int PASSWORD_WEP = 2;
private static final int PASSWORD_WPA2 = 3;
// 定义WifiManager对象
private WifiManager mWifiManager;
// 定义一个WifiLock
private WifiLock mWifiLock;
private String mSSID;
private int delSSID;
private String mPassword;
private Context mContext;
private ConnectivityManager networkManager;
// 构造器
public WifiAdmin(Context context) {
// 取得WifiManager对象
mWifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
networkManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
mContext = context;
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
context.registerReceiver(wifiNetStateReceiver, filter);
}
// 打开WIFI
public boolean openWifi() {
if (mWifiManager == null)
return false;
if (!mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(true);
}
return true;
}
// 关闭WIFI
public void closeWifi() {
if (mWifiManager != null && 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");
}
private BroadcastReceiver wifiNetStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equals(
WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo info = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
Log.d(TAG, mSSID + " connect failure!");
mWifiManager.removeNetwork(delSSID);
scanWifi();
mContext.unregisterReceiver(wifiNetStateReceiver);
} else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
Log.d(TAG, mSSID + " connect success!");
mContext.unregisterReceiver(wifiNetStateReceiver);
}
}
if (intent.getAction()
.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifistate = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_DISABLED);
if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
Log.d(TAG, " turn off wifi!");
} else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
Log.d(TAG, " turn on wifi!");
}
}
}
};
private BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
boolean found = false;
List mWifiScanResultLists;
if (intent.getAction().equals(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
mWifiScanResultLists = mWifiManager.getScanResults();
if (mWifiScanResultLists != null) {
for (ScanResult wifiScanResultList : mWifiScanResultLists) {
Log.d(TAG, " wifiScanResultList.SSID:"
+ wifiScanResultList.SSID);
if (wifiScanResultList.SSID.equals(mSSID)) {
found = true;
connectToTarget(wifiScanResultList.capabilities);
Log.d(TAG, "found " + mSSID + " in scan result!");
mContext.unregisterReceiver(wifiScanReceiver);// 取消监听
break;
}
}
}
if (!found) {
Log.d(TAG, "not found " + mSSID + " in scan result!");
}
}
}
};
private WifiConfiguration createWifiCfg(String ssid, String password,
int method) {
// closeWifi();
Log.d(TAG, " createWifiCfg..........................");
WifiConfiguration wifiCfg = new WifiConfiguration();
wifiCfg.allowedAuthAlgorithms.clear();
wifiCfg.allowedGroupCiphers.clear();
wifiCfg.allowedKeyManagement.clear();
wifiCfg.allowedPairwiseCiphers.clear();
wifiCfg.allowedProtocols.clear();
wifiCfg.SSID = "\"" + ssid + "\"";
switch (method) {
case NOPASSWORD:/* no password */
Log.d(TAG, " createWifiCfg........no password ");
wifiCfg.wepKeys[0] = "";
wifiCfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiCfg.wepTxKeyIndex = 0;
break;
case PASSWORD_WPA:/* have password :WPA */
Log.d(TAG, " createWifiCfg.........have password :WPA");
wifiCfg.preSharedKey = "\"" + password + "\"";
wifiCfg.hiddenSSID = true;
wifiCfg.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiCfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiCfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiCfg.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiCfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// wifiCfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
// wifiCfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiCfg.status = WifiConfiguration.Status.ENABLED;
break;
case PASSWORD_WEP:/* have password :WEP */
Log.d(TAG, " createWifiCfg.........have password :WEP");
wifiCfg.preSharedKey = "\"" + password + "\"";
wifiCfg.hiddenSSID = true;
wifiCfg.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
wifiCfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiCfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiCfg.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP40);
wifiCfg.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
wifiCfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiCfg.wepTxKeyIndex = 0;
break;
default:
wifiCfg = null;
break;
}
return wifiCfg;
}
private WifiConfiguration isConfigHotSpot() {
List mWifiHotSpotLists = mWifiManager
.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : mWifiHotSpotLists) {
if (wifiConfiguration.SSID.equals("\"" + mSSID + "\"")) {
Log.d(TAG, "before have cfg this hotspot:"
+ wifiConfiguration.SSID);
return wifiConfiguration;
}
}
return null;
}
private void connectToTarget(String capability) {
int mNetworkID;
int password_type = 0;
WifiConfiguration mTargetWifiCfg;
if (capability != null) {
if (capability.contains("WPA2") || capability.contains("wpa2")) {
password_type = PASSWORD_WPA2;
} else if (capability.contains("WPA") || capability.contains("wpa")) {
password_type = PASSWORD_WPA;
} else if (capability.contains("WEP") || capability.contains("wep")) {
password_type = PASSWORD_WEP;
} else {
password_type = NOPASSWORD;
}
}
mTargetWifiCfg = createWifiCfg(mSSID, mPassword, password_type);
mNetworkID = mWifiManager.addNetwork(mTargetWifiCfg);
mWifiManager.enableNetwork(mNetworkID, true);
mWifiManager.reassociate();
}
private boolean wifiNetworkAvailable() {
boolean NetworkFlag = false;
boolean wifiNetworkFlag = false;
State wifi = null;
// 去进行判断网络是否连接
if (networkManager.getActiveNetworkInfo() != null) {
NetworkFlag = networkManager.getActiveNetworkInfo().isAvailable();
}
if (NetworkFlag) {
wifi = networkManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
wifiNetworkFlag = true;
}
}
return wifiNetworkFlag;
}
private synchronized void scanWifi() {
mContext.registerReceiver(wifiScanReceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// 开始搜索,当搜索到可用的wifi时,将发送WifiManager.SCAN_RESULTS_AVAILABLE_ACTION的广播
mWifiManager.startScan();
}
private boolean currentWifi() {
WifiInfo info = mWifiManager.getConnectionInfo();
return info.getSSID().equals("\"" + mSSID + "\"") ? true : false;
}
public synchronized void connectToTargetWifi(String ssid, String password) {
mSSID = ssid;
mPassword = password;
WifiConfiguration mWifiConfiguration;
if (openWifi()) {
// 判断是否已经配置,并且尝试连接
mWifiConfiguration = isConfigHotSpot();
if (mWifiConfiguration != null) {
// 判断该SSID是否已经连接
if (wifiNetworkAvailable() && currentWifi()) {
return;
} else {
mWifiManager.enableNetwork(mWifiConfiguration.networkId,
true);
if (mWifiManager.reconnect()) {
// 注册消息通知
mContext.registerReceiver(
wifiNetStateReceiver,
new IntentFilter(
WifiManager.NETWORK_STATE_CHANGED_ACTION));
delSSID = mWifiConfiguration.networkId;
return;
} else {
mWifiManager
.removeNetwork(mWifiConfiguration.networkId);
}
}
}
scanWifi();
}
}
}