目录
在Android中对Wifi操作,android本身提供了一些有用的包,在android.net.wifi包下面,主要包括以下几个类和接口:
1.导图
2.权限
在AndroidManifest.xml进行对WIFI操作的权限设置(wifi需要打开定位,所以要加上定位权限,非系统应用还需要在打开wifi前请求定位权限,否则搜索不到wifi,返回的ScanResult为空)
<!-- 以下是使用wifi访问网络所需的权限 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
3.监听广播
需要监听的广播如下:
private BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Logg.d( "action:" + action);
switch(action)
{
case WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION:
case WifiManager.LINK_CONFIGURATION_CHANGED_ACTION:
case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION:
{
isScanning = false;
List<ScanResult> srList = mStmWifiManager.getWifiList();
notifyDatasChange(sortList(srList));
}
break;
case WifiManager.WIFI_STATE_CHANGED_ACTION:
{
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.WIFI_STATE_UNKNOWN);
if(WifiManager.WIFI_STATE_ENABLED == state)
{
Logg.d("wifi state:" + state);
handleWidgetState(true);
mSearchProgress.setVisibility(View.VISIBLE);
scanWifi();
}
}
break;
case WifiManager.NETWORK_STATE_CHANGED_ACTION:
{
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
NetworkInfo.State state = info.getState();
Logg.d("state:" + state);
if(state == NetworkInfo.State.CONNECTED)
{
updateWifiState(R.string.wifi_connected,mWifiAdapter.getItemPosition(mCurSelectSsid));
//连接成功后重新刷新wifi列表
notifyDatasChange(sortList(mStmWifiManager.getWifiList()));
}else
{
NetworkInfo.DetailedState ndState = info.getDetailedState();
if(ndState == NetworkInfo.DetailedState.CONNECTING)
{
updateWifiState(R.string.wifi_connecting,mWifiAdapter.getItemPosition(mCurSelectSsid));
}else if(ndState == NetworkInfo.DetailedState.AUTHENTICATING)
{
updateWifiState(R.string.wifi_authentication,mWifiAdapter.getItemPosition(mCurSelectSsid));
}else if(ndState == NetworkInfo.DetailedState.FAILED)
{
updateWifiState(R.string.wifi_connect_failed,mWifiAdapter.getItemPosition(mCurSelectSsid));
}
}
}
break;
case WifiManager.NETWORK_IDS_CHANGED_ACTION:
{
notifyDatasChange(sortList(mStmWifiManager.getWifiList()));
}
break;
case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
{
int state =intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR,-1);
if(WifiManager.ERROR_AUTHENTICATING == state)
{
updateWifiState(R.string.wifi_connect_failed,mWifiAdapter.getItemPosition(mCurSelectSsid));
}
}
break;
case WifiManager.RSSI_CHANGED_ACTION:
{
//这里根据广播重新刷新recycleView/ListView 达到动态显示信号强弱的目的
}
break;
}
}
};
4. 自定义管理类
自己项目中写的一个WifiManager,大概参考一下就可以了
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ProxyInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import com.stellamore.setting.entity.WifiStaticInfo;
import com.stellamore.setting.utils.Logg;
import com.stellamore.setting.utils.Utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class StmWifiManager {
private static StmWifiManager mStmWifiManager;
private Context mContext;
private List<WifiConfiguration> mWifiConfigurations;
private List<ScanResult> mWifiResultList;
private WifiInfo mWifiInfo;
private WifiManager.WifiLock mWifiLock;
private WifiManager mWifiManager;
private ConnectivityManager mConnectManager;
private StmWifiManager mInstance;
/**
* 得到配置好的网络连接
* @param ssid
* @return
*/
public WifiConfiguration isExist(String ssid) {
List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
if(0 == configs.size())
{
Logg.d("no save wifi configuration.");
return null;
}
for (WifiConfiguration config : configs) {
if (Utils.clearChar(config.SSID,'\"').equals(Utils.clearChar(ssid,'\"'))) {
Logg.d("config is exist.");
return config;
}
}
return null;
}
public boolean isEncrypted(ScanResult result)
{
Logg.d("check wifi is encrypted.");
String capabilities = result.capabilities;
if(!TextUtils.isEmpty(capabilities) || !"[ESS]".equals(capabilities))
{
return true;
}
return false;
}
/**锁定WifiLock,当下载大文件时需要锁定 **/
public void AcquireWifiLock() {
Logg.d("---AcquireWifiLock---");
this.mWifiLock.acquire();
}
/**创建一个WifiLock**/
public void CreateWifiLock() {
Logg.d("---CreateWifiLock---");
this.mWifiLock = this.mWifiManager.createWifiLock("Test");
}
/**解锁WifiLock**/
public void ReleaseWifilock() {
Logg.d("---ReleaseWifilock---");
if(mWifiLock.isHeld()) { //判断时候锁定
mWifiLock.acquire();
}
}
public int getWifiState()
{
Logg.d("---getWifiState---");
return mWifiManager.getWifiState();
}
public boolean isEnabled()
{
boolean enable = mWifiManager.isWifiEnabled();
Logg.d("wifi is enable:" + enable);
return enable;
}
/**打开Wifi**/
public void OpenWifi() {
Logg.d("open wifi.");
if(!this.mWifiManager.isWifiEnabled()){ //当前wifi不可用
this.mWifiManager.setWifiEnabled(true);
}
}
/**关闭Wifi**/
public void closeWifi() {
Logg.d("close wifi.");
if(mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}
}
public boolean disconnectWifi(int netId) {
Logg.d("disconnect wifi.");
mWifiManager.disableNetwork(netId);
return mWifiManager.disconnect();
}
public boolean removeConfiguration(String ssid)
{
int netId = -1;
if(isWifiConnected() && ssid.equals(Utils.clearChar(getWifiInfo().getSSID(),'\"')))
{
netId = getWifiInfo().getNetworkId();
disconnectWifi(netId);
return mWifiManager.removeNetwork(netId);
}else
{
netId = getWifiConfigurationNetId(ssid);
if(netId != -1)
{
return mWifiManager.removeNetwork(netId);
}
}
return false;
}
/**添加指定网络**/
public boolean addNetwork(WifiConfiguration paramWifiConfiguration) {
Logg.d("add wifi network");
mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
int netId = mWifiManager.addNetwork(paramWifiConfiguration);
return mWifiManager.enableNetwork(netId, true);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public boolean connectWifiPwd(String ssid, String pwd, ProxyInfo proxyInfo, WifiStaticInfo staticInfo)
{
WifiConfiguration config =getWifiConfig(ssid,pwd,true);
WifiConfiguration staticConfig = null;
int netId = -1;
if(null != proxyInfo)
{
config.setHttpProxy(proxyInfo);
}
if(null != staticInfo)
{
staticConfig = setStaticInfoToWifiCfg(staticInfo,config);
}
mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
if(null != staticConfig)
{
netId = mWifiManager.addNetwork(staticConfig);
}else
{
netId = mWifiManager.addNetwork(config);
}
return mWifiManager.enableNetwork(netId,true);
}
private WifiConfiguration setStaticInfoToWifiCfg(WifiStaticInfo staticInfo,WifiConfiguration config)
{
try {
Inet4Address ipAddr = (Inet4Address) InetAddress.getByName(staticInfo.getIp());
int prefixLength = staticInfo.getPrefix();
InetAddress gatewayAddr = InetAddress.getByName(staticInfo.getGateway());
InetAddress dns1 = InetAddress.getByName(staticInfo.getDomain1());
InetAddress dns2 = InetAddress.getByName(staticInfo.getDomain2());
Class[] classes = new Class[]{InetAddress.class,int.class};
Constructor constructor = null;
Class<?> clazz = Class.forName("android.net.LinkAddress");
constructor = clazz.getConstructor(classes);
if(null == constructor)
{
return null;
}
//给传入参数赋初值
Object[] obj = {ipAddr,prefixLength};
//构造StaticIpConfiguration对象
Class<?> staticIpConfigurationCls = Class.forName("android.net.StaticIpConfiguration");
//实例化StaticIpConfiguration
Object staticIpConfiguration = staticIpConfigurationCls.newInstance();;
Field ipAddress = staticIpConfigurationCls.getField("ipAddress");
Field gateway = staticIpConfigurationCls.getField("gateway");
Field dnsServers = staticIpConfigurationCls.getField("dnsServers");
//设置ipAddress
ipAddress.set(staticIpConfiguration,constructor.newInstance(obj));
//设置网关
gateway.set(staticIpConfiguration,gatewayAddr);
//设置dns
ArrayList<InetAddress> dnsList = (ArrayList<InetAddress>) dnsServers.get(staticIpConfiguration);
dnsList.add(dns1);
dnsList.add(dns2);
WifiConfiguration wifiConfig = config;
Class ipAssignmentCls = Class.forName("android.net.IpConfiguration$IpAssignment");
Object ipAssigment = Enum.valueOf(ipAssignmentCls,"STATIC");
Method setIpAssignmentMethod = wifiConfig.getClass().getDeclaredMethod("setIpAssignment", ipAssignmentCls);
setIpAssignmentMethod.invoke(wifiConfig, ipAssigment);
Method setStaticIpConfigurationMethod = wifiConfig.getClass().getDeclaredMethod("setStaticIpConfiguration", staticIpConfiguration.getClass());
//设置静态IP,将StaticIpConfiguration设置给WifiConfiguration
setStaticIpConfigurationMethod.invoke(wifiConfig, staticIpConfiguration);
return wifiConfig;
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
/**
* 无密码连接
* @param ssid
*/
public boolean connectWifiNoPwd(String ssid){
mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
mWifiManager.removeNetwork(mWifiManager.getConnectionInfo().getNetworkId());
int netId = mWifiManager.addNetwork(getWifiConfig(ssid, "", false));
Logg.d("---connectWifiNoPws---netId:" + netId);
return mWifiManager.enableNetwork(netId, true);
}
public int getCurrentWifiLevel()
{
return WifiManager.calculateSignalLevel(getWifiInfo().getRssi(),3);
}
/**
* wifi设置
* @param ssid
* @param pwd
* @param isHasPws
*/
private WifiConfiguration getWifiConfig(String ssid, String pwd, boolean isHasPws){
Logg.d("--getWifiConfig----");
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + ssid + "\"";
WifiConfiguration tempConfig = isExist(ssid);
if(tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
}
if (isHasPws){
config.preSharedKey = "\""+pwd+"\"";
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.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}else {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
return config;
}
public boolean isWifiConnected()
{
NetworkInfo wifiInfo = mConnectManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean result = wifiInfo.isConnected();
Logg.d("---isWifiConnected---,wifi connected:" + result);
return result;
}
/**
* 根据wifi信息创建或关闭一个热点
* @param paramWifiConfiguration
* @param paramBoolean 关闭标志
*/
public void createWifiAP(WifiConfiguration paramWifiConfiguration,boolean paramBoolean) {
try {
Class localClass = this.mWifiManager.getClass();
Class[] arrayOfClass = new Class[2];
arrayOfClass[0] = WifiConfiguration.class;
arrayOfClass[1] = Boolean.TYPE;
Method localMethod = localClass.getMethod("setWifiApEnabled",arrayOfClass);
WifiManager localWifiManager = this.mWifiManager;
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = paramWifiConfiguration;
arrayOfObject[1] = Boolean.valueOf(paramBoolean);
localMethod.invoke(localWifiManager, arrayOfObject);
return;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建一个wifi信息
* @param ssid
* @param passawrd
* @param paramInt
* @param type
* @return
*/
public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) {
//配置网络信息类
WifiConfiguration localWifiConfiguration1 = new WifiConfiguration();
//设置配置网络属性
localWifiConfiguration1.allowedAuthAlgorithms.clear();
localWifiConfiguration1.allowedGroupCiphers.clear();
localWifiConfiguration1.allowedKeyManagement.clear();
localWifiConfiguration1.allowedPairwiseCiphers.clear();
localWifiConfiguration1.allowedProtocols.clear();
if(type.equals("wt")) { //wifi连接
localWifiConfiguration1.SSID = ("\"" + ssid + "\"");
WifiConfiguration localWifiConfiguration2 = isExist(ssid);
if(localWifiConfiguration2 != null) {
mWifiManager.removeNetwork(localWifiConfiguration2.networkId); //从列表中删除指定的网络配置网络
}
if(paramInt == 1) { //没有密码
localWifiConfiguration1.wepKeys[0] = "";
localWifiConfiguration1.allowedKeyManagement.set(0);
localWifiConfiguration1.wepTxKeyIndex = 0;
} else if(paramInt == 2) { //简单密码
localWifiConfiguration1.hiddenSSID = true;
localWifiConfiguration1.wepKeys[0] = ("\"" + passawrd + "\"");
} else { //wap加密
localWifiConfiguration1.preSharedKey = ("\"" + passawrd + "\"");
localWifiConfiguration1.hiddenSSID = true;
localWifiConfiguration1.allowedAuthAlgorithms.set(0);
localWifiConfiguration1.allowedGroupCiphers.set(2);
localWifiConfiguration1.allowedKeyManagement.set(1);
localWifiConfiguration1.allowedPairwiseCiphers.set(1);
localWifiConfiguration1.allowedGroupCiphers.set(3);
localWifiConfiguration1.allowedPairwiseCiphers.set(2);
}
}else {//"ap" wifi热点
localWifiConfiguration1.SSID = ssid;
localWifiConfiguration1.allowedAuthAlgorithms.set(1);
localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
localWifiConfiguration1.allowedKeyManagement.set(0);
localWifiConfiguration1.wepTxKeyIndex = 0;
if (paramInt == 1) { //没有密码
localWifiConfiguration1.wepKeys[0] = "";
localWifiConfiguration1.allowedKeyManagement.set(0);
localWifiConfiguration1.wepTxKeyIndex = 0;
} else if (paramInt == 2) { //简单密码
localWifiConfiguration1.hiddenSSID = true;//网络上不广播ssid
localWifiConfiguration1.wepKeys[0] = passawrd;
} else if (paramInt == 3) {//wap加密
localWifiConfiguration1.preSharedKey = passawrd;
localWifiConfiguration1.allowedAuthAlgorithms.set(0);
localWifiConfiguration1.allowedProtocols.set(1);
localWifiConfiguration1.allowedProtocols.set(0);
localWifiConfiguration1.allowedKeyManagement.set(1);
localWifiConfiguration1.allowedPairwiseCiphers.set(2);
localWifiConfiguration1.allowedPairwiseCiphers.set(1);
}
}
return localWifiConfiguration1;
}
/**获取热点名**/
public String getApSSID() {
try {
Method localMethod = this.mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]);
if (localMethod == null) return null;
Object localObject1 = localMethod.invoke(this.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;
}
/**获取wifi名**/
public String getBSSID() {
mWifiInfo = mWifiManager.getConnectionInfo();
return this.mWifiInfo.getBSSID();
}
/**得到配置好的网络 **/
public List<WifiConfiguration> getConfiguration() {
Logg.d("get wifi configurations.");
mWifiConfigurations = mWifiManager.getConfiguredNetworks();
return mWifiConfigurations;
}
/**获取ip地址**/
public int getIPAddress() {
mWifiInfo = mWifiManager.getConnectionInfo();
return mWifiInfo.getIpAddress();
}
/**获取物理地址(Mac)**/
public String getMacAddress() {
mWifiInfo = mWifiManager.getConnectionInfo();
return mWifiInfo.getMacAddress();
}
/**获取已连接的网络id**/
public int getConnectNetworkId() {
Logg.d("get networkId");
mWifiInfo = mWifiManager.getConnectionInfo();
return mWifiInfo.getNetworkId();
}
public int getWifiConfigurationNetId(String ssid)
{
WifiConfiguration config = isExist(ssid);
if(null == config)
{
return -1;
}
return config.networkId;
}
/**获取热点创建状态**/
public int getWifiApState() {
try {
int i = ((Integer) this.mWifiManager.getClass()
.getMethod("getWifiApState", new Class[0])
.invoke(this.mWifiManager, new Object[0])).intValue();
return i;
} catch (Exception localException) {
}
return 4; //未知wifi网卡状态
}
/**获取wifi连接信息**/
public WifiInfo getWifiInfo() {
WifiInfo info = mWifiManager.getConnectionInfo();
Logg.d("get wifi info:" + info.toString());
return info;
}
/** 得到网络列表**/
public List<ScanResult> getWifiList() {
return mWifiManager.getScanResults();
}
/**查看扫描结果**/
public StringBuilder lookUpScan() {
StringBuilder localStringBuilder = new StringBuilder();
mWifiResultList = getWifiList();
for (int i = 0; i < mWifiResultList.size(); i++)
{
localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":");
//将ScanResult信息转换成一个字符串包
//其中把包括:BSSID、SSID、capabilities、frequency、level
localStringBuilder.append((mWifiResultList.get(i)).toString());
localStringBuilder.append("\n");
}
return localStringBuilder;
}
/* *//** 设置wifi搜索结果 **//*
public void setWifiList() {
this.mWifiResultList = this.mWifiManager.getScanResults();
}*/
/**
* 开始搜索wifi
* @return
*/
public boolean startScan() {
Logg.d("start scan wifi.");
return this.mWifiManager.startScan();
}
/**得到接入点的BSSID**/
public String GetBSSID() {
mWifiInfo = mWifiManager.getConnectionInfo();
return mWifiInfo.getBSSID();
}
public static StmWifiManager getInstance()
{
return SingleHolder.instance;
}
public StmWifiManager init(Context ctx)
{
mContext = ctx;
mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
mConnectManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
return this;
}
private static class SingleHolder
{
private static StmWifiManager instance = new StmWifiManager();
}
}
5.总结
流程: