开发中遇到需要获取连接的wifi的一些信息,以下代码适合有自己编译的系统jar包使用,时间不多没整理有点乱,合起来看就可以。
private void setwifiinfo(){
String wifiinfoIp = "";//ip
String wifiinfomac = "";//mac
String wifiinfoDNS = "";//dns
String wifiinfogetaway = "";//getaway
String wifiinfomask = ""; //子网掩码
Boolean isdhcp = true; //是否静态动态
WifiConfiguration wifiConfiguration = wifiAdmin.getWifiConfiguration(wifiAdmin.getNetworkId());
if(wifiConfiguration != null){
if (wifiAdmin.getwificonfigstatic(wifiConfiguration)){
StaticIpConfiguration staticIpConfiguration = wifiConfiguration.getIpConfiguration().staticIpConfiguration;
isdhcp = false;
wifiinfoIp = wifiAdmin.getIPAddress();
wifiinfogetaway = staticIpConfiguration.gateway.getHostAddress();
wifiinfomask = utils.getmaskutll(staticIpConfiguration.ipAddress.getNetworkPrefixLength());
Iterator<InetAddress> dns = staticIpConfiguration.dnsServers.iterator();
if(dns.hasNext()){
wifiinfoDNS = dns.next().getHostAddress();
}
}else{
DhcpInfo dhcpInfo = wifiAdmin.getmWifiManager().getDhcpInfo();
if(dhcpInfo != null){
isdhcp = true;
wifiinfoIp = utils.getfrmentIPinfo(dhcpInfo.ipAddress);
wifiinfogetaway = utils.getfrmentIPinfo(dhcpInfo.gateway);
wifiinfomask = utils.getfrmentIPinfo(dhcpInfo.netmask);
wifiinfoDNS = utils.getfrmentIPinfo(dhcpInfo.dns1);
}
}
}
wifiinfomac = wifiAdmin.getMacAddress();
}
为了不影响结构上述代码中的方法提取如下
public WifiAdmin(Context context) {
// 取得WifiManager对象
mWifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
// 取得WifiInfo对象
mWifiInfo = mWifiManager.getConnectionInfo();
}
//获取连接wifi的config
public WifiConfiguration getWifiConfiguration(int networkId) {
List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration configuredNetwork : configuredNetworks) {
if (configuredNetwork.networkId == networkId) {
return configuredNetwork;
}
}
}
return null;
}
//判断是否静态
public Boolean getwificonfigstatic(WifiConfiguration wifiConfiguration){
return wifiConfiguration.getIpAssignment() == IpConfiguration.IpAssignment.STATIC;
}
// 得到连接的ID
public int getNetworkId() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
}
// 得到IP地址
public String getIPAddress() {
return utils.getfrmentIPinfo((mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress());
}
public WifiManager getmWifiManager(){
return mWifiManager;
}
util类的
public String getfrmentIPinfo(int ipadds){
return Formatter.formatIpAddress(ipadds);
}
// 得到MAC地址
public String getMacAddress() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
}