Change WiFi's configuration on Android 5 (L) programmatically

前端 未结 1 897
半阙折子戏
半阙折子戏 2021-02-06 12:36

There\'re some problems with the code worked on android 4.0.2..4.4.4, but doesn\'t really work on Android 5 and I don\'t know why. Basically, the code below allows to set new Wi

相关标签:
1条回答
  • 2021-02-06 13:00

    Although the ipAssignment field was still present in the L preview (at least the version in grepcode), it's not in the released version, as you can see in the "master" branch of the source code or in the Github mirror.

    Both the Enum definition and the field are now inside an inner object, of type IpConfiguration (also new). These are the dangers of using reflection to access undocumented waters... :)

    However, it's simple to tweak the code to access it by reflection and set it there:

    public static void setIpAssignment(String assign, WifiConfiguration wifiConf)
            throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Object ipConfiguration = wifiConf.getClass().getMethod("getIpConfiguration").invoke(wifiConf);
            setEnumField(ipConfiguration, assign, "ipAssignment");
        } else {
            setEnumField(wifiConf, assign, "ipAssignment");
        }
    }
    

    This code "works" (in the sense that it does not throw an exception) but I haven't tested it any further.


    See How to configure a static IP address, netmask, gateway, DNS programmatically on Android 5.x (Lollipop) for Wi-Fi connection for a more detailed solution.

    0 讨论(0)
提交回复
热议问题