关于wifi连接机制以及WifiManager的使用和监听wifi的方式
Posted da_caoyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于wifi连接机制以及WifiManager的使用和监听wifi的方式相关的知识,希望对你有一定的参考价值。
啥也不说,先贴上代码:
package com.everyoo.utils;
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 com.everyoo.wifidemon.Constants;
import java.util.List;
/**
* Created by yuanpeikai on 2015/10/7.
*/
public class WifiUtil
private final String TAG = "WifiUtil ";
// 定义WifiManager对象
private WifiManager mWifiManager;
// 定义WifiInfo对象
private WifiInfo mWifiInfo;
// 扫描出的网络连接列表
private List<ScanResult> mWifiList;
// 网络连接列表
private List<WifiConfiguration> mWifiConfiguration;
// 定义一个WifiLock
WifiManager.WifiLock mWifiLock;
private static WifiUtil wifiUtil;
private Context mContext;
// 构造器
private WifiUtil(Context context)
mContext = context;
// 取得WifiManager对象
mWifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
// 取得WifiInfo对象
mWifiInfo = mWifiManager.getConnectionInfo();
public static synchronized WifiUtil getInstance(Context context)
if (wifiUtil == null)
wifiUtil = new WifiUtil(context);
return wifiUtil;
// 打开WIFI
public void openWifi()
if (!mWifiManager.isWifiEnabled())
mWifiManager.setWifiEnabled(true);
// 关闭WIFI
public void closeWifi()
if (mWifiManager.isWifiEnabled())
mWifiManager.setWifiEnabled(false);
public void forgetWifi()
List<WifiConfiguration> configurations = mWifiManager.getConfiguredNetworks();
if (configurations != null && configurations.size() > 0)
for (int i = 0; i < configurations.size(); i++)
System.out.println("configuration ssid = " + configurations.get(i).SSID);
mWifiManager.removeNetwork(configurations.get(i).networkId);
mWifiManager.saveConfiguration();
else
System.out.println("configurations is null");
// 检查当前WIFI状态
public int checkState()
return mWifiManager.getWifiState();
// 锁定WifiLock
public void acquireWifiLock()
mWifiLock.acquire();
// 解锁WifiLock
public void releaseWifiLock()
// 判断时候锁定
if (mWifiLock.isHeld())
mWifiLock.release();
// 创建一个WifiLock
public void creatWifiLock(int lockType, String tag)
mWifiLock = mWifiManager.createWifiLock(lockType, tag);
mWifiLock.setReferenceCounted(false);// false:不计数锁,即无论调用多少次acquire(),只要调用一次release()即可解锁。
// 判断网络是否连接
public boolean isConnecting(Context context)
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null)
if (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING)
return true;
return false;
/**
* 扫描wifi列表
*/
public void startScan()
try
Thread.sleep(2000);
catch (InterruptedException e)
e.printStackTrace();
mWifiManager.startScan();
// 得到扫描结果
mWifiList = mWifiManager.getScanResults();
// 得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
// 得到网络列表
public List<ScanResult> getWifiList()
return mWifiList;
// 得到配置好的网络
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 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 boolean addNetwork(WifiConfiguration wcg)
int wcgID = mWifiManager.addNetwork(wcg);
boolean b = mWifiManager.enableNetwork(wcgID, false);
mWifiManager.saveConfiguration();
System.out.println("a--" + wcgID);
System.out.println("b--" + b);
return b;
// 断开指定ID的网络
public void disconnectWifi(int netId)
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
//然后是一个实际应用方法,只验证过没有密码的情况:分为三种情况:1 没有密码; 2 用wep加密; 3 用wpa加密
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();
if (existingConfigs != null)
for (WifiConfiguration existingConfig : existingConfigs)
if (existingConfig.SSID.equals("\\"" + SSID + "\\""))
return existingConfig;
return null;
public boolean isExsistsWifiList(String SSID, List<ScanResult> mWifiList)
//List<ScanResult> mList = getWifiList();
if (mWifiList != null)
for (ScanResult scanResult : mWifiList)
if (scanResult.SSID.equals(SSID))
return true;
return false;
// 判断当前是否有网络
public boolean isNetworkConnected(Context context)
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null)
if (mNetworkInfo.isAvailable() && mNetworkInfo.isConnected())
return true;
return false;
public synchronized boolean connectWifi(String ssid, String pwd, int encriptionType)
openWifi();
return addNetwork(createWifiInfo(ssid, pwd, encriptionType));
public boolean isWifiConnected(Context context)
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mNetworkInfo != null && mNetworkInfo.isAvailable() && mNetworkInfo.isConnected())
System.out.println(TAG + "isWifiConnected wifi is connected");
return true;
System.out.println(TAG + "isWifiConnected wifi is disconnected");
return false;
public void getConfigurations()
List<WifiConfiguration> configurations = mWifiManager.getConfiguredNetworks();
if (configurations != null)
for (int i = 0; i < configurations.size(); i++)
WifiConfiguration wifiConfiguration = configurations.get(i);
String ssid = wifiConfiguration.SSID;
String bssid = wifiConfiguration.BSSID;
/**
* 判断wifi的加密方式
*/
public void parseWifiEncryption()
int times = 0;
int LAST_TIMES = 5;
while (times < LAST_TIMES)
times++;
openWifi();
startScan();
List<ScanResult> scanResultList = getWifiList();
if (scanResultList != null)
for (ScanResult scanResult : scanResultList) // 如果没有扫描到,默认加密方式是WPA
if (Constants.wifiSsid != null && Constants.wifiSsid.equals(scanResult.SSID))
String encryption = scanResult.capabilities;
if (encryption != null)
if (encryption.contains("WPA") || encryption.contains("wpa"))
LogUtil.println(TAG + "judgeEncryption", " wap 方式加密");
Constants.wifiEncription = 3;
return;
else if (encryption.contains("WEB") || encryption.contains("web"))
LogUtil.println(TAG + "judgeEncryption", " web 方式加密");
Constants.wifiEncription = 2;
return;
else
LogUtil.println(TAG + "judgeEncryption", " 没有加密");
Constants.wifiEncription = 1;
return;
else
LogUtil.println(TAG + "judgeEncryption", "用户传来的wifi信息不存在或wifi列表中没有发现");
try
Thread.sleep(1000);
catch (InterruptedException e)
e.printStackTrace();
else
LogUtil.println(TAG + "judgeEncryption", " scanResult is null");
try
Thread.sleep(2000);
catch (InterruptedException e)
e.printStackTrace();
/**
* 连接wifi
*/
public void connectWifi()
if (!Constants.wifiSsid.equals("") && !Constants.userId.equals(""))
boolean isConnected = false;
int connectTimes = 0;
while (!isConnected && connectTimes < 10)
connectTimes++;
isConnected = wifiUtil.connectWifi(Constants.wifiSsid, Constants.wifiPwd, Constants.wifiEncription);
if (!isConnected)
try
Thread.sleep(2000);
catch (InterruptedException e)
e.printStackTrace();
if (connectTimes >= 10)
LogUtil.println(TAG + "connectWifi", "wifi is unavailable");
RestartAppUtil.restartApp(mContext, 0);
else
LogUtil.println(TAG + "connectWifi", " 用户信息不完整!");
RestartAppUtil.restartApp(mContext, 0);
以上代码是几乎WifiManager所有的方法,百度一搜几乎都能搜到,我做了一下整理,只不过比较全一些。
关键也就是这个类,你可以任意使用。
这个是监听wifi网络的三种方式,还是先上代码:
package com.everyoo.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import com.everyoo.utils.LogUtil;
import com.everyoo.utils.WifiUtil;
/**
* Android wifi状态三种广播
* Created by yuanpeikai on 2016/10/9.
*/
public class NetworkReceiver extends BroadcastReceiver
private final String TAG = "NetworkReceiver ";
@Override
public void onReceive(Context context, Intent intent)
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) //这个监听wifi的打开与关闭,与wifi的连接无关
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
switch (wifiState)
case WifiManager.WIFI_STATE_DISABLED:
LogUtil.println(TAG + "onReceive ", "wifi has been closed");
WifiUtil.getInstance(context).openWifi();
break;
case WifiManager.WIFI_STATE_ENABLED:
LogUtil.println(TAG + "onReceive ", "wifi has been opened");
break;
else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) // 这个监听wifi的连接状态
// 这个监听wifi的连接状态即是否连上了一个有效无线路由,当上边广播的状态是WifiManager.WIFI_STATE_DISABLING,和WIFI_STATE_DISABLED的时候,根本不会接到这个广播。
// 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播,当然刚打开wifi肯定还没有连接到有效的无线
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED))
LogUtil.println(TAG + "onReceive ", "wifi has been disconnected");
else if (info.getState().equals(NetworkInfo.State.CONNECTED))
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
LogUtil.println(TAG + "onReceive ", "wifi has been connected to" + wifiInfo.getSSID());
LogUtil.println(TAG + "onReceive", "info.getState = " + info.getState());
else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) //这个监听网络连接的设置,包括wifi和移动数据的打开和关闭。.
//最好用的还是这个监听。wifi如果打开,关闭,以及连接上可用的连接都会接到监听。见log
// 这个广播的最大弊端是比上边两个广播的反应要慢,如果只是要监听wifi,我觉得还是用上边两个配合比较合适
// if (Constants.isBind)
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null)
if (networkInfo.isAvailable() && networkInfo.isConnected())
if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET)
System.out.println("NetworkReceiver ethernet network is connected");
else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
System.out.println("NetworkReceiver wifi network is connected");
else if (networkInfo.isConnectedOrConnecting())
System.out.println("NetworkReceiver network is connecting");
else
System.out.println("NetworkReceiver network is unKnow");
else
System.out.println("NetworkReceiver network is null");
//
源码demon地址下载
注释说的都比较清楚了,我也不多说了。为防止忘记,先记下来了,有点乱,以后还会好好整理的。
以上是关于关于wifi连接机制以及WifiManager的使用和监听wifi的方式的主要内容,如果未能解决你的问题,请参考以下文章