1

我使用连接管理器类并获取网络信息,我只知道网络类型是 Wifi 还是以太网。但是当我的网络类型是 Wifi 时,我想知道它是静态的还是动态的。

有人可以帮我解决这个问题吗

4

2 回答 2

2

下面你可以找到从这个线程改编的简单(未优化)代码。代码是为 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 | 静电 | DHCP

于 2013-09-24T17:46:05.320 回答
0

我的android测试设备android版本5.1.1(嵌入式板)我使用了上面的代码,但它陷入了错误(“catch 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" />
于 2018-12-26T14:06:42.203 回答