在API 30中,可以使用ConnectivityManager的setLinkProperties方法设置静态IP,具体代码如下:
private void setStaticIp(Context context, String ipAddress, int prefixLength, String gateway, String[] dnsServers) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Network network = cm.getActiveNetwork();
    LinkProperties lp = cm.getLinkProperties(network);
    // Set IP address
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddresses.parseNumericAddress(ipAddress);
    } catch (Exception e) {
        Log.e(TAG, "Invalid IP address: " + ipAddress, e);
    }
    if (inetAddress != null) {
        lp.addLinkAddress(new LinkAddress(inetAddress, prefixLength));
    }
    // Set gateway
    InetAddress gatewayInet = null;
    try {
        gatewayInet = InetAddresses.parseNumericAddress(gateway);
    } catch (Exception e) {
        Log.e(TAG, "Invalid gateway: " + gateway, e);
    }
    if (gatewayInet != null) {
        lp.addRoute(new RouteInfo(new IpPrefix(gatewayInet, 32), null, null));
    }
    // Set DNS servers
    if (dnsServers != null) {
        for (String dns : dnsServers) {
            InetAddress dnsInet = null;
            try {
                dnsInet = InetAddresses.parseNumericAddress(dns);
            } catch (Exception e) {
                Log.e(TAG, "Invalid DNS server: " + dns, e);
            }
            if (dnsInet != null) {
                lp.addDnsServer(dnsInet);
            }
        }
    }
    cm.setLinkProperties(network, lp);
}
下一篇:API30中如何重命名文件