精华内容
下载资源
问答
  • 想要设置以太网静态IP通过搜索是需用到EthernetManager,但是EthernetManager是谷歌隐藏的API,app是无法调用到的,所以只能通过反射来进行设置 也可以通过下载系统的class.jar包,放到自己的项目中,就可以不用...

    想要设置以太网为静态IP通过搜索是需用到EthernetManager,但是EthernetManager是谷歌隐藏的API,app是无法调用到的,所以只能通过反射来进行设置

    也可以通过下载系统的class.jar包,放到自己的项目中,就可以不用反射,直接调用

    下边是引入jar包直接调用的代码,通过EthernetManager 的setConfiguration方法来设置,但是需要构造IpConfiguration 和StaticIpConfiguration对象,IpConfiguration.IpAssignment.STATIC就代表设置为静态IP,也可以设置DHCP

    private void setStaticIP() {
            EthernetManager mEthManager = (EthernetManager) getSystemService("ethernet");
            StaticIpConfiguration mStaticIpConfiguration = new StaticIpConfiguration();
            /*
              * get ip address, netmask,dns ,gw etc.
              */
            Inet4Address inetAddr = getIPv4Address(mEthIpAddress);
            int prefixLength = NetUtils.maskStr2InetMask(mEthNetmask);
            InetAddress gatewayAddr = getIPv4Address(mEthGateway);
            InetAddress dnsAddr = getIPv4Address(mEthdns1);
    
            if (inetAddr.getAddress().toString().isEmpty() || prefixLength ==0 || gatewayAddr.toString().isEmpty()
                    || dnsAddr.toString().isEmpty()) {
               return;
            }
    
            Class<?> clazz = null;
            try {
                clazz = Class.forName("android.net.LinkAddress");
            } catch (Exception e) {
                // TODO: handle exception
            }
    
            Class[] cl = new Class[]{InetAddress.class, int.class};
            Constructor cons = null;
    
            //取得所有构造函数
            try {
                 cons = clazz.getConstructor(cl);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
    
            //给传入参数赋初值
            Object[] x = {inetAddr, prefixLength};
    
            String dnsStr2 = mEthdns2;
            //mStaticIpConfiguration.ipAddress = new LinkAddress(inetAddr, prefixLength);
            try {
                mStaticIpConfiguration.ipAddress = (LinkAddress) cons.newInstance(x);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
    
            mStaticIpConfiguration.gateway=gatewayAddr;
            mStaticIpConfiguration.dnsServers.add(dnsAddr);
    
            if (!dnsStr2.isEmpty()) {
                mStaticIpConfiguration.dnsServers.add(getIPv4Address(dnsStr2));
            }
    
            Log.d("2312321", "chanson mStaticIpConfiguration  ====" + mStaticIpConfiguration);
    
            IpConfiguration mIpConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.STATIC, IpConfiguration.ProxySettings.NONE, mStaticIpConfiguration, null);
    
            mEthManager.setConfiguration(mIpConfiguration);
        }
    

    参考项目链接

    不想引用jar包的话就需要使用反射来实现,下边代码是我模仿这个逻辑通过反射来实现的代码

    try {
        Class<?> ethernetManagerCls = Class.forName("android.net.EthernetManager");
    
        //获取EthernetManager实例
        Object ethManager = VfiServiceApp.getContext().getSystemService("ethernet");
    
        // get ip address, netmask,dns ,gw etc.
        Inet4Address inetAddr = getIPv4Address(STATIC_IP);
        int prefixLength = NetUtils.maskStr2InetMask(STATIC_NETMASK);
        InetAddress gatewayAddr = getIPv4Address(STATIC_GATEWAY);
        InetAddress dnsAddr = getIPv4Address(STATIC_DNS1);
    
        Class<?> clazz = Class.forName("android.net.LinkAddress");
    
        if (ethManager == null || inetAddr == null || inetAddr.getAddress() == null || gatewayAddr == null
                || dnsAddr == null || Arrays.toString(inetAddr.getAddress()).isEmpty() || prefixLength == 0
                || gatewayAddr.toString().isEmpty() || dnsAddr.toString().isEmpty() || clazz == null) {
            return;
        }
    
        Class[] cl = new Class[]{InetAddress.class, int.class};
        Constructor cons = null;
    
        //取得所有构造函数
        try {
            cons = clazz.getConstructor(cl);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    
        if (cons == null) {
            return;
        }
        //给传入参数赋初值
        Object[] x = {inetAddr, prefixLength};
    
    
        Class<?> staticIpConfigurationCls = Class.forName("android.net.StaticIpConfiguration");
        //实例化StaticIpConfiguration
        Object staticIpConfiguration = null;
    
        staticIpConfiguration = staticIpConfigurationCls.newInstance();
        Field ipAddress = staticIpConfigurationCls.getField("ipAddress");
        Field gateway = staticIpConfigurationCls.getField("gateway");
        Field dnsServers = staticIpConfigurationCls.getField("dnsServers");
        //设置ipAddress
        ipAddress.set(staticIpConfiguration, (LinkAddress) cons.newInstance(x));
        //设置网关
        gateway.set(staticIpConfiguration, gatewayAddr);
        //设置dns
        ArrayList<InetAddress> dnsList = (ArrayList<InetAddress>) dnsServers.get(staticIpConfiguration);
        dnsList.add(dnsAddr);
        if (!STATIC_DNS2.isEmpty()) {
            dnsList.add(getIPv4Address(STATIC_DNS2));
        }
        Log.d(TAG, "chanson mStaticIpConfiguration  ====" + staticIpConfigurationCls);
    
        Class<?> ipConfigurationCls = Class.forName("android.net.IpConfiguration");
        Object ipConfiguration = ipConfigurationCls.newInstance();
        //设置StaticIpConfiguration
        Field staticIpConfigurationField = ipConfigurationCls.getField("staticIpConfiguration");
        staticIpConfigurationField.set(ipConfiguration, staticIpConfiguration);
        //获取ipAssignment、proxySettings的枚举值
        Map<String, Object> ipConfigurationEnum = getIpConfigurationEnum(ipConfigurationCls);
        //设置ipAssignment
        Field ipAssignment = ipConfigurationCls.getField("ipAssignment");
        ipAssignment.set(ipConfiguration, ipConfigurationEnum.get("IpAssignment.STATIC"));
        //设置proxySettings
        Field proxySettings = ipConfigurationCls.getField("proxySettings");
        proxySettings.set(ipConfiguration, ipConfigurationEnum.get("ProxySettings.NONE"));
    
        @SuppressLint("PrivateApi")
        Method setConfigurationMethod = ethernetManagerCls.getDeclaredMethod("setConfiguration", ipConfiguration.getClass());
        //设置静态IP
        setConfigurationMethod.invoke(ethManager, ipConfiguration);
    } catch (NoSuchFieldException | IllegalAccessException | InstantiationException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {
        e.printStackTrace();
    }
    

    最好放到主线程中执行,因为我之前测试在子线程有报错,所以需要切换到主线程,参考文章https://blog.csdn.net/lebulangzhen/article/details/108519311

    两种方式都可以设置成功,根据个人需要使用即可,class.jar可以通过到参考项目libs中进行下载

    当然还需要应用有系统权限才可以设置,所以需要改为系统应用并进行系统签名才可真正设置成功

    展开全文
  • 安卓9.0设置以太网静态IP地址

    千次阅读 热门讨论 2019-08-14 19:41:37
    前言:因为项目需要设置安卓9.0系统的以太网静态ip地址,于是网上搜索相关资料。9.0系统以太网设置静态ip有关的,只有Github上有个MTK开发人员的分享,github链接:...

    前言:因为项目需要设置安卓9.0系统的以太网静态ip地址,于是网上搜索相关资料。9.0系统以太网设置静态ip有关的,只有Github上有个MTK开发人员的分享,github链接:https://github.com/Dufre/Android-Settings-Ethernet,patch是在系统设置中加上以太网设置,用过后发现设置静态IP可以成功,但是无法连外网,解决方法是将 0001-Ethernet-Add-Static-IP-Settiings.patch 中的两个注释去掉,改成如下,且在设置的时候一定要配置正确的网关和DNS。

    +        mStaticIpConfiguration.gateway=gatewayAddr;
    +        mStaticIpConfiguration.dnsServers.add(dnsAddr);

     打patch方式,比方说想打0001-Ethernet-Add-Static-IP-Settiings.patch,那么到/packages/apps/Settings目录,这个目录可以通过看patch文件中类似如下代码中a/b所在目录确认。

    diff --git a/AndroidManifest.xml b/AndroidManifest.xml
    index 4456aa0..ea33f8a 100644
    --- a/AndroidManifest.xml
    +++ b/AndroidManifest.xml
    
    // 进入到a所在目录即可。

    然后执行patch -p1 < patch文件绝对路径,p后面是数字1,即可。

    0001-Ethernet-IP-Add-Framework-Interface.patch这个patch到/frameworks/base目录导入。

    0001-Ethernet-IP-Add-Framework-Function.patch这个patch到/frameworks/opt/net/ethernet目录导入。

    接下来讲解如何通过一个方法来实现9.0以太网设置。

    首先:在应用的清单文件中授权网络权限,主要应该是如下几个。同时

    sharedUserId设置成"android.uid.system"。
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL"/>
    <uses-permission android:name="android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS"/>

    其次:导入framework.jar,因为用到的类都是在framework中的。而且我测试的时候也使用了platform签名。

    最后:终极方法如下,反射方式获取EthernetManager的实例参考 https://blog.csdn.net/aaa1050070637/article/details/79769788

       private static final String TAG = "EthernetUtils";
        /**
         * @param context use Activity or Service context
         * @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
         *   eg. dhcp mode: setEthernetIP(ApplicationContext, "DHCP", "", "", "", "", "");
         *         static mode: setEthernetIP(ApplicationContext, "STATIC",
         *                     "192.168.1.168", "255.255.255.0",
         *                     "192.168.1.1", "114.114.114.114", "8.8.8.8");
         *  for android 9.0
         * */
        public static void setEthernetIP(Context context, String mode, String ipAddress, String netmask,
                                         String gateway, String dns1, String dns2) {
            if (context == null || (!"STATIC".equals(mode) && !"DHCP".equals(mode))) {
                Log.d(TAG, " setEthernetIP failed, param incorrect context=" + context + ", mode=" + mode);
                return;
            }
    
            try {
                // get EthernetManager instance by reflect @{
                Class<?> ethernetManagerClass = Class
                        .forName("android.net.EthernetManager");
                Class<?> iEthernetManagerClass = Class
                        .forName("android.net.IEthernetManager");
                // 获取ETHERNET_SERVICE参数
                String ETHERNET_SERVICE = (String) Context.class.getField(
                        "ETHERNET_SERVICE").get(null);
                // 获取ethernetManager服务对象
                Object ethernetManager = context.getSystemService(ETHERNET_SERVICE);
                // 获取在EthernetManager中的抽象类mService成员变量
                Field mService = ethernetManagerClass.getDeclaredField("mService");
                // 修改private权限
                mService.setAccessible(true);
                // 获取抽象类的实例化对象
                Object mServiceObject = mService.get(ethernetManager);
                Object ethernetManagerInstance = ethernetManagerClass
                        .getDeclaredConstructor(Context.class,
                                iEthernetManagerClass).newInstance(context,
                                mServiceObject);
                EthernetManager mEthManager = (EthernetManager) ethernetManagerInstance;
                // @}
    
                String[] ifaces = mEthManager.getAvailableInterfaces();
                if (ifaces.length <= 0) {
                    Log.e(TAG, " setEthernetIP failed ifaces.length <= 0");
                    return;
                }
                String mInterfaceName = ifaces[0];
                Log.d(TAG, " setEthernetIP mInterfaceName=" + mInterfaceName);
                if ("DHCP".equals(mode)) {
                    Log.i(TAG, " setEthernetIP  set dhcp started");
                    IpConfiguration dhcpConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.DHCP,
                            IpConfiguration.ProxySettings.NONE, null, null);
                    dhcpConfiguration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
                    mEthManager.setConfiguration(mInterfaceName, dhcpConfiguration);
                    return;
                }
    
                if (TextUtils.isEmpty(ipAddress)
                        || TextUtils.isEmpty(netmask) || TextUtils.isEmpty(gateway)
                        || TextUtils.isEmpty(dns1)) {
                    Log.e(TAG, "setEthernetIP error has some param is null ipAddress=" + ipAddress
                            + ", netmask=" + netmask + ", gateway=" + gateway
                            + ", dns1=" + dns1 + ", dns2=" + dns2);
                    return;
                }
                StaticIpConfiguration mStaticIpConfiguration = new StaticIpConfiguration();
                int prefixLength = maskStr2InetMask(netmask);
                InetAddress inetAddr = null;
                InetAddress gatewayAddr = getIPv4Address(gateway);
                InetAddress dnsAddr = getIPv4Address(dns1);
    
                if (TextUtils.isEmpty(ipAddress)) {
                    inetAddr = NetUtils.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, "setEthernetIP  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, " setEthernetIP  address incorrect inetAddr=" + inetAddr);
                    return;
                }
    
                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 {
                    mStaticIpConfiguration.ipAddress = (LinkAddress) cons.newInstance(x);
                    Log.d(TAG, " setEthernetIP mStaticIpConfiguration.ipAddress=" + mStaticIpConfiguration.ipAddress);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
    
                mStaticIpConfiguration.gateway = gatewayAddr;
                mStaticIpConfiguration.dnsServers.add(dnsAddr);
                if (!dns2.isEmpty())
                    mStaticIpConfiguration.dnsServers.add(getIPv4Address(dns2));
    
                Log.d(TAG, " setEthernetIP mStaticIpConfiguration  ====" + mStaticIpConfiguration
                        + ", inetAddr=" + inetAddr + ", mEthManager=" + mEthManager);
    
                IpConfiguration ipConfiguration = new IpConfiguration(IpConfiguration.IpAssignment.STATIC,
                        IpConfiguration.ProxySettings.NONE, mStaticIpConfiguration, null);
                ipConfiguration.setIpAssignment(IpConfiguration.IpAssignment.STATIC);
                ipConfiguration.setStaticIpConfiguration(mStaticIpConfiguration);
                mEthManager.setConfiguration(mInterfaceName, ipConfiguration);
            } catch (Exception e) {
                Log.e(TAG, "setEthernetIP error e=" + e.getMessage(), e);
            }
        }

    注意事项: 该方法最好在Activity或者Fragment中执行,第一个参数使用活动、碎片或服务的context,否则容易报线程不对或初始化以太网管理器的错误,且执行完后需要重启系统才能生效。

    android 9.0 GO系统 framework.jar 见资源:https://download.csdn.net/download/zzhceo/11548681

    2019.12.12补充github工程地址:https://github.com/zzhceo/EthernetStaticIp,欢迎大家点赞收藏。

     

    展开全文
  • 在做android设备时候有设置设备的静态IP,因为这个方法是系统隐藏方法,而且还是9.0的系统目前测试...原博客:安卓9.0设置以太网静态IP地址 博客来源地址:https://blog.csdn.net/zzhceo/article/details/99596435 ...

    在做android设备时候有设置设备的静态IP,因为这个方法是系统隐藏方法,而且还是9.0的系统目前测试验证一下博客的方法可行。

    原博客:安卓9.0设置以太网静态IP地址
    博客来源地址:https://blog.csdn.net/zzhceo/article/details/99596435

    以上只是设置没有获取已经设置的信息,故自己参照以上博客,实现了获取已经设置好的静态IP信息。

    /**
         * 获取静态信息
         */
        public static Map<String, String> getEthernnetIp(Context context) {
            Map<String, String> ipMaps = new HashMap<>(16);
            try {
                String mInterfaceName = "eth0";
                EthernetManager mEthManager = getEthernetManager(context);
                if (mEthManager == null) {
                    return ipMaps;
                }
                String assignMent = mEthManager.getConfiguration(mInterfaceName).ipAssignment.name();
                // if assignMent is dhcp, no need repeat set
                if ("DHCP".equals(assignMent)) {
                    Log.d(TAG, " setEthernetIP mode == assignment = DHCP, no need repeat set");
                    return ipMaps;
                }
                IpConfiguration configuration = mEthManager.getConfiguration(mInterfaceName);
                if (configuration != null) {
                    StaticIpConfiguration staticIpConfiguration = configuration.getStaticIpConfiguration();
                    if (staticIpConfiguration != null) {
                        ArrayList<InetAddress> dnsServers = staticIpConfiguration.dnsServers;
                        InetAddress gateway = staticIpConfiguration.gateway;
                        LinkAddress ipAddress = staticIpConfiguration.ipAddress;
    
                        if (gateway != null) {
                            ipMaps.put("gateway", gateway.getHostAddress());
                        }
                        if (ipAddress != null) {
                            InetAddress address = ipAddress.getAddress();
                            if (address != null) {
                                ipMaps.put("ip", address.getHostAddress());
                            }
    
    //                      int prefixLength = ipAddress.getPrefixLength();
                            String s = ipAddress.toString();
                            String mask = getMask(s);
                            ipMaps.put("mask", mask);
                        }
    
                        if (dnsServers != null && dnsServers.size() > 1) {
                            ipMaps.put("dns", dnsServers.get(0).getHostAddress());
                        }
    
                        Log.d(TAG, ipMaps.toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ipMaps;
        }
    

    然后把,反射进行抽取

     private static EthernetManager getEthernetManager(Context context) {
            // get EthernetManager instance by reflect @{
            Object ethernetManagerInstance = null;
            try {
                Class<?> ethernetManagerClass = Class.forName("android.net.EthernetManager");
                Class<?> iEthernetManagerClass = Class.forName("android.net.IEthernetManager");
                // 获取ETHERNET_SERVICE参数
                String ETHERNET_SERVICE = (String) Context.class.getField("ETHERNET_SERVICE").get(null);
                // 获取ethernetManager服务对象
                Object ethernetManager = context.getSystemService(ETHERNET_SERVICE);
                // 获取在EthernetManager中的抽象类mService成员变量
                Field mService = ethernetManagerClass.getDeclaredField("mService");
                // 修改private权限
                mService.setAccessible(true);
                // 获取抽象类的实例化对象
                Object mServiceObject = mService.get(ethernetManager);
                ethernetManagerInstance = ethernetManagerClass
                        .getDeclaredConstructor(Context.class, iEthernetManagerClass).newInstance(context, mServiceObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return (EthernetManager) ethernetManagerInstance;
        }
    

    子网掩码反转代码:

     /**
         * 数值子网掩码转换成IP的格式
         */
        public static String getMask(String addr) {
            try {
                String[] parts = addr.split("/");
                int prefix;
                if (parts.length < 2) {
                    prefix = 0;
                } else {
                    prefix = Integer.parseInt(parts[1]);
                }
                int mask = 0xffffffff << (32 - prefix);
    
                byte[] bytes = new byte[]{
                        (byte) (mask >>> 24), (byte) (mask >> 16 & 0xff), (byte) (mask >> 8 & 0xff), (byte) (mask & 0xff)};
    
                InetAddress netAddr = InetAddress.getByAddress(bytes);
    
                return netAddr.getHostAddress();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
    
    展开全文
  • 这个项目已经很老了,其实是从 Android 4.4.4 的系统 Settings 中 copy 出来的。 其实原理都是编译运行系统 ...Android 操作以太网的项目,提供了监听网线插拔和以太网开关,设置以太网静态IP、网关、子网掩码、dns等。
  • 公司是做工控和楼宇智能方面产品,使用的设备有rk和全志平台,运行的是android操作系统,部分场景需要设置有线网络的静态Ip。所以针对这一需求做了如下工作,并以此文作为总结。 遇到的问题 工作前也有百度过相关...

    写文目的

    • 公司是做工控和楼宇智能方面产品,使用的设备有rk和全志平台,
      运行的是android操作系统,部分场景需要设置有线网络的静态Ip。
      所以针对这一需求做了如下工作,并以此文作为总结。

    遇到的问题

    • 之前也有百度过相关方案,但大部分使用的是busybox ifconfig来设置,而这种方式有很多弊端,如设置的app必须拥有root权限、不能实时切换static和dhcp、重启后设置的就不生效、不能通过系统的settings参看设置的状态。经过一番折腾后发现为了解决这些问题必须从android的系统应用settings apk入手!

    实现思路

    • 在settings中注册一个静态广播,广播的接收函数中完成ip的设置。当用户层要设置ip时,只需发送广播给settings即可。

    用户app设置样例

    Intent intent = new Intent();
            intent.putExtra("netMode", "static");
            intent.putExtra("ipaddr", "192.168.1.223");
            intent.putExtra("netMask", "255.255.255.0");
            intent.putExtra("gateway", "192.168.1.198");
            intent.putExtra("dns1", "192.168.1.198");
            intent.putExtra("dns2", "8.8.8.8");
            intent.setAction("android.net.action.ETHERNET_IP_CHANGED");
            sendBroadcast(intent);
    

    settings修改部分

    一、修改AndroidManifest.xml
    1.新增如下内容

    <uses-permission android:name="android.net.action.ETHERNET_IP_CHANGED"/>
    <receiver android:name="com.android.settings.EtherentBoardcastReceive"
    			 android:enabled="true"
    			 android:exported="true">
                 <intent-filter android:priority="1000">
                    <action android:name="android.net.action.ETHERNET_IP_CHANGED" />
                </intent-filter>
            </receiver>
    

    2.在目录Settings\src\com\android\settings\ethernet 下新增文件EtherentBoardcastReceive.java

    package com.android.settings;
    
    import com.android.settings.R;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.Dialog;
    import android.app.admin.DevicePolicyManager;
    import android.content.ActivityNotFoundException;
    import android.content.BroadcastReceiver;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.pm.PackageManager;
    import android.content.res.Resources;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.SystemProperties;
    import android.os.UserHandle;
    import android.os.UserManager;
    import android.preference.CheckBoxPreference;
    //import android.preference.Preference;
    import android.preference.Preference.OnPreferenceChangeListener;
    import android.preference.PreferenceScreen;
    //import android.preference.SwitchPreference;
    import android.support.v14.preference.SwitchPreference;
    import android.support.v7.preference.ListPreference;
    import android.support.v7.preference.Preference;
    import android.provider.SearchIndexableResource;
    import android.provider.Settings;
    import android.telephony.TelephonyManager;
    import android.text.TextUtils;
    import android.util.Log;
    import android.content.Intent;
    
    import java.io.File;
    import java.io.FileDescriptor;
    import java.io.File;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.File;
    import java.io.FileDescriptor;
    import java.io.File;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    import java.util.regex.Pattern;
    import java.lang.Integer;
    import java.net.InetAddress;
    import java.net.Inet4Address;
    import java.util.Iterator;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.List;
    
    
    
    /*for 5.0*/
    import android.net.EthernetManager;
    import android.net.IpConfiguration;
    import android.net.IpConfiguration.IpAssignment;
    import android.net.IpConfiguration.ProxySettings;
    import android.net.wifi.SupplicantState;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiManager;
    import android.net.StaticIpConfiguration;
    import android.net.NetworkUtils;
    import android.net.LinkAddress;
    import android.net.LinkProperties;
    //import android.preference.ListPreference;
    import com.android.internal.logging.MetricsProto.MetricsEvent;
    
    import com.android.settings.ethernet_static_ip_dialog;
    import com.android.settings.pppoe_dialog;
    
    import com.android.settings.EthernetSettings;  
    
    public class EtherentBoardcastReceive extends BroadcastReceiver  {
    	private static final String TAG = "EtherentBoardcastReceive";
    	 
    	private  static String mEthMode = null;//"static";
        private  static String mEthIpAddress = null;//"192.168.1.254";
        private  static String mEthNetmask = null;//"255.255.255.0";
        private  static String mEthGateway = null;//"192.168.1.1";
        private  static String mEthdns1 = null;//"192.168.1.1";
        private  static String mEthdns2 = null;//"null";
    
        private final static String nullIpInfo = "0.0.0.0";
    
    	 @Override
        public void onReceive(Context context, Intent intent) {
    
    			IpConfiguration mIpConfiguration;
    			StaticIpConfiguration mStaticIpConfiguration;
    			String action = intent.getAction();
    		    Log.i(TAG, "receive a new action : " + action);
    			
    			EthernetManager mEthManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
    			if(mEthManager == null){
    				Log.i(TAG, "fail to getSystemService :  "+Context.ETHERNET_SERVICE);
    			}
    
    		  mStaticIpConfiguration =new StaticIpConfiguration();
    		  getNetConfigFromIntent(intent);
    		 /*
    		  * get ip address, netmask,dns ,gw etc.
    		  */
    		
    
    
    		if (mEthMode  == null ||mEthMode.equals("static"))
    		{
    			 Inet4Address inetAddr = getIPv4Address(this.mEthIpAddress);
    			int prefixLength = maskStr2InetMask(this.mEthNetmask); 
    			InetAddress gatewayAddr = getIPv4Address(this.mEthGateway); 
    			InetAddress dnsAddr1 = getIPv4Address(this.mEthdns1);
    			InetAddress dnsAddr2 = getIPv4Address(this.mEthdns2);
    			if(inetAddr ==null || gatewayAddr == null || prefixLength <= 0  ){
    				  Log.e(TAG,"ip,mask or dnsAddr is wrong");
    				  return ;
    			}
    			if (inetAddr.getAddress().toString().isEmpty() || prefixLength ==0 || gatewayAddr.toString().isEmpty()
    			  ) {
    				   Log.e(TAG,"ip,mask or dnsAddr is wrong");
    				  return ;
    			}
    			  
    			mStaticIpConfiguration.ipAddress = new LinkAddress(inetAddr, prefixLength);
    			mStaticIpConfiguration.gateway=gatewayAddr;
    			if(dnsAddr1 != null && !dnsAddr1.toString().isEmpty())
    				mStaticIpConfiguration.dnsServers.add(dnsAddr1);
    			if(dnsAddr2 != null && !dnsAddr2.toString().isEmpty())
    				mStaticIpConfiguration.dnsServers.add(dnsAddr2);
    		
    			mIpConfiguration=new IpConfiguration(IpAssignment.STATIC, ProxySettings.NONE,mStaticIpConfiguration,null);  
    			mEthManager.setConfiguration(mIpConfiguration); 
    		}else{
    			mEthManager.setConfiguration(new IpConfiguration(IpAssignment.DHCP, ProxySettings.NONE,null,null));
    		}
           
    		//
    		
        }
    	
    	private void getNetConfigFromIntent(Intent intent){
    		Bundle bundle = intent.getExtras();
            if (bundle.getString("netMode") != null)
    			this.mEthMode = bundle.getString("netMode");
    		if (bundle.getString("ipaddr") != null)
    			this.mEthIpAddress = bundle.getString("ipaddr");
    		if (bundle.getString("netMask")!= null)
    			this.mEthNetmask = bundle.getString("netMask");
    		if (bundle.getString("gateway")!= null)
    			this.mEthGateway = bundle.getString("gateway");
    		if (bundle.getString("dns1") != null)
    			this.mEthdns1 = bundle.getString("dns1");
    		if (bundle.getString("dns2") != null)
    			this.mEthdns2 = bundle.getString("dns2");
    	}
    	 private Inet4Address getIPv4Address(String text) {
            try {
                return (Inet4Address) NetworkUtils.numericToInetAddress(text);
            } catch (IllegalArgumentException|ClassCastException e) {
                return null;
            }
        }
    
    	 /*
         * convert subMask string to prefix length
         */
        private int maskStr2InetMask(String maskStr) {
        	StringBuffer sb ;
        	String str;
        	int inetmask = 0; 
        	int count = 0;
        	/*
        	 * check the subMask format
        	 */
          	Pattern pattern = Pattern.compile("(^((\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])$)|^(\\d|[1-2]\\d|3[0-2])$");
        	if (pattern.matcher(maskStr).matches() == false) {
        		Log.e(TAG,"subMask is error");
        		return 0;
        	}
        	
        	String[] ipSegment = maskStr.split("\\.");
        	for(int n =0; n<ipSegment.length;n++) {
        		sb = new StringBuffer(Integer.toBinaryString(Integer.parseInt(ipSegment[n])));
        		str = sb.reverse().toString();
        		count=0;
        		for(int i=0; i<str.length();i++) {
        			i=str.indexOf("1",i);
        			if(i==-1)  
        				break;
        			count++;
        		}
        		inetmask+=count;
        	}
        	return inetmask;
        }
    
    
    
    }
    
    

    代码就不多介绍了,大体流程是接收到广播后就解析字符串后进行IP设置
    ,有明白处可给我留言。

    展开全文
  • Android 9.0 以太网静态IP设置

    千次阅读 2020-09-11 10:42:15
    吐槽一下,官方貌似没有以太网和WiFi的配置流程,网络设置这部分主要借鉴的是Settings中的内容 以太网配置需要使用EthernetManager类,我们看下这个类的特点: /** * A class representing the IP configuration ...
  • 在做机顶盒项目的时候,有个需求是这样的: ...3、如果是动态IP,可以设置成静态的,然后设置静态IP、网关等信息。 项目完成后,就把以太网相关的抽出来了,现在放出来,顺便记录记录! apk需要放置到/
  • Android9.0目前网络上没有关于以太网静态IP设置功能的资料,求大神有空做一下提供一下补丁。基于Android9.0源码。。。目前能重写IP了,就是重写IP后无法联网。重写以太网静态IP的补丁如下:[Ethernet Setting]...
  • EthernetManager Android 以太网静态IP设置

    万次阅读 热门讨论 2016-08-01 12:37:59
    关于以太网设置由于公司的需求,需要在项目中加入设置以太网静态IP的功能,在网上找了一下,发 现这方面的资料比较少最后只找到了一个demo,但是导入后发现项目报错.之后查了一下资料才发现原来EthernetManager是谷歌...
  • 设置 -> 更多 -> 以太网功能: 1. 支持以太网开启与禁用 2. 支持以太网静态IP和动态获取切换
  • Android客制化------设置以太网静态IP

    千次阅读 2017-11-24 09:37:47
    最近有个功能,机器连接以太网之后能够通过app获取ip地址,网关,子网掩码等信息,同时还能去手动设置静态ip。在网上查阅了相关资料,这方面的API在Android都是被hide的,通过反射等方式去调用比较麻烦。而我们...
  • 本补丁是在安卓6.0.1设置界面增加以太网静态IP配置功能,基于全志A64平台,SDK_V2.1.1安卓6.0.1 补丁名称里已经包含了路径,在源码对应路径用patch -p1 即可
  • android 以太网设置静态ip

    千次阅读 2018-04-26 09:01:01
    先是查到了以下的方法,发现是设置Wi-Fi的。 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentResolver cr = this....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,128
精华内容 851
关键字:

安卓设置以太网静态ip