【Android智能硬件开发】【012】通过代码设置以太网静态IP

前提

只有系统APP才具备此功能,即APP的uid必须使用系统用户,APK必须进行系统签名

这个不懂的请翻阅本专栏前面的博客

核心代码

由于以太网相关接口是隐藏的,只能通过反射调用


	package com.android.commons.framework;
	
	import android.content.ContentResolver;
	import android.content.Context;
	import android.provider.Settings;
	
	import com.easing.commons.android.code.Console;
	
	import java.lang.reflect.Constructor;
	import java.lang.reflect.Field;
	import java.lang.reflect.Method;
	import java.net.InetAddress;
	import java.util.LinkedHashMap;
	import java.util.List;
	import java.util.Map;
	
	import lombok.SneakyThrows;
	
	@SuppressWarnings("all")
	public class EthernetHandlerInternal {
	
	    //设置以太网动态IP
	    public static boolean setDynamicIp(Context context) {
	        try {
	            //创建EthernetManager实例
	            Class ethernetManagerClass = Class.forName("android.net.EthernetManager");
	            Object ethernetManager = context.getSystemService("ethernet");
	            //创建IpConfiguration
	            Class ipConfigurationClass = Class.forName("android.net.IpConfiguration");
	            Object ipConfiguration = ipConfigurationClass.newInstance();
	            //获取所有枚举常量
	            Map<String, Object> enumMap = getIpConfigurationEnumMap(ipConfigurationClass);
	            //设置ipAssignment
	            Field ipAssignment = ipConfigurationClass.getField("ipAssignment");
	            ipAssignment.set(ipConfiguration, enumMap.get("IpAssignment.DHCP"));
	            //设置proxySettings
	            Field proxySettings = ipConfigurationClass.getField("proxySettings");
	            proxySettings.set(ipConfiguration, enumMap.get("ProxySettings.NONE"));
	            //设置Configuration
	            Method setConfigurationMethod = ethernetManagerClass.getDeclaredMethod("setConfiguration", ipConfiguration.getClass());
	            setConfigurationMethod.invoke(ethernetManager, ipConfiguration);
	            return true;
	        } catch (Throwable e) {
	            Console.error(e);
	            return false;
	        }
	    }
	
	    //设置以太网静态IP
	    public static boolean setStaticIp(Context context, String address, String mask, String gateway, String dns) {
	        try {
	            //创建EthernetManager实例
	            Class ethernetManagerClass = Class.forName("android.net.EthernetManager");
	            Object ethernetManager = context.getSystemService("ethernet");
	            //设置IpConfiguration
	            Object staticIpConfiguration = newStaticIpConfiguration(address, gateway, mask, dns);
	            Object ipConfiguration = newIpConfiguration(staticIpConfiguration);
	            //保存IP设置
	            saveIpSettings(context, address, gateway, mask, dns);
	            //设置Configuration
	            Method setConfigurationMethod = ethernetManagerClass.getDeclaredMethod("setConfiguration", ipConfiguration.getClass());
	            setConfigurationMethod.invoke(ethernetManager, ipConfiguration);
	            return true;
	        } catch (Throwable e) {
	            Console.error(e);
	            return false;
	        }
	    }
	
	    //创建LinkAddress
	    @SneakyThrows
	    protected static Object newLinkAddress(String address, String mask) {
	        Class linkAddressClass = Class.forName("android.net.LinkAddress");
	        Constructor constructor = linkAddressClass.getDeclaredConstructor(InetAddress.class, int.class);
	        return constructor.newInstance(InetAddress.getByName(address), getPrefixLength(mask));
	    }
	
	
	    //创建StaticIpConfiguration
	    @SneakyThrows
	    protected static Object newStaticIpConfiguration(String address, String gateway, String mask, String dns) {
	        //创建StaticIpConfiguration
	        Class clazz = Class.forName("android.net.StaticIpConfiguration");
	        Object staticIpConfiguration = clazz.newInstance();
	        //设置IP
	        Field addressField = clazz.getField("ipAddress");
	        addressField.set(staticIpConfiguration, newLinkAddress(address, mask));
	        //设置网关
	        Field gatewayField = clazz.getField("gateway");
	        gatewayField.set(staticIpConfiguration, InetAddress.getByName(gateway));
	        //设置子网掩码
	        Field domainField = clazz.getField("domains");
	        domainField.set(staticIpConfiguration, mask);
	        //设置DNS
	        Field dnsField = clazz.getField("dnsServers");
	        List<InetAddress> dnsList = (List) dnsField.get(staticIpConfiguration);
	        dnsList.add(InetAddress.getByName(dns));
	        return staticIpConfiguration;
	    }
	
	
	    //创建IpConfiguration
	    @SneakyThrows
	    protected static Object newIpConfiguration(Object staticIpConfiguration) {
	        //创建IpConfiguration
	        Class clazz = Class.forName("android.net.IpConfiguration");
	        Object ipConfiguration = clazz.newInstance();
	        //设置staticIpConfiguration
	        Field staticIpConfigurationField = clazz.getField("staticIpConfiguration");
	        staticIpConfigurationField.set(ipConfiguration, staticIpConfiguration);
	        Map<String, Object> ipConfigurationEnum = getIpConfigurationEnumMap(clazz);
	        //设置ipAssignment
	        Field ipAssignment = clazz.getField("ipAssignment");
	        ipAssignment.set(ipConfiguration, ipConfigurationEnum.get("IpAssignment.STATIC"));
	        //设置proxySettings
	        Field proxySettings = clazz.getField("proxySettings");
	        proxySettings.set(ipConfiguration, ipConfigurationEnum.get("ProxySettings.STATIC"));
	        return ipConfiguration;
	    }
	
	    //获取IpConfiguration类中的所有枚举常量
	    protected static Map<String, Object> getIpConfigurationEnumMap(Class ipConfigurationClass) {
	        Map<String, Object> enumMap = new LinkedHashMap();
	        Class[] classes = ipConfigurationClass.getDeclaredClasses();
	        for (Class clazz : classes) {
	            Object[] enumConstants = clazz.getEnumConstants();
	            if (enumConstants == null)
	                continue;
	            for (Object constant : enumConstants)
	                enumMap.put(clazz.getSimpleName() + "." + constant.toString(), constant);
	        }
	        return enumMap;
	    }
	
	    //保存IP设置
	    protected static void saveIpSettings(Context context, String address, String gateway, String mask, String dns) {
	        ContentResolver contentResolver = context.getContentResolver();
	        Settings.Global.putString(contentResolver, "ethernet_static_ip", address);
	        Settings.Global.putString(contentResolver, "ethernet_static_mask", mask);
	        Settings.Global.putString(contentResolver, "ethernet_static_gateway", gateway);
	        Settings.Global.putString(contentResolver, "ethernet_static_dns1", dns);
	    }
	
	    //根据子网掩码,自动计算前缀长度
	    protected static int getPrefixLength(String mask) {
	        String[] strs = mask.split("\\.");
	        int count = 0;
	        for (String str : strs)
	            if (str.equals("255"))
	                ++count;
	        return count * 8;
	    }
	}




	package com.android.commons.framework;
	
	import com.easing.commons.android.app.CommonApplication;
	import com.easing.commons.android.code.Console;
	
	import lombok.SneakyThrows;
	
	@SuppressWarnings("all")
	public class EthernetHandler {
	
	    //设置动态IP
	    @SneakyThrows
	    public static boolean setDynamicIP() {
	        try {
	            boolean ret = EthernetHandlerInternal.setDynamicIp(CommonApplication.ctx);
	            return ret;
	        } catch (Throwable e) {
	            Console.error(e);
	            return false;
	        }
	    }
	
	    //设置以太网静态IP
	    //子网掩码和DNS使用默认值
	    @SneakyThrows
	    public static boolean setStaticIP(String address, String gateway) {
	        try {
	            boolean ret = EthernetHandlerInternal.setStaticIp(CommonApplication.ctx, address, "255.255.255.0", gateway, "119.29.29.29");
	            return ret;
	        } catch (Throwable e) {
	            Console.error(e);
	            return false;
	        }
	    }
	}


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 11设置以太网静态 IP 路由,可以使用以下代码实现: 1. 添加权限到 AndroidManifest.xml 文件中: ``` <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> ``` 2. 在代码中添加以下代码: ```java // 获取 ConnectivityManager ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // 获取当前活动网络信息 Network activeNetwork = connectivityManager.getActiveNetwork(); // 获取 Ethernet 网络信息 NetworkInfo ethernetNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET); // 判断 Ethernet 网络是否已连接 if (ethernetNetworkInfo.isConnected()) { // 获取 Ethernet 网络的网络 ID int ethernetNetworkId = ethernetNetworkInfo.getNetworkId(); // 创建一个 Ethernet 网络的路由信息 RouteInfo ethernetRouteInfo = new RouteInfo(new IpPrefix("192.168.0.0/24"), null, "eth0", RouteInfo.RTN_UNICAST); // 获取 Wi-Fi 网络信息 NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // 判断 Wi-Fi 网络是否已连接 if (wifiNetworkInfo.isConnected()) { // 获取 Wi-Fi 网络的网络 ID int wifiNetworkId = wifiNetworkInfo.getNetworkId(); // 创建一个 Wi-Fi 网络的路由信息 RouteInfo wifiRouteInfo = new RouteInfo(new IpPrefix("192.168.1.0/24"), null, "wlan0", RouteInfo.RTN_UNICAST); // 创建一个路由表 RouteTable routeTable = new RouteTable(); // 添加路由信息到路由表中 routeTable.add(ethernetRouteInfo); routeTable.add(wifiRouteInfo); // 设置路由表到 Ethernet 网络 connectivityManager.setNetworkRoutes(ethernetNetworkId, routeTable); // 设置路由表到 Wi-Fi 网络 connectivityManager.setNetworkRoutes(wifiNetworkId, routeTable); } } ``` 上述代码中,我们首先获取 ConnectivityManager 对象,并获取当前活动网络信息和 Ethernet 网络信息。如果 Ethernet 网络已连接,则获取 Ethernet 网络的网络 ID,并创建一个 Ethernet 网络的路由信息。接着,我们获取 Wi-Fi 网络信息,如果 Wi-Fi 网络已连接,则获取 Wi-Fi 网络的网络 ID,并创建一个 Wi-Fi 网络的路由信息。最后,我们创建一个路由表,并将路由信息添加到路由表中。最后,我们将路由表设置到 Ethernet 网络和 Wi-Fi 网络中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值