我使用连接管理器类获取网络信息,我只是得到网络类型是Wifi或以太网。但是当我的网络类型是Wifi时,我想知道它的静态还是动态。
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
您可以找到从此thread改编的简单(未优化)代码。 代码是为Android 4.0编写的。
请记住添加其他用户权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
方法:
public String getIpAssignment(){
String myenumvalue="";
WifiConfiguration wifiConf = null;
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
for (WifiConfiguration conf : configuredNetworks){
if (conf.networkId == connectionInfo.getNetworkId()){
wifiConf = conf;
break;
}
}
if(wifiConf != null){
try {
Object Enumer = getDeclaredField(wifiConf, "ipAssignment");
myenumvalue = Enumer.toString();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return myenumvalue;
}
它从ipAssignment返回一个枚举字段:UNASSIGNED | STATIC | DHCP
答案 1 :(得分:0)
我的android测试设备android版本5.1.1(嵌入式板) 我使用了上面的代码,但它落入了错误 (“捕获NoSuchFieldException”)
我使用以下代码查找静态或dhcp连接:
public void getWifiDhcpStatic(){
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
for (WifiConfiguration conf : configuredNetworks){
if (conf.networkId == connectionInfo.getNetworkId()){
if (conf.toString().toLowerCase().indexOf("DHCP".toLowerCase())>-1){
Log.i("myLogDHCPorSTATIC","DHCP ");
}else if(conf.toString().toLowerCase().indexOf("STATIC".toLowerCase())>-1){
Log.i("myLogDHCPorSTATIC","STATIC ");
}
break;
}
}
}
别忘了添加清单
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />