安卓9.0设置WIFI静态IP地址。

简单的一个函数实现对wifi设置静态或动态IP地址。

一、需要的权限




可以删除该WiFi 和修改。

二、清单文件需要将shareduserid设置成system。

android:sharedUserId="android.uid.system"

三、具体函数,函数执行条件是wifi开关打开,并且要设置的wifi已经连接成功。

    // 定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
    public enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    /**
     * @param context   use Application context is better
     * @param ipAddress ip address: like 192.168.1.168
     * @param mode      : STATIC or DHCP, set static or dhcp ip mode
     * @param netmask   ip mask, like 255.255.255.0
     * @param gateway   gateway, like 192.168.1.1
     * @param dns1      dns 1
     * @param dns2      dns 2, if mode=static, then can use "" or null
     * @param ssid current has connected wifi ssid
     * @param pwd current has connected wifi pwd
     * @param wifiCipherType current has connected wifi capabilities
     *                  eg. dhcp mode: setWifiStaticIP(ApplicationContext, "DHCP", "", "", "", "", "", "test", "123456", WifiCipherType.WIFICIPHER_WPA);
     *                  static mode: setWifiStaticIP(ApplicationContext, "STATIC",
     *                  "192.168.1.168", "255.255.255.0",
     *                  "192.168.1.1", "114.114.114.114", "8.8.8.8", "test", "123456", WifiCipherType.WIFICIPHER_WPA);
     *                  for android 9.0
     */
    public static boolean setWifiStaticIP(Context context, String mode, String ipAddress, String netmask,
                                        String gateway, String dns1, String dns2,
                                          String ssid, String pwd, WifiCipherType wifiCipherType) {
        if (context == null || (!"STATIC".equals(mode) && !"DHCP".equals(mode))
            || TextUtils.isEmpty(ssid) || wifiCipherType == null
                || TextUtils.isEmpty(wifiCipherType.name())) {
            Log.d(TAG, " setWifiStaticIP failed, param incorrect context=" + context + ", mode=" + mode);
            return false;
        }

        try {
            WifiManager wifiManager = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE));
            if ("DHCP".equals(mode)) {
                IpConfiguration dhcpConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.DHCP,
                        IpConfiguration.ProxySettings.NONE, null, null);
                dhcpConfiguration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
                WifiConfiguration wifiConfiguration = createWifiConfig(ssid, pwd, wifiCipherType, dhcpConfiguration);
                // current assignment is DHCP OR STATIC
                String assignMent = wifiConfiguration.getIpConfiguration().ipAssignment.name();
                Log.d(TAG, " setWifiStaticIP assignMent=" + assignMent + ", mode=" + mode);
                wifiManager.setWifiApConfiguration(wifiConfiguration);
                // update network
                wifiManager.updateNetwork(wifiConfiguration);
                // reconnect
                int netId = wifiManager.addNetwork(wifiConfiguration);
                wifiManager.disableNetwork(netId);
                wifiManager.enableNetwork(netId, true);
                Log.i(TAG, " setWifiStaticIP dhcp set success");
                return true;
            }
            // set static ip address
            IpConfiguration ipConfiguration = getStaticIpConfiguration(ipAddress, netmask, gateway, dns1, dns2);
            if (ipConfiguration != null) {
                WifiConfiguration wifiConfiguration = createWifiConfig(ssid, pwd, wifiCipherType, ipConfiguration);
                wifiManager.setWifiApConfiguration(wifiConfiguration);
                // update network
                wifiManager.updateNetwork(wifiConfiguration);
                // reconnect
                int netId = wifiManager.addNetwork(wifiConfiguration);
                wifiManager.disableNetwork(netId);
                wifiManager.enableNetwork(netId, true);
                Log.i(TAG, "setWifiStaticIP set static ip success");
                return true;
            } else {
                Log.w(TAG, "setWifiStaticIP set static ip failed");
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "setWifiStaticIP e=" + e.getMessage());
        }
        return false;
    }

    private static IpConfiguration getStaticIpConfiguration(String ipAddress, String netmask, String gateway, String dns1, String dns2) {
        try {
            StaticIpConfiguration staticIpConfiguration = new StaticIpConfiguration();
            int prefixLength = maskStr2InetMask(netmask);
            InetAddress inetAddr = null;
            InetAddress gatewayAddr = getIPv4Address(gateway);
            InetAddress dnsAddr = getIPv4Address(dns1);

            if (TextUtils.isEmpty(ipAddress)) {
                inetAddr = getLocalIPAddress();
            } else {
                String[] ipStr = ipAddress.split("\\.");
                byte[] ipBuf = new byte[4];
                for (int i = 0; i < 4; i++) {
                    ipBuf[i] = (byte) (Integer.parseInt(ipStr[i]) & 0xff);
                }
                try {
                    inetAddr = InetAddress.getByAddress(ipBuf);
                    Log.d(TAG, "getStaticIpConfiguration  address correct inetAddr=" + inetAddr);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }

            if (inetAddr == null || inetAddr.getAddress().toString().isEmpty()
                    || prefixLength == 0 || gatewayAddr.toString().isEmpty()
                    || dnsAddr == null || dnsAddr.toString().isEmpty()) {
                Log.d(TAG, " getStaticIpConfiguration  address incorrect inetAddr=" + inetAddr);
                return null;
            }

            Class linkAddressClass = null;
            linkAddressClass = Class.forName("android.net.LinkAddress");
            Class[] cl = new Class[]{InetAddress.class, int.class};
            Constructor cons = null;
            try {
                cons = linkAddressClass.getConstructor(cl);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            Object[] x = {inetAddr, prefixLength};
            try {
                staticIpConfiguration.ipAddress = (LinkAddress) cons.newInstance(x);
                Log.d(TAG, " getStaticIpConfiguration staticIpConfiguration.ipAddress=" + staticIpConfiguration.ipAddress);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }

            staticIpConfiguration.gateway = gatewayAddr;
            staticIpConfiguration.dnsServers.add(dnsAddr);
            if (!dns2.isEmpty())
                staticIpConfiguration.dnsServers.add(getIPv4Address(dns2));

            Log.d(TAG, " getStaticIpConfiguration staticIpConfiguration  ====" + staticIpConfiguration
                    + ", inetAddr=" + inetAddr);

            IpConfiguration ipConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.STATIC,
                    IpConfiguration.ProxySettings.NONE, staticIpConfiguration, null);
            ipConfiguration.setIpAssignment(IpConfiguration.IpAssignment.STATIC);
            ipConfiguration.setStaticIpConfiguration(staticIpConfiguration);
            return ipConfiguration;
        } catch (Exception e) {
            Log.e(TAG, "getStaticIpConfiguration ERROR=" + e.getMessage());
        }
        return null;
    }

部分参考:https://blog.csdn.net/ink_s/article/details/78720544

以太网静态、动态IP设置可参考我的另一篇文章:https://blog.csdn.net/zzhceo/article/details/99596435

你可能感兴趣的:(Android,安卓,android,wifi,java)