当前位置:   article > 正文

Android13 原生以太网实现设置静态IP_android 13 以太网

android 13 以太网

一、引言


        首先需要实现android13设置静态IP的功能,就要对android13以太网架构变化大致理解,谷歌把以太网相关的功能进行模块化,提取到packages/modules/Connectivity/目录,导致之前的实现需要调整,本文主要从2大块进行阐述,分别为framework与原生Settings。

        本文涉及功能点主要有如下几点:

        1.设置IP的方式分为DHCP和静态两种

        2.IP地址的设置

        3.子网掩码设置

        4.DNS设置

        5.网关设置

        6.代理设置

二、Framework部分

        2.1、涉及修改的类

  1. packages/modules/Connectivity/framework-t/api/module-lib-current.txt
  2. packages/modules/Connectivity/framework-t/src/android/net/EthernetManager.java
  3. packages/modules/Connectivity/framework-t/src/android/net/IEthernetManager.aidl
  4. packages/modules/Connectivity/framework/api/current.txt
  5. packages/modules/Connectivity/framework/api/system-current.txt
  6. packages/modules/Connectivity/framework/src/android/net/IpConfiguration.java
  7. packages/modules/Connectivity/framework/src/android/net/ProxyInfo.java
  8. packages/modules/Connectivity/service-t/src/com/android/server/ethernet/EthernetNetworkFactory.java
  9. packages/modules/Connectivity/service-t/src/com/android/server/ethernet/EthernetServiceImpl.java
  10. packages/modules/Connectivity/service-t/src/com/android/server/ethernet/EthernetTracker.java

        2.2、涉及类修改阐述

                android其实不管怎么更新,都离不开client-aidl-server这样的模式,所以大体思路就是根

                据以太网源码框架,在其上模仿原有的接口进行添加内容的方式,先把路打通。

                2.2.1、客户端接口添加及修改

1.IEthernetManager.aidl类中添加4个接口,提供给上层使用

  1. /*
  2. * Copyright (C) 2014 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package android.net;
  17. import android.net.IpConfiguration;
  18. import android.net.IEthernetServiceListener;
  19. import android.net.EthernetNetworkManagementException;
  20. import android.net.EthernetNetworkUpdateRequest;
  21. import android.net.INetworkInterfaceOutcomeReceiver;
  22. import android.net.ITetheredInterfaceCallback;
  23. import java.util.List;
  24. /**
  25. * Interface that answers queries about, and allows changing
  26. * ethernet configuration.
  27. */
  28. /** {@hide} */
  29. interface IEthernetManager
  30. {
  31. String[] getAvailableInterfaces();
  32. IpConfiguration getConfiguration(String iface);
  33. void setConfiguration(String iface, in IpConfiguration config);
  34. boolean isAvailable(String iface);
  35. void addListener(in IEthernetServiceListener listener);
  36. void removeListener(in IEthernetServiceListener listener);
  37. void setIncludeTestInterfaces(boolean include);
  38. void requestTetheredInterface(in ITetheredInterfaceCallback callback);
  39. void releaseTetheredInterface(in ITetheredInterfaceCallback callback);
  40. void updateConfiguration(String iface, in EthernetNetworkUpdateRequest request,
  41. in INetworkInterfaceOutcomeReceiver listener);
  42. void connectNetwork(String iface, in INetworkInterfaceOutcomeReceiver listener);
  43. void disconnectNetwork(String iface, in INetworkInterfaceOutcomeReceiver listener);
  44. void setEthernetEnabled(boolean enabled);
  45. List<String> getInterfaceList();
  46. //added by cgt Adding an Ethernet Interface start
  47. String getIpAddress(String iface);
  48. String getNetmask(String iface);
  49. String getGateway(String iface);
  50. String getDns(String iface);
  51. //added by cgt Adding an Ethernet Interface end
  52. }

2.EthernetManager.java类中实现aidl中的4个接口,并修改android13 APP调用以太网API时受限制

  1. import java.util.Objects;
  2. import java.util.concurrent.Executor;
  3. import java.util.function.IntConsumer;
  4. +//added by cgt Adding an Ethernet Interface start
  5. +import java.net.InetAddress;
  6. +import android.net.NetworkUtils;
  7. +//added by cgt Adding an Ethernet Interface end
  8. /**
  9. * A class that manages and configures Ethernet interfaces.
  10. @@ -191,8 +195,15 @@ public class EthernetManager {
  11. * @return the Ethernet Configuration, contained in {@link IpConfiguration}.
  12. * @hide
  13. */
  14. - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  15. - public IpConfiguration getConfiguration(String iface) {
  16. + //added by cgt Adding an Ethernet Interface start
  17. + /*@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  18. + public IpConfiguration getConfiguration(String iface) {*/
  19. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  20. + @SystemApi(client = MODULE_LIBRARIES)
  21. + @NonNull
  22. + @UnsupportedAppUsage
  23. + public IpConfiguration getConfiguration(@NonNull String iface) {
  24. + //added by cgt Adding an Ethernet Interface end
  25. try {
  26. return mService.getConfiguration(iface);
  27. } catch (RemoteException e) {
  28. @@ -204,7 +215,13 @@ public class EthernetManager {
  29. * Set Ethernet configuration.
  30. * @hide
  31. */
  32. - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  33. + //added by cgt Adding an Ethernet Interface start
  34. + //@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  35. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  36. + @SystemApi(client = MODULE_LIBRARIES)
  37. + @NonNull
  38. + @UnsupportedAppUsage
  39. + //added by cgt Adding an Ethernet Interface end
  40. public void setConfiguration(@NonNull String iface, @NonNull IpConfiguration config) {
  41. try {
  42. mService.setConfiguration(iface, config);
  43. @@ -217,7 +234,10 @@ public class EthernetManager {
  44. * Indicates whether the system currently has one or more Ethernet interfaces.
  45. * @hide
  46. */
  47. - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  48. + //added by cgt Adding an Ethernet Interface start
  49. + //@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  50. + @UnsupportedAppUsage
  51. + //modified by cengt,ethernet,Adding an Ethernet Interface,20230628-end
  52. public boolean isAvailable() {
  53. return getAvailableInterfaces().length > 0;
  54. }
  55. @@ -228,7 +248,10 @@ public class EthernetManager {
  56. * @param iface Ethernet interface name
  57. * @hide
  58. */
  59. - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  60. + //added by cgt Adding an Ethernet Interface start
  61. + //@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  62. + @UnsupportedAppUsage
  63. + //added by cgt Adding an Ethernet Interface end
  64. public boolean isAvailable(String iface) {
  65. try {
  66. return mService.isAvailable(iface);
  67. @@ -318,7 +341,13 @@ public class EthernetManager {
  68. * Returns an array of available Ethernet interface names.
  69. * @hide
  70. */
  71. - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  72. + //added by cgt Adding an Ethernet Interface start
  73. + //@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  74. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  75. + @SystemApi(client = MODULE_LIBRARIES)
  76. + @NonNull
  77. + @UnsupportedAppUsage
  78. + //added by cgt Adding an Ethernet Interface end
  79. public String[] getAvailableInterfaces() {
  80. try {
  81. return mService.getAvailableInterfaces();
  82. @@ -696,9 +725,12 @@ public class EthernetManager {
  83. * is available or not currently.
  84. * @hide
  85. */
  86. + //added by cgt Adding an Ethernet Interface start
  87. + //@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  88. @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  89. @SystemApi(client = MODULE_LIBRARIES)
  90. @NonNull
  91. + //added by cgt Adding an Ethernet Interface end
  92. public List<String> getInterfaceList() {
  93. try {
  94. return mService.getInterfaceList();
  95. @@ -706,4 +738,78 @@ public class EthernetManager {
  96. throw e.rethrowAsRuntimeException();
  97. }
  98. }
  99. +
  100. + //added by cgt Adding an Ethernet Interface start
  101. + /**
  102. + * @hide
  103. + */
  104. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  105. + @SystemApi(client = MODULE_LIBRARIES)
  106. + @NonNull
  107. + @UnsupportedAppUsage
  108. + public String getIpAddress(@NonNull String iface) {
  109. + try {
  110. + return mService.getIpAddress(iface);
  111. + } catch (RemoteException e) {
  112. + throw e.rethrowFromSystemServer();
  113. + }
  114. + }
  115. +
  116. + /**
  117. + * @hide
  118. + */
  119. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  120. + @SystemApi(client = MODULE_LIBRARIES)
  121. + @NonNull
  122. + @UnsupportedAppUsage
  123. + public String getNetmask(@NonNull String iface) {
  124. + try {
  125. + return mService.getNetmask(iface);
  126. + } catch (RemoteException e) {
  127. + throw e.rethrowFromSystemServer();
  128. + }
  129. + }
  130. +
  131. + /**
  132. + * @hide
  133. + */
  134. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  135. + @SystemApi(client = MODULE_LIBRARIES)
  136. + @NonNull
  137. + @UnsupportedAppUsage
  138. + public String getGateway(@NonNull String iface) {
  139. + try {
  140. + return mService.getGateway(iface);
  141. + } catch (RemoteException e) {
  142. + throw e.rethrowFromSystemServer();
  143. + }
  144. + }
  145. +
  146. + /**
  147. + * @hide
  148. + */
  149. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  150. + @SystemApi(client = MODULE_LIBRARIES)
  151. + @NonNull
  152. + @UnsupportedAppUsage
  153. + public String getDns(@NonNull String iface) {
  154. + try {
  155. + return mService.getDns(iface);
  156. + } catch (RemoteException e) {
  157. + throw e.rethrowFromSystemServer();
  158. + }
  159. + }
  160. +
  161. + /**
  162. + * @hide
  163. + */
  164. + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  165. + @SystemApi(client = MODULE_LIBRARIES)
  166. + @NonNull
  167. + @UnsupportedAppUsage
  168. + public static InetAddress iminNumericToInetAddress(@NonNull String text) {
  169. + return NetworkUtils.numericToInetAddress(text);
  170. + }
  171. + //added by cgt Adding an Ethernet Interface end
  172. +
  173. }

3.module-lib-current.txt类中实现aidl添加接口后系统编译的文件,此文件也可以自行使用make update-api编译生成,如不想编译直接自己实现

  1. +++ b/XXX/packages/modules/Connectivity/framework-t/api/module-lib-current.txt
  2. @@ -44,9 +44,17 @@ package android.net {
  3. public class EthernetManager {
  4. method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void addEthernetStateListener(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.IntConsumer);
  5. method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void addInterfaceStateListener(@NonNull java.util.concurrent.Executor, @NonNull android.net.EthernetManager.InterfaceStateListener);
  6. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public String[] getAvailableInterfaces();
  7. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public android.net.IpConfiguration getConfiguration(@NonNull String);
  8. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public String getDns(@NonNull String);
  9. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public String getGateway(@NonNull String);
  10. method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public java.util.List<java.lang.String> getInterfaceList();
  11. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public String getIpAddress(@NonNull String);
  12. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public String getNetmask(@NonNull String);
  13. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public static java.net.InetAddress iminNumericToInetAddress(@NonNull String);
  14. method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void removeEthernetStateListener(@NonNull java.util.function.IntConsumer);
  15. method public void removeInterfaceStateListener(@NonNull android.net.EthernetManager.InterfaceStateListener);
  16. + method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void setConfiguration(@NonNull String, @No
  17. nNull android.net.IpConfiguration);
  18. method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK
  19. , android.Manifest.permission.NETWORK_SETTINGS}) public void setEthernetEnabled(boolean);
  20. method public void setIncludeTestInterfaces(boolean);
  21. field public static final int ETHERNET_STATE_DISABLED = 0; // 0x0

4.current.txt类中添加ProxyInfo两个构造函数

  1. +++ b/XXX/packages/modules/Connectivity/framework/api/current.txt
  2. @@ -445,6 +445,8 @@ package android.net {
  3. }
  4. public class ProxyInfo implements android.os.Parcelable {
  5. + ctor public ProxyInfo(@NonNull String, int, @NonNull String);
  6. + ctor public ProxyInfo(@NonNull android.net.Uri);
  7. ctor public ProxyInfo(@Nullable android.net.ProxyInfo);
  8. method public static android.net.ProxyInfo buildDirectProxy(String, int);
  9. method public static android.net.ProxyInfo buildDirectProxy(String, int, java.util.List<java.lang.String>);

5.system-current.txt类中添加两个函数

  1. +++ b/xxx/packages/modules/Connectivity/framework/api/system-current.txt
  2. @@ -126,6 +126,7 @@ package android.net {
  3. public final class IpConfiguration implements android.os.Parcelable {
  4. ctor public IpConfiguration();
  5. + ctor public IpConfiguration(@NonNull android.net.IpConfiguration.IpAssignment, @NonNull android.net.IpConfiguration.ProxySettings, @NonNull android.net.StaticIpConfiguration, @NonNull android.net.ProxyInfo);
  6. ctor public IpConfiguration(@NonNull android.net.IpConfiguration);
  7. method @NonNull public android.net.IpConfiguration.IpAssignment getIpAssignment();
  8. method @NonNull public android.net.IpConfiguration.ProxySettings getProxySettings();

6.IpConfiguration.java类中修改android13 APP调用以太网API时受限制

  1. +++ b/xxx/packages/modules/Connectivity/framework/src/android/net/IpConfiguration.java
  2. @@ -103,11 +103,14 @@ public final class IpConfiguration implements Parcelable {
  3. }
  4. /** @hide */
  5. - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  6. - public IpConfiguration(IpAssignment ipAssignment,
  7. - ProxySettings proxySettings,
  8. - StaticIpConfiguration staticIpConfiguration,
  9. - ProxyInfo httpProxy) {
  10. + //added by cgt Adding an Ethernet Interface start
  11. + //@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  12. + @SystemApi
  13. + //added by cgt Adding an Ethernet Interface end
  14. + public IpConfiguration(@NonNull IpAssignment ipAssignment,
  15. + @NonNull ProxySettings proxySettings,
  16. + @NonNull StaticIpConfiguration staticIpConfiguration,
  17. + @NonNull ProxyInfo httpProxy) {
  18. init(ipAssignment, proxySettings, staticIpConfiguration, httpProxy);
  19. }

7.ProxyInfo.java类中修改android13 APP调用以太网API时受限制

  1. +++ b/xxx/packages/modules/Connectivity/framework/src/android/net/ProxyInfo.java
  2. @@ -103,10 +103,11 @@ public class ProxyInfo implements Parcelable {
  3. /**
  4. * Create a ProxyProperties that points at a HTTP Proxy.
  5. - * @hide
  6. */
  7. - @UnsupportedAppUsage
  8. - public ProxyInfo(String host, int port, String exclList) {
  9. + //added by cgt Adding an Ethernet Interface start
  10. + //@UnsupportedAppUsage
  11. + //added by cgt Adding an Ethernet Interface end
  12. + public ProxyInfo(@NonNull String host, int port, @NonNull String exclList) {
  13. mHost = host;
  14. mPort = port;
  15. mExclusionList = exclList;
  16. @@ -116,7 +117,6 @@ public class ProxyInfo implements Parcelable {
  17. /**
  18. * Create a ProxyProperties that points at a PAC URL.
  19. - * @hide
  20. */
  21. public ProxyInfo(@NonNull Uri pacFileUrl) {
  22. mHost = LOCAL_HOST;
                2.2.2、客户端接口添加及修改

1.EthernetNetworkFactory.java类中实现4个接口

  1. +++ b/xxx/packages/modules/Connectivity/service-t/src/com/android/server/ethernet/EthernetNetworkFactory.java
  2. @@ -58,6 +58,17 @@ import java.io.FileDescriptor;
  3. import java.util.Objects;
  4. import java.util.Set;
  5. import java.util.concurrent.ConcurrentHashMap;
  6. +//added by cgt Adding an Ethernet Interface start
  7. +import android.net.EthernetManager;
  8. +import android.net.LinkAddress;
  9. +import android.net.NetworkUtils;
  10. +import android.net.RouteInfo;
  11. +import java.net.Inet4Address;
  12. +import java.net.InetAddress;
  13. +import android.net.LinkAddress;
  14. +import android.net.NetworkUtils;
  15. +import android.net.RouteInfo;
  16. +//added by cgt Adding an Ethernet Interface end
  17. /**
  18. * {@link NetworkProvider} that manages NetworkOffers for Ethernet networks.
  19. @@ -118,7 +129,114 @@ public class EthernetNetworkFactory {
  20. mContext = context;
  21. mProvider = provider;
  22. mDeps = deps;
  23. + //added by cgt Adding an Ethernet Interface start
  24. + mEthernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE);
  25. + //added by cgt Adding an Ethernet Interface end
  26. + }
  27. +
  28. + //added by cgt Adding an Ethernet Interface start
  29. + private EthernetManager mEthernetManager;
  30. + String getIpAddress(String iface) {
  31. + if(mEthernetManager == null){
  32. + mEthernetManager = (EthernetManager) mContext.getSystemService(Context.ETHERNET_SERVICE);
  33. + }
  34. + IpConfiguration config = mEthernetManager.getConfiguration(iface);
  35. + if (config.getIpAssignment() == IpAssignment.STATIC) {
  36. + return config.getStaticIpConfiguration().ipAddress.getAddress().getHostAddress();
  37. + } else {
  38. + NetworkInterfaceState netState = mTrackingInterfaces.get(iface);
  39. + if (null != netState) {
  40. + for (LinkAddress l : netState.mLinkProperties.getLinkAddresses()) {
  41. + InetAddress source = l.getAddress();
  42. + //Log.d(TAG, "getIpAddress: " + source.getHostAddress());
  43. + if (source instanceof Inet4Address) {
  44. + return source.getHostAddress();
  45. + }
  46. + }
  47. + }
  48. + }
  49. + return "";
  50. + }
  51. +
  52. + private String prefix2netmask(int prefix) {
  53. + // convert prefix to netmask
  54. + if (true) {
  55. + int mask = 0xFFFFFFFF << (32 - prefix);
  56. + //Log.d(TAG, "mask = " + mask + " prefix = " + prefix);
  57. + return ((mask>>>24) & 0xff) + "." + ((mask>>>16) & 0xff) + "." + ((mask>>>8) & 0xff) + "." + ((mask) & 0xff);
  58. + } else {
  59. + return NetworkUtils.intToInetAddress(NetworkUtils.prefixLengthToNetmaskInt(prefix)).getHostName();
  60. + }
  61. + }
  62. +
  63. + String getNetmask(String iface) {
  64. + if(mEthernetManager == null){
  65. + mEthernetManager = (EthernetManager) mContext.getSystemService(Context.ETHERNET_SERVICE);
  66. + }
  67. + IpConfiguration config = mEthernetManager.getConfiguration(iface);
  68. + if (config.getIpAssignment() == IpAssignment.STATIC) {
  69. + return prefix2netmask(config.getStaticIpConfiguration().ipAddress.getPrefixLength());
  70. + } else {
  71. + NetworkInterfaceState netState = mTrackingInterfaces.get(iface);
  72. + if (null != netState) {
  73. + for (LinkAddress l : netState.mLinkProperties.getLinkAddresses()) {
  74. + InetAddress source = l.getAddress();
  75. + if (source instanceof Inet4Address) {
  76. + return prefix2netmask(l.getPrefixLength());
  77. + }
  78. + }
  79. + }
  80. + }
  81. + return "";
  82. + }
  83. +
  84. + String getGateway(String iface) {
  85. + if(mEthernetManager == null){
  86. + mEthernetManager = (EthernetManager) mContext.getSystemService(Context.ETHERNET_SERVICE);
  87. + }
  88. + IpConfiguration config = mEthernetManager.getConfiguration(iface);
  89. + if (config.getIpAssignment() == IpAssignment.STATIC) {
  90. + return config.getStaticIpConfiguration().gateway.getHostAddress();
  91. + } else {
  92. + NetworkInterfaceState netState = mTrackingInterfaces.get(iface);
  93. + if (null != netState) {
  94. + for (RouteInfo route : netState.mLinkProperties.getRoutes()) {
  95. + if (route.hasGateway()) {
  96. + InetAddress gateway = route.getGateway();
  97. + if (route.isIPv4Default()) {
  98. + return gateway.getHostAddress();
  99. + }
  100. + }
  101. + }
  102. + }
  103. + }
  104. + return "";
  105. + }
  106. +
  107. + /*
  108. + * return dns format: "8.8.8.8,4.4.4.4"
  109. + */
  110. + String getDns(String iface) {
  111. + if(mEthernetManager == null){
  112. + mEthernetManager = (EthernetManager) mContext.getSystemService(Context.ETHERNET_SERVICE);
  113. + }
  114. + String dns = "";
  115. + IpConfiguration config = mEthernetManager.getConfiguration(iface);
  116. + if (config.getIpAssignment() == IpAssignment.STATIC) {
  117. + for (InetAddress nameserver : config.getStaticIpConfiguration().dnsServers) {
  118. + dns += nameserver.getHostAddress() + ",";
  119. + }
  120. + } else {
  121. + NetworkInterfaceState netState = mTrackingInterfaces.get(iface);
  122. + if (null != netState) {
  123. + for (InetAddress nameserver : netState.mLinkProperties.getDnsServers()) {
  124. + dns += nameserver.getHostAddress() + ",";
  125. + }
  126. + }
  127. + }
  128. + return dns;
  129. }
  130. + //added by cgt Adding an Ethernet Interface end
  131. /**
  132. * Registers the network provider with the system.

2.EthernetTracker.java类中调用EthernetNetworkFactory类中的接口,修改updateInterfaceState方法的访问范围供APP使用

  1. +++ b/xxx/packages/modules/Connectivity/service-t/src/com/android/server/ethernet/EthernetTracker.java
  2. @@ -173,6 +173,24 @@ public class EthernetTracker {
  3. mConfigStore = new EthernetConfigStore();
  4. }
  5. + //added by cgt Adding an Ethernet Interface start
  6. + String getIpAddress(String iface) {
  7. + return mFactory.getIpAddress(iface);
  8. + }
  9. +
  10. + String getNetmask(String iface) {
  11. + return mFactory.getNetmask(iface);
  12. + }
  13. +
  14. + String getGateway(String iface) {
  15. + return mFactory.getGateway(iface);
  16. + }
  17. +
  18. + String getDns(String iface) {
  19. + return mFactory.getDns(iface);
  20. + }
  21. + //added by cgt Adding an Ethernet Interface end
  22. +
  23. void start() {
  24. mFactory.register();
  25. mConfigStore.read();
  26. @@ -533,7 +551,10 @@ public class EthernetTracker {
  27. }
  28. }
  29. - private void updateInterfaceState(String iface, boolean up) {
  30. + //added by cgt Adding an Ethernet Interface start
  31. + //private void updateInterfaceState(String iface, boolean up) {
  32. + public void updateInterfaceState(String iface, boolean up) {
  33. + //added by cgt Adding an Ethernet Interface end
  34. updateInterfaceState(iface, up, null /* listener */);
  35. }

3.EthernetServiceImpl.java类中调用EthernetTracker类中的接口,供给APP用

  1. +++ b/xxx/packages/modules/Connectivity/service-t/src/com/android/server/ethernet/EthernetServiceImpl.java
  2. @@ -122,8 +122,57 @@ public class EthernetServiceImpl extends IEthernetManager.Stub {
  3. // TODO: this does not check proxy settings, gateways, etc.
  4. // Fix this by making IpConfiguration a complete representation of static configuration.
  5. mTracker.updateIpConfiguration(iface, new IpConfiguration(config));
  6. }
  7. + //added by cgt Adding an Ethernet Interface start
  8. + @Override
  9. + public String getIpAddress(String iface) {
  10. + PermissionUtils.enforceAccessNetworkStatePermission(mContext, TAG);
  11. + if (mTracker.isRestrictedInterface(iface)) {
  12. + PermissionUtils.enforceRestrictedNetworkPermission(mContext, TAG);
  13. + }
  14. +
  15. + return mTracker.getIpAddress(iface);
  16. + }
  17. +
  18. + @Override
  19. + public String getNetmask(String iface) {
  20. + PermissionUtils.enforceAccessNetworkStatePermission(mContext, TAG);
  21. + if (mTracker.isRestrictedInterface(iface)) {
  22. + PermissionUtils.enforceRestrictedNetworkPermission(mContext, TAG);
  23. + }
  24. +
  25. + return mTracker.getNetmask(iface);
  26. + }
  27. +
  28. + @Override
  29. + public String getGateway(String iface) {
  30. + PermissionUtils.enforceAccessNetworkStatePermission(mContext, TAG);
  31. + if (mTracker.isRestrictedInterface(iface)) {
  32. + PermissionUtils.enforceRestrictedNetworkPermission(mContext, TAG);
  33. + }
  34. +
  35. + return mTracker.getGateway(iface);
  36. + }
  37. +
  38. + @Override
  39. + public String getDns(String iface) {
  40. + PermissionUtils.enforceAccessNetworkStatePermission(mContext, TAG);
  41. + if (mTracker.isRestrictedInterface(iface)) {
  42. + PermissionUtils.enforceRestrictedNetworkPermission(mContext, TAG);
  43. + }
  44. +
  45. + return mTracker.getDns(iface);
  46. + }
  47. + //added by cgt Adding an Ethernet Interface end
  48. +
  49. /**
  50. * Indicates whether given interface is available.
  51. */

三、Settings部分

        3.1、涉及修改的类

  1. Settings/AndroidManifest.xml
  2. Settings/res/layout/static_ip_dialog.xml
  3. Settings/res/xml/imin_ethernet_settings.xml
  4. Settings/res/xml/network_provider_internet.xml
  5. Settings/src/com/android/settings/core/gateway/SettingsGateway.java
  6. Settings/src/com/android/settings/ethernet/EtherentStaticIpDialog.java
  7. Settings/src/com/android/settings/ethernet/EthernetSettingsPreferenceController.java
  8. Settings/src/com/android/settings/ethernet/IminEthernetSettings.java
  9. Settings/src/com/android/settings/ethernet/getStaticIpInfo.java

        3.2、涉及类修改的类

                Settings中添加一个界面去设置以太网相关的内容,我们可以仿照原生在网络中添加一项

                以太网设置,供用户使用,以下简略描述下实现相关。

                3.2.1、资源类

1.AndroidManifest.xml类中配置添加的以太网界面

  1. +++ b/packages/apps/Settings/AndroidManifest.xml
  2. @@ -801,9 +801,28 @@
  3. android:value="@string/menu_key_network"/>
  4. </activity>
  5. + <!--added by cgt Adding an Ethernet Interface start -->
  6. + <activity android:name="Settings$EthernetSettingsActivity"
  7. + android:label="@string/ethernet_settings_title"
  8. + android:icon="@drawable/ic_settings_wireless"
  9. + android:exported="true"
  10. + android:taskAffinity="">
  11. + <intent-filter>
  12. + <action android:name="android.intent.action.MAIN" />
  13. + <category android:name="android.intent.category.DEFAULT" />
  14. + <category android:name="android.intent.category.VOICE_LAUNCH" />
  15. + <category android:name="com.android.settings.SHORTCUT" />
  16. + </intent-filter>
  17. + <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
  18. + android:value="com.android.settings.ethernet.IminEthernetSettings" />
  19. + </activity>
  20. + <!--added by cgt Adding an Ethernet Interface end -->
  21. <!-- Keep compatibility with old shortcuts. -->
  22. - <activity-alias android:name=".TetherSettings"
  23. + <!--added by cgt Adding an Ethernet Interface start -->
  24. + <!--<activity-alias android:name=".TetherSettings" -->
  25. + <!--added by cgt Adding an Ethernet Interface end -->
  26. + <activity-alias android:name=".TestEthernetSettings"
  27. android:label="@string/tether_settings_title_all"
  28. android:clearTaskOnLaunch="true"
  29. android:exported="true"

2.network_provider_internet.xml类中配置添加显示在网络选项中的以太网项

  1. +++ b/Settings/res/xml/network_provider_internet.xml
  2. @@ -108,6 +108,16 @@
  3. settings:userRestriction="no_config_vpn"
  4. settings:useAdminDisabledSummary="true" />
  5. + <!--added by cgt Adding an Ethernet Interface start -->
  6. + <com.android.settingslib.RestrictedPreference
  7. + android:fragment="com.android.settings.ethernet.TestEthernetSettings"
  8. + android:icon="@drawable/ic_ethernet"
  9. + android:key="ethernet_settings"
  10. + android:title="@string/ethernet_settings_title"
  11. + settings:useAdminDisabledSummary="true"
  12. + settings:userRestriction="no_ethernet_settings" />
  13. + <!--aadded by cgt Adding an Ethernet Interface end -->
  14. +
  15. <com.android.settings.network.PrivateDnsModeDialogPreference
  16. android:key="private_dns_settings"
  17. android:title="@string/select_private_dns_configuration_title"

3.xml目录中添加imin_ethernet_settings.xml类用于显示以太网和mac地址项

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:settings="http://schemas.android.com/apk/res/com.android.settings"
  4. android:title="@string/imin_ethernet_settings" >
  5. <Preference
  6. android:key="imin_ethernet"
  7. android:persistent="true"
  8. android:summary="@string/imin_ethernet_not_connect"
  9. android:title="@string/imin_ethernet" />
  10. <Preference
  11. android:key="imin_ethernet_mac"
  12. android:summary="@string/imin_ethernet_not"
  13. android:title="@string/imin_ethernet_mac" />
  14. </PreferenceScreen>

4.layout目录中添加以太网设置界面的布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@drawable/imin_ethernet_bg"
  8. android:orientation="vertical">
  9. <TextView
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:textColor="#ff333333"
  13. android:layout_marginTop="8dp"
  14. android:textSize="18sp"
  15. android:text="@string/imin_ethernet_settings"
  16. android:layout_gravity="center_horizontal"/>
  17. <LinearLayout
  18. android:layout_marginTop="37dp"
  19. android:layout_width="match_parent"
  20. android:layout_height="wrap_content"
  21. android:orientation="horizontal">
  22. <TextView
  23. android:layout_width="0dp"
  24. android:layout_height="wrap_content"
  25. android:layout_weight="1"
  26. android:text="@string/imin_ethernet_way"
  27. android:gravity="right"
  28. android:textColor="#ff333333"
  29. />
  30. <RadioGroup
  31. android:id="@+id/imin_ip_set_rg"
  32. android:layout_marginLeft="15dp"
  33. android:layout_width="0dp"
  34. android:layout_height="wrap_content"
  35. android:layout_weight="3"
  36. android:orientation="horizontal">
  37. <RadioButton
  38. android:id="@+id/imin_ip_set_dhcp_rb"
  39. android:layout_width="27px"
  40. android:layout_height="27px"
  41. android:background="@drawable/imin_ethernet_checkbox_selector"
  42. android:button="@null"
  43. android:gravity="center" />
  44. <TextView
  45. android:layout_marginLeft="12dp"
  46. android:layout_marginRight="25dp"
  47. android:layout_width="wrap_content"
  48. android:layout_height="wrap_content"
  49. android:text="@string/imin_ethernet_dhcp"/>
  50. <RadioButton
  51. android:id="@+id/imin_ip_set_static_rb"
  52. android:layout_width="27px"
  53. android:layout_height="27px"
  54. android:layout_marginStart="10dp"
  55. android:background="@drawable/imin_ethernet_checkbox_selector"
  56. android:button="@null"
  57. android:gravity="center"/>
  58. <TextView
  59. android:layout_marginLeft="12dp"
  60. android:layout_width="wrap_content"
  61. android:layout_height="wrap_content"
  62. android:text="@string/imin_ethernet_static"/>
  63. </RadioGroup>
  64. </LinearLayout>
  65. <LinearLayout
  66. android:layout_marginTop="20dp"
  67. android:layout_width="match_parent"
  68. android:layout_height="wrap_content"
  69. android:orientation="horizontal">
  70. <TextView
  71. android:textColor="#ff333333"
  72. android:gravity="right"
  73. android:layout_width="0dp"
  74. android:layout_height="wrap_content"
  75. android:layout_weight="1"
  76. android:text="@string/imin_ethernet_address"
  77. />
  78. <RelativeLayout
  79. android:layout_marginLeft="15dp"
  80. android:layout_width="0dp"
  81. android:layout_weight="3"
  82. android:layout_height="26dp">
  83. <EditText
  84. android:id="@+id/imin_ip_et"
  85. android:layout_width="match_parent"
  86. android:layout_height="30dp"
  87. android:textSize="14sp"
  88. android:layout_marginRight="30dp"
  89. android:background="@drawable/imin_ethernet_input"
  90. android:paddingLeft="14dp"
  91. android:hint="192.168.1.148"/>
  92. </RelativeLayout>
  93. </LinearLayout>
  94. <LinearLayout
  95. android:layout_marginTop="20dp"
  96. android:layout_width="match_parent"
  97. android:layout_height="wrap_content"
  98. android:orientation="horizontal">
  99. <TextView
  100. android:textColor="#ff333333"
  101. android:gravity="right"
  102. android:layout_width="0dp"
  103. android:layout_height="wrap_content"
  104. android:layout_weight="1"
  105. android:text="@string/imin_ethernet_mask"
  106. />
  107. <RelativeLayout
  108. android:layout_marginLeft="15dp"
  109. android:layout_width="0dp"
  110. android:layout_weight="3"
  111. android:layout_height="26dp">
  112. <EditText
  113. android:id="@+id/imin_mask_et"
  114. android:layout_width="match_parent"
  115. android:layout_height="30dp"
  116. android:textSize="14sp"
  117. android:layout_marginRight="30dp"
  118. android:background="@drawable/imin_ethernet_input"
  119. android:paddingLeft="14dp"
  120. android:hint="255.255.255.0"/>
  121. </RelativeLayout>
  122. </LinearLayout>
  123. <LinearLayout
  124. android:layout_marginTop="20dp"
  125. android:layout_width="match_parent"
  126. android:layout_height="wrap_content"
  127. android:orientation="horizontal">
  128. <TextView
  129. android:textColor="#ff333333"
  130. android:gravity="right"
  131. android:layout_width="0dp"
  132. android:layout_height="wrap_content"
  133. android:layout_weight="1"
  134. android:text="@string/imin_ethernet_dns"
  135. />
  136. <RelativeLayout
  137. android:layout_marginLeft="15dp"
  138. android:layout_width="0dp"
  139. android:layout_weight="3"
  140. android:layout_height="26dp">
  141. <EditText
  142. android:id="@+id/imin_dns_et"
  143. android:layout_width="match_parent"
  144. android:layout_height="30dp"
  145. android:textSize="14sp"
  146. android:layout_marginRight="30dp"
  147. android:background="@drawable/imin_ethernet_input"
  148. android:paddingLeft="14dp"
  149. android:hint="192.168.1.1"/>
  150. </RelativeLayout>
  151. </LinearLayout>
  152. <LinearLayout
  153. android:layout_marginTop="20dp"
  154. android:layout_width="match_parent"
  155. android:layout_height="wrap_content"
  156. android:orientation="horizontal">
  157. <TextView
  158. android:textColor="#ff333333"
  159. android:gravity="right"
  160. android:layout_width="0dp"
  161. android:layout_height="wrap_content"
  162. android:layout_weight="1"
  163. android:text="@string/imin_ethernet_gateway"
  164. />
  165. <RelativeLayout
  166. android:layout_marginLeft="15dp"
  167. android:layout_width="0dp"
  168. android:layout_weight="3"
  169. android:layout_height="26dp">
  170. <EditText
  171. android:id="@+id/imin_gateway_et"
  172. android:layout_width="match_parent"
  173. android:layout_height="30dp"
  174. android:textSize="14sp"
  175. android:layout_marginRight="30dp"
  176. android:background="@drawable/imin_ethernet_input"
  177. android:paddingLeft="14dp"
  178. android:hint="192.168.1.1"/>
  179. </RelativeLayout>
  180. </LinearLayout>
  181. <LinearLayout
  182. android:layout_marginTop="27dp"
  183. android:layout_width="match_parent"
  184. android:layout_height="wrap_content"
  185. android:orientation="horizontal">
  186. <TextView
  187. android:textColor="#ff333333"
  188. android:gravity="right"
  189. android:layout_width="0dp"
  190. android:layout_height="wrap_content"
  191. android:layout_weight="1"
  192. android:text="@string/imin_ethernet_agency"
  193. />
  194. <RadioGroup
  195. android:id="@+id/imin_agency_rg"
  196. android:layout_marginLeft="15dp"
  197. android:layout_width="0dp"
  198. android:layout_weight="3"
  199. android:orientation="horizontal"
  200. android:layout_height="wrap_content">
  201. <RadioButton
  202. android:id="@+id/imin_agency_not_rb"
  203. android:layout_width="27px"
  204. android:layout_height="27px"
  205. android:background="@drawable/imin_ethernet_checkbox_selector"
  206. android:button="@null"
  207. android:gravity="center" />
  208. <TextView
  209. android:layout_marginLeft="12dp"
  210. android:layout_marginRight="25dp"
  211. android:layout_width="wrap_content"
  212. android:layout_height="wrap_content"
  213. android:text="@string/imin_ethernet_not"/>
  214. <RadioButton
  215. android:id="@+id/imin_agency_manual_rb"
  216. android:layout_width="27px"
  217. android:layout_height="27px"
  218. android:layout_marginStart="10dp"
  219. android:background="@drawable/imin_ethernet_checkbox_selector"
  220. android:button="@null"
  221. android:gravity="center"/>
  222. <TextView
  223. android:layout_marginLeft="12dp"
  224. android:layout_marginRight="25dp"
  225. android:layout_width="wrap_content"
  226. android:layout_height="wrap_content"
  227. android:text="@string/imin_ethernet_manual"/>
  228. <RadioButton
  229. android:id="@+id/imin_agency_auto_rb"
  230. android:layout_width="27px"
  231. android:layout_height="27px"
  232. android:layout_marginStart="10dp"
  233. android:background="@drawable/imin_ethernet_checkbox_selector"
  234. android:button="@null"
  235. android:gravity="center"/>
  236. <TextView
  237. android:layout_marginLeft="12dp"
  238. android:layout_width="wrap_content"
  239. android:layout_height="wrap_content"
  240. android:text="@string/imin_ethernet_auto"/>
  241. </RadioGroup>
  242. </LinearLayout>
  243. <LinearLayout
  244. android:id="@+id/imin_host_ll"
  245. android:visibility="gone"
  246. android:layout_marginTop="20dp"
  247. android:layout_width="match_parent"
  248. android:layout_height="wrap_content"
  249. android:orientation="horizontal">
  250. <TextView
  251. android:textColor="#ff333333"
  252. android:gravity="right"
  253. android:layout_width="0dp"
  254. android:layout_height="wrap_content"
  255. android:layout_weight="1"
  256. android:text="@string/imin_ethernet_host"
  257. />
  258. <RelativeLayout
  259. android:layout_marginLeft="15dp"
  260. android:layout_width="0dp"
  261. android:layout_weight="3"
  262. android:layout_height="26dp">
  263. <EditText
  264. android:id="@+id/imin_host_et"
  265. android:layout_width="match_parent"
  266. android:layout_height="30dp"
  267. android:textSize="14sp"
  268. android:layout_marginRight="30dp"
  269. android:background="@drawable/imin_ethernet_input"
  270. android:paddingLeft="14dp"
  271. android:hint="Proxy.example.com"/>
  272. </RelativeLayout>
  273. </LinearLayout>
  274. <LinearLayout
  275. android:id="@+id/imin_port_ll"
  276. android:visibility="gone"
  277. android:layout_marginTop="20dp"
  278. android:layout_width="match_parent"
  279. android:layout_height="wrap_content"
  280. android:orientation="horizontal">
  281. <TextView
  282. android:textColor="#ff333333"
  283. android:gravity="right"
  284. android:layout_width="0dp"
  285. android:layout_height="wrap_content"
  286. android:layout_weight="1"
  287. android:text="@string/imin_ethernet_port"
  288. />
  289. <RelativeLayout
  290. android:layout_marginLeft="15dp"
  291. android:layout_width="0dp"
  292. android:layout_weight="3"
  293. android:layout_height="26dp">
  294. <EditText
  295. android:id="@+id/imin_port_et"
  296. android:layout_width="match_parent"
  297. android:layout_height="30dp"
  298. android:textSize="14sp"
  299. android:layout_marginRight="30dp"
  300. android:digits="0123456789"
  301. android:background="@drawable/imin_ethernet_input"
  302. android:paddingLeft="14dp"
  303. android:hint="8080"/>
  304. </RelativeLayout>
  305. </LinearLayout>
  306. <LinearLayout
  307. android:id="@+id/imin_proxy_ll"
  308. android:visibility="gone"
  309. android:layout_marginTop="20dp"
  310. android:layout_width="match_parent"
  311. android:layout_height="wrap_content"
  312. android:orientation="horizontal">
  313. <TextView
  314. android:textColor="#ff333333"
  315. android:gravity="right"
  316. android:layout_width="0dp"
  317. android:layout_height="wrap_content"
  318. android:layout_weight="1"
  319. android:text="@string/imin_ethernet_proxy"
  320. />
  321. <RelativeLayout
  322. android:layout_marginLeft="15dp"
  323. android:layout_width="0dp"
  324. android:layout_weight="3"
  325. android:layout_height="26dp">
  326. <EditText
  327. android:id="@+id/imin_proxy_et"
  328. android:layout_width="match_parent"
  329. android:layout_height="30dp"
  330. android:textSize="14sp"
  331. android:layout_marginRight="30dp"
  332. android:background="@drawable/imin_ethernet_input"
  333. android:paddingLeft="14dp"
  334. android:hint="example.com,localhose"/>
  335. </RelativeLayout>
  336. </LinearLayout>
  337. <LinearLayout
  338. android:id="@+id/imin_pac_ll"
  339. android:visibility="gone"
  340. android:layout_marginTop="20dp"
  341. android:layout_width="match_parent"
  342. android:layout_height="wrap_content"
  343. android:orientation="horizontal">
  344. <TextView
  345. android:textColor="#ff333333"
  346. android:gravity="right"
  347. android:layout_width="0dp"
  348. android:layout_height="wrap_content"
  349. android:layout_weight="1"
  350. android:text="@string/imin_ethernet_pac"
  351. />
  352. <RelativeLayout
  353. android:layout_marginLeft="15dp"
  354. android:layout_width="0dp"
  355. android:layout_weight="3"
  356. android:layout_height="26dp">
  357. <EditText
  358. android:id="@+id/imin_pac_et"
  359. android:layout_width="match_parent"
  360. android:layout_height="30dp"
  361. android:textSize="14sp"
  362. android:layout_marginRight="30dp"
  363. android:background="@drawable/imin_ethernet_input"
  364. android:paddingLeft="14dp"
  365. />
  366. </RelativeLayout>
  367. </LinearLayout>
  368. <Button
  369. android:id="@+id/imin_confirm_bt"
  370. android:layout_marginTop="27dp"
  371. android:layout_width="72dp"
  372. android:layout_height="35dp"
  373. android:layout_gravity="center_horizontal"
  374. android:text="@string/imin_ethernet_confirm"
  375. android:textColor="@android:color/holo_red_dark"
  376. android:textSize="12sp"
  377. android:background="@drawable/imin_ethernet_button_selector"
  378. />
  379. </LinearLayout>
                3.2.2、源码实现类

1.SettingsGateway.java类中添加设置界面进入设置网络主页

  1. +++ b/xxx/Settings/src/com/android/settings/core/gateway/SettingsGateway.java
  2. @@ -190,6 +190,9 @@ import com.mediatek.settings.advancedcalling.AdvancedWifiCallingSettings;
  3. import com.mediatek.hdmi.HdmiSettings;
  4. /// M: Add for wfd settings fragment.
  5. import com.mediatek.settings.wfd.WfdSinkSurfaceFragment;
  6. +//added by cgt Adding an Ethernet Interface start
  7. +import com.android.settings.ethernet.IminEthernetSettings;
  8. +//added by cgt Adding an Ethernet Interface end
  9. public class SettingsGateway {
  10. @@ -214,6 +217,9 @@ public class SettingsGateway {
  11. WifiTetherSettings.class.getName(),
  12. BackgroundCheckSummary.class.getName(),
  13. VpnSettings.class.getName(),
  14. + //added by cgt Adding an Ethernet Interface start
  15. + TestEthernetSettings.class.getName(),
  16. + //added by cgt Adding an Ethernet Interface end
  17. DataSaverSummary.class.getName(),
  18. DateTimeSettings.class.getName(),
  19. LocaleListEditor.class.getName(),

2.添加TestEthernetSettings.java类实现设置代码

  1. /*
  2. * Copyright (C) 2009 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.android.settings.ethernet;
  17. import android.app.AlertDialog;
  18. import android.app.Dialog;
  19. import android.content.BroadcastReceiver;
  20. import android.content.Context;
  21. import android.content.DialogInterface;
  22. import android.content.Intent;
  23. import android.content.IntentFilter;
  24. import android.net.ConnectivityManager;
  25. import android.net.EthernetManager;
  26. import android.net.IpConfiguration;
  27. import android.net.IpConfiguration.IpAssignment;
  28. import android.net.IpConfiguration.ProxySettings;
  29. import android.net.LinkAddress;
  30. import android.net.NetworkInfo;
  31. import android.net.ProxyInfo;
  32. import android.net.StaticIpConfiguration;
  33. import android.net.Uri;
  34. import android.os.Bundle;
  35. import android.os.Handler;
  36. import android.os.Message;
  37. import android.os.SystemProperties;
  38. import android.preference.CheckBoxPreference;
  39. import android.provider.Settings;
  40. import android.text.TextUtils;
  41. import android.util.Log;
  42. import android.view.LayoutInflater;
  43. import android.view.View;
  44. import android.view.WindowManager;
  45. import android.widget.Button;
  46. import android.widget.EditText;
  47. import android.widget.LinearLayout;
  48. import android.widget.RadioButton;
  49. import android.widget.RadioGroup;
  50. import android.widget.Toast;
  51. import androidx.preference.ListPreference;
  52. import androidx.preference.Preference;
  53. import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
  54. import com.android.settings.R;
  55. import com.android.settings.SettingsPreferenceFragment;
  56. import java.io.BufferedReader;
  57. import java.io.File;
  58. import java.io.FileInputStream;
  59. import java.io.InputStreamReader;
  60. import java.net.Inet4Address;
  61. import java.net.InetAddress;
  62. import java.util.ArrayList;
  63. import java.util.List;
  64. import java.util.regex.Pattern;
  65. import java.io.FileReader;
  66. import java.io.IOException;
  67. import android.util.DisplayMetrics;
  68. import android.view.Window;
  69. /*for 5.0*/
  70. //import android.preference.ListPreference;
  71. //import com.android.internal.logging.MetricsProto.MetricsEvent;
  72. public class TestEthernetSettings extends SettingsPreferenceFragment
  73. implements Preference.OnPreferenceClickListener {
  74. private static final String TAG = "TestEthernetSettings";
  75. public enum ETHERNET_STATE {
  76. ETHER_STATE_DISCONNECTED,
  77. ETHER_STATE_CONNECTING,
  78. ETHER_STATE_CONNECTED
  79. }
  80. private static final String KEY_ETH_test = "test_ethernet";
  81. private static final String KEY_ETH_MAC = "test_ethernet_mac";
  82. private static String mEthHwAddress = null;
  83. private static String mEthIpAddress = null;
  84. private static String mEthNetmask = null;
  85. private static String mEthGateway = null;
  86. private static String mEthdns1 = null;
  87. private static String mEthdns2 = null;
  88. private final static String nullIpInfo = "0.0.0.0";
  89. private Preference mkeyEthMode;
  90. private final IntentFilter mIntentFilter;
  91. IpConfiguration mIpConfiguration;
  92. EthernetManager mEthManager;
  93. StaticIpConfiguration mStaticIpConfiguration;
  94. Context mContext;
  95. private String mIfaceName;
  96. private long mChangeTime;
  97. private static final int SHOW_RENAME_DIALOG = 0;
  98. private static final int ETHER_IFACE_STATE_DOWN = 0;
  99. private static final int ETHER_IFACE_STATE_UP = 1;
  100. private static final String FILE = "/sys/class/net/eth0/flags";
  101. private static final int MSG_GET_ETHERNET_STATE = 0;
  102. private EditText test_ip_et = null;
  103. private EditText test_mask_et = null;
  104. private EditText test_dns_et = null;
  105. private EditText test_gateway_et = null;
  106. private EditText test_host_et = null;
  107. private EditText test_port_et = null;
  108. private EditText test_proxy_et = null;
  109. private EditText test_pac_et = null;
  110. private RadioButton test_ip_set_dhcp_rb = null;
  111. private RadioButton test_ip_set_static_rb = null;
  112. private RadioButton test_agency_not_rb = null;
  113. private RadioButton test_agency_manual_rb = null;
  114. private RadioButton test_agency_auto_rb = null;
  115. private Dialog alertDialog = null;
  116. private LinearLayout test_host_ll = null;
  117. private LinearLayout test_port_ll = null;
  118. private LinearLayout test_proxy_ll = null;
  119. private LinearLayout test_pac_ll = null;
  120. private boolean isStaticMode = false;
  121. private boolean mCurrentModeIsStatic = false;
  122. private String mEthTempIpAddress = null;
  123. private String mEthTempNetmask = null;
  124. private String mEthTempGateway = null;
  125. private String mEthTempdns1 = null;
  126. private static String mEthTempdns2 = null;
  127. @Override
  128. public int getMetricsCategory() {
  129. return MetricsEvent.WIFI_TETHER_SETTINGS;
  130. }
  131. @Override
  132. public int getDialogMetricsCategory(int dialogId) {
  133. switch (dialogId) {
  134. case SHOW_RENAME_DIALOG:
  135. return MetricsEvent.WIFI_TETHER_SETTINGS;
  136. default:
  137. return 0;
  138. }
  139. }
  140. public TestEthernetSettings() {
  141. mIntentFilter = new IntentFilter();
  142. mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  143. }
  144. @Override
  145. public void onCreate(Bundle savedInstanceState) {
  146. super.onCreate(savedInstanceState);
  147. addPreferencesFromResource(R.xml.test_ethernet_settings);
  148. mContext = this.getActivity().getApplicationContext();
  149. mEthManager = (EthernetManager) getSystemService(Context.ETHERNET_SERVICE);
  150. if (mEthManager == null) {
  151. Log.e(TAG, "get ethernet manager failed");
  152. Toast.makeText(mContext, R.string.disabled_feature, Toast.LENGTH_SHORT).show();
  153. finish();
  154. return;
  155. }
  156. String[] ifaces = mEthManager.getAvailableInterfaces();
  157. for(int i = 0; i < ifaces.length; i++){
  158. Log.e(TAG, "TestEthernetSettings iface= " + ifaces[i]);
  159. }
  160. if (ifaces.length > 0) {
  161. mIfaceName = ifaces[0];//"eth0";
  162. }
  163. if (null == mIfaceName) {
  164. Log.e(TAG, "get ethernet ifaceName failed");
  165. Toast.makeText(mContext, R.string.disabled_feature, Toast.LENGTH_SHORT).show();
  166. finish();
  167. }
  168. }
  169. @Override
  170. public void onResume() {
  171. super.onResume();
  172. if (null == mIfaceName) {
  173. return;
  174. }
  175. if (mkeyEthMode == null) {
  176. mkeyEthMode = (Preference) findPreference(KEY_ETH_test);
  177. mkeyEthMode.setOnPreferenceClickListener(this);
  178. }
  179. setStringSummary(KEY_ETH_MAC, getEthernetMacAddress());
  180. log("resume");
  181. mContext.registerReceiver(mReceiver, mIntentFilter);
  182. }
  183. @Override
  184. public void onPause() {
  185. super.onPause();
  186. log("onPause");
  187. if (null == mIfaceName) {
  188. return;
  189. }
  190. //setIPSettingMode();
  191. //setProxyInfo();
  192. mContext.unregisterReceiver(mReceiver);
  193. if(alertDialog != null){
  194. alertDialog.dismiss();
  195. }
  196. }
  197. @Override
  198. public void onDestroy() {
  199. super.onDestroy();
  200. mHandler.removeMessages(MSG_GET_ETHERNET_STATE);
  201. log("destory");
  202. }
  203. @Override
  204. public void onStop() {
  205. super.onStop();
  206. log("stop");
  207. }
  208. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  209. @Override
  210. public void onReceive(Context context, Intent intent) {
  211. String action = intent.getAction();
  212. log("Action " + action);
  213. if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
  214. NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
  215. Log.v(TAG, "===" + info.toString());
  216. if (null != info && ConnectivityManager.TYPE_ETHERNET == info.getType()) {
  217. long currentTime = System.currentTimeMillis();
  218. int delayTime = 0;
  219. if (currentTime - mChangeTime < 1000) {
  220. delayTime = 2000;
  221. }
  222. if (NetworkInfo.State.CONNECTED == info.getState()) {
  223. handleEtherStateChange(ETHERNET_STATE.ETHER_STATE_CONNECTED, delayTime);
  224. } else if (NetworkInfo.State.DISCONNECTED == info.getState()) {
  225. handleEtherStateChange(ETHERNET_STATE.ETHER_STATE_DISCONNECTED, delayTime);
  226. }
  227. }
  228. }
  229. }
  230. };
  231. private Handler mHandler = new Handler() {
  232. @Override
  233. public void handleMessage(Message msg) {
  234. if (MSG_GET_ETHERNET_STATE == msg.what) {
  235. handleEtherStateChange((ETHERNET_STATE) msg.obj);
  236. }
  237. }
  238. };
  239. private void handleEtherStateChange(ETHERNET_STATE EtherState, long delayMillis) {
  240. mHandler.removeMessages(MSG_GET_ETHERNET_STATE);
  241. if (delayMillis > 0) {
  242. Message msg = new Message();
  243. msg.what = MSG_GET_ETHERNET_STATE;
  244. msg.obj = EtherState;
  245. mHandler.sendMessageDelayed(msg, delayMillis);
  246. } else {
  247. handleEtherStateChange(EtherState);
  248. }
  249. }
  250. private void handleEtherStateChange(ETHERNET_STATE EtherState) {
  251. log("curEtherState" + EtherState);
  252. switch (EtherState) {
  253. case ETHER_STATE_DISCONNECTED:
  254. mEthHwAddress = nullIpInfo;
  255. mEthIpAddress = nullIpInfo;
  256. mEthNetmask = nullIpInfo;
  257. mEthGateway = nullIpInfo;
  258. mEthdns1 = nullIpInfo;
  259. mEthdns2 = nullIpInfo;
  260. break;
  261. case ETHER_STATE_CONNECTING:
  262. //modify by luoyalong for Eth and WLAN control 20220530 begin
  263. String way = Settings.System.getString(mContext.getContentResolver() , "test_ip_way");
  264. IpAssignment mode = way != null&& way.equals("static") ? IpAssignment.STATIC : IpAssignment.DHCP;
  265. log("IES refreshtestUI way= " + way + " , mode= " + mode);
  266. log("handleEtherStateChange mode= " + mode);
  267. if (mode == IpAssignment.DHCP) {
  268. String mStatusString = this.getResources().getString(R.string.ethernet_info_getting);
  269. mEthHwAddress = mStatusString;
  270. mEthIpAddress = mStatusString;
  271. mEthNetmask = mStatusString;
  272. mEthGateway = mStatusString;
  273. mEthdns1 = mStatusString;
  274. mEthdns2 = mStatusString;
  275. }else{
  276. getEthInfo();
  277. }
  278. //modify by luoyalong for Eth and WLAN control 20220530 end
  279. break;
  280. case ETHER_STATE_CONNECTED:
  281. getEthInfo();
  282. break;
  283. }
  284. if(isAdded()){
  285. refreshtestUI();
  286. }
  287. }
  288. private void refreshtestUI(){
  289. ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
  290. NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
  291. if(mNetworkInfo != null && mNetworkInfo.isConnected() && !(mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)){
  292. String connected = this.getResources().getString(R.string.network_connected);
  293. setStringSummary(KEY_ETH_test, connected);
  294. }else{
  295. String notConnected = this.getResources().getString(R.string.test_ethernet_not_connect);
  296. setStringSummary(KEY_ETH_test, notConnected);
  297. }
  298. if(test_ip_et != null){
  299. String way = Settings.System.getString(mContext.getContentResolver() , "test_ip_way");
  300. IpAssignment mode = way != null&& way.equals("static") ? IpAssignment.STATIC : IpAssignment.DHCP;
  301. log("IES refreshtestUI way= " + way + " , mode= " + mode);
  302. if (mode == IpAssignment.STATIC) {
  303. isStaticMode = true;
  304. test_ip_set_static_rb.setChecked(true);
  305. test_ip_et.setEnabled(true);
  306. test_mask_et.setEnabled(true);
  307. test_dns_et.setEnabled(true);
  308. test_gateway_et.setEnabled(true);
  309. } else {
  310. isStaticMode = false;
  311. test_ip_set_dhcp_rb.setChecked(true);
  312. test_ip_et.setEnabled(false);
  313. test_mask_et.setEnabled(false);
  314. test_dns_et.setEnabled(false);
  315. test_gateway_et.setEnabled(false);
  316. }
  317. String host = Settings.System.getString(mContext.getContentResolver() , "test_proxy_host");
  318. String port = Settings.System.getString(mContext.getContentResolver() , "test_proxy_port");
  319. String exclList = Settings.System.getString(mContext.getContentResolver() , "test_proxy_exclList");
  320. String uri = Settings.System.getString(mContext.getContentResolver() , "test_proxy_uri");
  321. log("refreshtestUI host: = " + host
  322. + " , port: = " + port
  323. + " , exclList: = " + exclList
  324. + " , uri: = " + uri);
  325. String mHost = test_host_et.getText().toString();
  326. String mPort = test_port_et.getText().toString();
  327. String mExclList = test_proxy_et.getText().toString();
  328. String uriString = test_pac_et.getText().toString();
  329. if(!"".equals(mHost)){
  330. host = mHost;
  331. }
  332. if(!"".equals(mPort)){
  333. port = mPort;
  334. }
  335. if(!"".equals(mExclList)){
  336. exclList = mExclList;
  337. }
  338. if(!"".equals(uriString)){
  339. uri = uriString;
  340. }
  341. if(!"".equals(host)&& host != null){
  342. test_host_et.setText(host);
  343. }
  344. if(!"".equals(port)&& port != null){
  345. test_port_et.setText(port);
  346. }
  347. if(!"".equals(exclList)&& exclList != null){
  348. test_proxy_et.setText(exclList);
  349. }
  350. if(!"".equals(uri)&& uri != null){
  351. test_pac_et.setText(uri);
  352. }
  353. int agency = Settings.System.getInt(mContext.getContentResolver() , "test_agency_select" , 0);
  354. test_host_ll.setVisibility(View.GONE);
  355. test_port_ll.setVisibility(View.GONE);
  356. test_proxy_ll.setVisibility(View.GONE);
  357. test_pac_ll.setVisibility(View.GONE);
  358. if(agency == 1){
  359. test_pac_ll.setVisibility(View.VISIBLE);
  360. test_agency_auto_rb.setChecked(true);
  361. }else if(agency == 2){
  362. test_host_ll.setVisibility(View.VISIBLE);
  363. test_port_ll.setVisibility(View.VISIBLE);
  364. test_proxy_ll.setVisibility(View.VISIBLE);
  365. test_agency_manual_rb.setChecked(true);
  366. }else{
  367. test_agency_not_rb.setChecked(true);
  368. }
  369. test_ip_et.setText(mEthIpAddress);
  370. test_mask_et.setText(mEthNetmask);
  371. test_gateway_et.setText(mEthGateway);
  372. test_dns_et.setText(mEthdns1);
  373. }
  374. log("refreshtestUI 380 mEthIpAddress= " + mEthIpAddress
  375. + " , mEthGateway= " + mEthGateway
  376. + " , mEthdns1= " + mEthdns1
  377. + " , mEthNetmask= " + mEthNetmask);
  378. }
  379. private void settestEtherentDialog() {
  380. LayoutInflater layoutInflater = LayoutInflater.from(mContext);
  381. //modify by luoyalong for bug 5040 eth UI problem 20230308 begin
  382. View view =null;
  383. DisplayMetrics d2 = this.getResources().getDisplayMetrics();
  384. if(d2.density > 2.0){
  385. view =layoutInflater.inflate(R.layout.test_ethernet_dialog_2d, null);
  386. }else{
  387. view =layoutInflater.inflate(R.layout.test_ethernet_dialog, null);
  388. }
  389. //modify by luoyalong for bug 5040 eth UI problem 20230308 end
  390. RadioGroup test_ip_set_rg = view.findViewById(R.id.test_ip_set_rg);
  391. test_ip_set_dhcp_rb = view.findViewById(R.id.test_ip_set_dhcp_rb);
  392. test_ip_set_static_rb = view.findViewById(R.id.test_ip_set_static_rb);
  393. test_ip_et = view.findViewById(R.id.test_ip_et);
  394. test_mask_et = view.findViewById(R.id.test_mask_et);
  395. test_dns_et = view.findViewById(R.id.test_dns_et);
  396. test_gateway_et = view.findViewById(R.id.test_gateway_et);
  397. RadioGroup test_agency_rg = view.findViewById(R.id.test_agency_rg);
  398. test_agency_not_rb = view.findViewById(R.id.test_agency_not_rb);
  399. test_agency_manual_rb = view.findViewById(R.id.test_agency_manual_rb);
  400. test_agency_auto_rb = view.findViewById(R.id.test_agency_auto_rb);
  401. test_host_ll = view.findViewById(R.id.test_host_ll);
  402. test_host_et = view.findViewById(R.id.test_host_et);
  403. test_port_ll = view.findViewById(R.id.test_port_ll);
  404. test_port_et = view.findViewById(R.id.test_port_et);
  405. test_proxy_ll = view.findViewById(R.id.test_proxy_ll);
  406. test_proxy_et = view.findViewById(R.id.test_proxy_et);
  407. test_pac_ll = view.findViewById(R.id.test_pac_ll);
  408. test_pac_et = view.findViewById(R.id.test_pac_et);
  409. Button test_confirm_bt = view.findViewById(R.id.test_confirm_bt);
  410. mEthIpAddress = mEthNetmask = mEthGateway = mEthdns1 = "";
  411. getEthInfo();
  412. refreshtestUI();
  413. test_ip_set_rg.setOnCheckedChangeListener((group, checkedId) -> {
  414. //handleEtherStateChange(TestEthernetSettings.ETHERNET_STATE.ETHER_STATE_CONNECTING);
  415. if(checkedId == test_ip_set_dhcp_rb.getId()){
  416. mEthTempIpAddress = test_ip_et.getText().toString();
  417. mEthTempGateway = test_gateway_et.getText().toString();
  418. mEthTempdns1 = test_dns_et.getText().toString();
  419. mEthTempNetmask = test_mask_et.getText().toString();
  420. getEthInfo();
  421. log("setOnCheckedChangeListener dhcp mEthIpAddress= " + mEthIpAddress
  422. + " , mEthGateway= " + mEthGateway
  423. + " , mEthdns1= " + mEthdns1
  424. + " , mEthNetmask= " + mEthNetmask + " mEthTempIpAddress= " + mEthTempIpAddress
  425. + " , mEthTempGateway= " + mEthTempGateway
  426. + " , mEthTempdns1= " + mEthTempdns1
  427. + " , mEthTempNetmask= " + mEthTempNetmask);
  428. test_ip_et.setText(mEthIpAddress);
  429. test_mask_et.setText(mEthNetmask);
  430. test_gateway_et.setText(mEthGateway);
  431. test_dns_et.setText(mEthdns1);
  432. test_ip_et.setEnabled(false);
  433. test_mask_et.setEnabled(false);
  434. test_dns_et.setEnabled(false);
  435. test_gateway_et.setEnabled(false);
  436. mChangeTime = System.currentTimeMillis();
  437. }else{
  438. getEthInfo();
  439. log("setOnCheckedChangeListener static mEthIpAddress= " + mEthIpAddress
  440. + " , mEthGateway= " + mEthGateway
  441. + " , mEthdns1= " + mEthdns1
  442. + " , mEthNetmask= " + mEthNetmask + " mEthTempIpAddress= " + mEthTempIpAddress
  443. + " , mEthTempGateway= " + mEthTempGateway
  444. + " , mEthTempdns1= " + mEthTempdns1
  445. + " , mEthTempNetmask= " + mEthTempNetmask);
  446. if (mEthTempIpAddress != null) {
  447. mEthIpAddress = mEthTempIpAddress;
  448. }
  449. if (mEthTempGateway != null) {
  450. mEthGateway = mEthTempGateway;
  451. }
  452. if (mEthTempdns1 != null) {
  453. mEthdns1 = mEthTempdns1;
  454. }
  455. if (mEthTempNetmask != null) {
  456. mEthNetmask = mEthTempNetmask;
  457. }
  458. test_ip_et.setText(mEthIpAddress);
  459. test_mask_et.setText(mEthNetmask);
  460. test_gateway_et.setText(mEthGateway);
  461. test_dns_et.setText(mEthdns1);
  462. test_ip_et.setEnabled(true);
  463. test_mask_et.setEnabled(true);
  464. test_dns_et.setEnabled(true);
  465. test_gateway_et.setEnabled(true);
  466. }
  467. });
  468. test_agency_rg.setOnCheckedChangeListener((group, checkedId) -> {
  469. test_host_ll.setVisibility(View.GONE);
  470. test_port_ll.setVisibility(View.GONE);
  471. test_proxy_ll.setVisibility(View.GONE);
  472. test_pac_ll.setVisibility(View.GONE);
  473. Settings.System.putInt(mContext.getContentResolver() , "test_agency_select" , 0);
  474. if(checkedId == test_agency_auto_rb.getId()){
  475. test_pac_ll.setVisibility(View.VISIBLE);
  476. Settings.System.putInt(mContext.getContentResolver() , "test_agency_select" , 1);
  477. }else if(checkedId == test_agency_manual_rb.getId()){
  478. test_host_ll.setVisibility(View.VISIBLE);
  479. test_port_ll.setVisibility(View.VISIBLE);
  480. test_proxy_ll.setVisibility(View.VISIBLE);
  481. Settings.System.putInt(mContext.getContentResolver() , "test_agency_select" , 2);
  482. }
  483. });
  484. test_confirm_bt.setOnClickListener(v -> {
  485. log("cliked confirm button" );
  486. setEthernetSettings();
  487. alertDialog.dismiss();
  488. });
  489. alertDialog = new AlertDialog.Builder(mContext).setView(view).create();
  490. alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
  491. Window dialogWindow = alertDialog.getWindow();
  492. WindowManager.LayoutParams lp = dialogWindow.getAttributes();
  493. DisplayMetrics d = this.getResources().getDisplayMetrics();
  494. alertDialog.show();
  495. if(d.density > 1.6){
  496. if(d.scaledDensity > 2.0){
  497. alertDialog.getWindow().setLayout(840, 1320);
  498. }else{
  499. alertDialog.getWindow().setLayout(840, 1160);
  500. }
  501. }else{
  502. alertDialog.getWindow().setLayout(760, 800);
  503. }
  504. }
  505. private void setStringSummary(String preference, String value) {
  506. try {
  507. findPreference(preference).setSummary(value);
  508. } catch (RuntimeException e) {
  509. findPreference(preference).setSummary("");
  510. log("can't find " + preference);
  511. }
  512. }
  513. private void setProxyInfo(){
  514. IpAssignment ipAssignment = test_ip_set_static_rb.isChecked() ? IpAssignment.STATIC : IpAssignment.DHCP;
  515. log("setProxyInfo 431 ipAssignment= " + ipAssignment + " , isStaticMode : " + isStaticMode);
  516. if(test_agency_manual_rb.isChecked()){
  517. String host = test_host_et.getText().toString();
  518. String port = test_port_et.getText().toString();
  519. String exclList = test_proxy_et.getText().toString();
  520. log("setProxyInfo 440 host= " + host + " , port= " + port + " , exclList= " + exclList);
  521. if("".equals(host) || "".equals(port) || "".equals(exclList)){
  522. Toast.makeText(mContext , R.string.test_ethernet_manual_setup_failed , Toast.LENGTH_LONG).show();
  523. return;
  524. }
  525. Settings.System.putString(mContext.getContentResolver() , "test_proxy_host" , host);
  526. Settings.System.putString(mContext.getContentResolver() , "test_proxy_port" , port);
  527. Settings.System.putString(mContext.getContentResolver() , "test_proxy_exclList" , exclList);
  528. ProxyInfo proxyInfo = new ProxyInfo(host, Integer.parseInt(port), exclList);
  529. if(checkIPValue()){
  530. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(ipAssignment, ProxySettings.STATIC, isStaticMode ? mStaticIpConfiguration:null, proxyInfo));
  531. }
  532. }else if(test_agency_auto_rb.isChecked()){
  533. String uriString = test_pac_et.getText().toString();
  534. log("setProxyInfo 449 uriString= " + uriString);
  535. if("".equals(uriString)){
  536. Toast.makeText(mContext , R.string.test_ethernet_address_setup_failed , Toast.LENGTH_LONG).show();
  537. return;
  538. }
  539. Settings.System.putString(mContext.getContentResolver() , "test_proxy_uri" , uriString);
  540. Uri uri = Uri.parse(uriString);
  541. ProxyInfo proxyInfo = new ProxyInfo(uri);
  542. if(checkIPValue()){
  543. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(ipAssignment, ProxySettings.PAC, isStaticMode ? mStaticIpConfiguration:null, proxyInfo));
  544. }
  545. }else{
  546. log("setProxyInfo null = ");
  547. if(checkIPValue()){
  548. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(ipAssignment, ProxySettings.NONE, isStaticMode ? mStaticIpConfiguration:null, null));
  549. }
  550. }
  551. }
  552. private void setEthernetProxyInfo(){
  553. IpAssignment ipAssignment = mCurrentModeIsStatic ? IpAssignment.STATIC : IpAssignment.DHCP;
  554. log("setEthernetProxyInfo 431 ipAssignment= " + ipAssignment + " , mCurrentModeIsStatic : " + mCurrentModeIsStatic);
  555. if(test_agency_manual_rb.isChecked()){
  556. String host = test_host_et.getText().toString();
  557. String port = test_port_et.getText().toString();
  558. String exclList = test_proxy_et.getText().toString();
  559. log("setProxyInfo 440 host= " + host + " , port= " + port + " , exclList= " + exclList);
  560. if("".equals(host) || "".equals(port) || "".equals(exclList)){
  561. Toast.makeText(mContext , R.string.test_ethernet_manual_setup_failed , Toast.LENGTH_LONG).show();
  562. return;
  563. }
  564. Settings.System.putString(mContext.getContentResolver() , "test_proxy_host" , host);
  565. Settings.System.putString(mContext.getContentResolver() , "test_proxy_port" , port);
  566. Settings.System.putString(mContext.getContentResolver() , "test_proxy_exclList" , exclList);
  567. ProxyInfo proxyInfo = new ProxyInfo(host, Integer.parseInt(port), exclList);
  568. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(ipAssignment, ProxySettings.STATIC, mCurrentModeIsStatic ? mStaticIpConfiguration:null, proxyInfo));
  569. }else if(test_agency_auto_rb.isChecked()){
  570. String uriString = test_pac_et.getText().toString();
  571. log("setProxyInfo 449 uriString= " + uriString);
  572. if("".equals(uriString)){
  573. Toast.makeText(mContext , R.string.test_ethernet_address_setup_failed , Toast.LENGTH_LONG).show();
  574. return;
  575. }
  576. Settings.System.putString(mContext.getContentResolver() , "test_proxy_uri" , uriString);
  577. Uri uri = Uri.parse(uriString);
  578. ProxyInfo proxyInfo = new ProxyInfo(uri);
  579. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(ipAssignment, ProxySettings.PAC, mCurrentModeIsStatic ? mStaticIpConfiguration:null, proxyInfo));
  580. }else{
  581. log("setEthernetProxyInfo null = ");
  582. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(ipAssignment, ProxySettings.NONE, mCurrentModeIsStatic ? mStaticIpConfiguration:null, null));
  583. }
  584. }
  585. public boolean checkEthernetSettings() {
  586. boolean enable = false;
  587. mEthIpAddress = test_ip_et.getText().toString();
  588. mEthGateway = test_gateway_et.getText().toString();
  589. mEthdns1 = test_dns_et.getText().toString();
  590. mEthNetmask = test_mask_et.getText().toString();
  591. 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])$"); /*check subnet mask*/
  592. log(" ** checkEthernetSettings mEthIpAddress= " + mEthIpAddress
  593. + " , mEthGateway= " + mEthGateway
  594. + " , mEthdns1= " + mEthdns1
  595. + " , mEthNetmask= " + mEthNetmask
  596. + " , isValidIpAddress mEthIpAddress= " + isValidIpAddress(mEthIpAddress)
  597. + " , isValidIpAddress mEthGateway= " + isValidIpAddress(mEthGateway)
  598. + " , isValidIpAddress mEthdns1= " + isValidIpAddress(mEthdns1)
  599. + " , matches= " + pattern.matcher(mEthNetmask).matches());
  600. if (isValidIpAddress(mEthIpAddress) && isValidIpAddress(mEthGateway)
  601. && isValidIpAddress(mEthdns1) && (pattern.matcher(mEthNetmask).matches())) {
  602. enable = true;
  603. } else {
  604. enable = false;
  605. }
  606. if (mEthIpAddress != null && mEthGateway != null && mEthIpAddress.equals(mEthGateway)) {
  607. enable = false;
  608. }
  609. return enable;
  610. }
  611. private void setEthernetSettings() {
  612. log("setEthernetSettings = ");
  613. if(test_ip_set_static_rb.isChecked()){
  614. if(checkEthernetSettings()){
  615. if (setStaticIpConfiguration()) {
  616. mChangeTime = System.currentTimeMillis();
  617. Settings.System.putString(mContext.getContentResolver() , "test_ip_way" , "static");
  618. mCurrentModeIsStatic = true;
  619. mEthManager.setConfiguration(mIfaceName, mIpConfiguration);
  620. log("setEthernetSettings static is checked , setConfiguration static ");
  621. handleEtherStateChange(TestEthernetSettings.ETHERNET_STATE.ETHER_STATE_CONNECTING);
  622. setEthernetProxyInfo();
  623. } else {
  624. Toast.makeText(mContext , R.string.test_ethernet_static_ip_setup_failed , Toast.LENGTH_LONG).show();
  625. }
  626. } else{
  627. Toast.makeText(mContext , R.string.test_ethernet_parameter_exception , Toast.LENGTH_LONG).show();
  628. }
  629. }else if(test_ip_set_dhcp_rb.isChecked()){
  630. log("setEthernetSettings dhcp is checked , setConfiguration DHCP ");
  631. Settings.System.putString(mContext.getContentResolver() , "test_ip_way" , "dhcp");
  632. mCurrentModeIsStatic = false;
  633. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(IpAssignment.DHCP, ProxySettings.NONE, null, null));
  634. setEthernetProxyInfo();
  635. }
  636. }
  637. private void setIPSettingMode(){
  638. log("setIPSettingMode = ");
  639. if(test_ip_set_static_rb.isChecked()){
  640. if(checkIPValue()){
  641. if (setStaticIpConfiguration()) {
  642. mChangeTime = System.currentTimeMillis();
  643. mEthManager.setConfiguration(mIfaceName, mIpConfiguration);
  644. handleEtherStateChange(TestEthernetSettings.ETHERNET_STATE.ETHER_STATE_CONNECTING);
  645. } else {
  646. Toast.makeText(mContext , R.string.test_ethernet_static_ip_setup_failed , Toast.LENGTH_LONG).show();
  647. }
  648. }else{
  649. log("setIPSettingMode setConfiguration DHCP= ");
  650. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(IpAssignment.DHCP, ProxySettings.NONE, null, null));
  651. }
  652. }else if(test_ip_set_dhcp_rb.isChecked()){
  653. log("setIPSettingMode dhcp is checked , setConfiguration DHCP ");
  654. mEthManager.setConfiguration(mIfaceName, new IpConfiguration(IpAssignment.DHCP, ProxySettings.NONE, null, null));
  655. }
  656. }
  657. private String getEthernetMacAddress() {
  658. BufferedReader reader = null;
  659. String ethernetMac =null;
  660. try {
  661. reader = new BufferedReader(new FileReader("sys/class/net/eth0/address"));
  662. ethernetMac = reader.readLine();
  663. Log.v("hg", "ethernetMac: " + ethernetMac.toString());
  664. } catch (Exception e) {
  665. Log.e("hg", "open sys/class/net/eth0/address failed : " + e);
  666. } finally {
  667. try {
  668. if (reader != null)
  669. reader.close();
  670. } catch (IOException e) {
  671. Log.e("hg", "close sys/class/net/eth0/address failed : " + e);
  672. }
  673. }
  674. return ethernetMac.toString();
  675. }
  676. public boolean checkIPValue() {
  677. boolean enable = false;
  678. mEthIpAddress = test_ip_et.getText().toString();
  679. mEthGateway = test_gateway_et.getText().toString();
  680. mEthdns1 = test_dns_et.getText().toString();
  681. mEthNetmask = test_mask_et.getText().toString();
  682. 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])$"); /*check subnet mask*/
  683. log(" ** checkIPValue mEthIpAddress= " + mEthIpAddress
  684. + " , mEthGateway= " + mEthGateway
  685. + " , mEthdns1= " + mEthdns1
  686. + " , mEthNetmask= " + mEthNetmask
  687. + " , isValidIpAddress mEthIpAddress= " + isValidIpAddress(mEthIpAddress)
  688. + " , isValidIpAddress mEthGateway= " + isValidIpAddress(mEthGateway)
  689. + " , isValidIpAddress mEthdns1= " + isValidIpAddress(mEthdns1)
  690. + " , matches= " + pattern.matcher(mEthNetmask).matches());
  691. if (isValidIpAddress(mEthIpAddress) && isValidIpAddress(mEthGateway)
  692. && isValidIpAddress(mEthdns1) && (pattern.matcher(mEthNetmask).matches())) {
  693. enable = true;
  694. } else {
  695. Toast.makeText(mContext , R.string.test_ethernet_parameter_exception , Toast.LENGTH_LONG).show();
  696. enable = false;
  697. }
  698. return enable;
  699. }
  700. private Inet4Address getIPv4Address(String text) {
  701. try {
  702. return (Inet4Address) EthernetManager.testNumericToInetAddress(text);
  703. } catch (IllegalArgumentException | ClassCastException e) {
  704. return null;
  705. }
  706. }
  707. /*
  708. * 返回 指定的 String 是否是 有效的 IP 地址.
  709. */
  710. private boolean isValidIpAddress(String value) {
  711. int start = 0;
  712. int end = value.indexOf('.');
  713. int numBlocks = 0;
  714. if(nullIpInfo.equals(value)){
  715. return false;
  716. }
  717. while (start < value.length()) {
  718. if (-1 == end) {
  719. end = value.length();
  720. }
  721. try {
  722. int block = Integer.parseInt(value.substring(start, end));
  723. if ((block > 255) || (block < 0)) {
  724. Log.w("EthernetIP",
  725. "isValidIpAddress() : invalid 'block', block = "
  726. + block);
  727. return false;
  728. }
  729. } catch (NumberFormatException e) {
  730. Log.w("EthernetIP", "isValidIpAddress() : e = " + e);
  731. return false;
  732. }
  733. numBlocks++;
  734. start = end + 1;
  735. end = value.indexOf('.', start);
  736. }
  737. return numBlocks == 4;
  738. }
  739. @Override
  740. public boolean onPreferenceClick(Preference preference) {
  741. log("onPreferenceClick");
  742. if (preference == mkeyEthMode) {
  743. settestEtherentDialog();
  744. }
  745. return true;
  746. }
  747. //将子网掩码转换成ip子网掩码形式,比如输入32输出为255.255.255.255
  748. public String interMask2String(int prefixLength) {
  749. String netMask = null;
  750. int inetMask = prefixLength;
  751. int part = inetMask / 8;
  752. int remainder = inetMask % 8;
  753. int sum = 0;
  754. for (int i = 8; i > 8 - remainder; i--) {
  755. sum = sum + (int) Math.pow(2, i - 1);
  756. }
  757. if (part == 0) {
  758. netMask = sum + ".0.0.0";
  759. } else if (part == 1) {
  760. netMask = "255." + sum + ".0.0";
  761. } else if (part == 2) {
  762. netMask = "255.255." + sum + ".0";
  763. } else if (part == 3) {
  764. netMask = "255.255.255." + sum;
  765. } else if (part == 4) {
  766. netMask = "255.255.255.255";
  767. }
  768. return netMask;
  769. }
  770. /*
  771. * convert subMask string to prefix length
  772. */
  773. private int maskStr2InetMask(String maskStr) {
  774. StringBuffer sb;
  775. String str;
  776. int inetmask = 0;
  777. int count = 0;
  778. /*
  779. * check the subMask format
  780. */
  781. 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])$");
  782. log("595 maskStr2InetMask pattern= " + pattern
  783. + " , maskStr= " + maskStr);
  784. if (pattern.matcher(maskStr).matches() == false) {
  785. Log.e(TAG, "subMask is error");
  786. return 0;
  787. }
  788. String[] ipSegment = maskStr.split("\\.");
  789. for (int n = 0; n < ipSegment.length; n++) {
  790. sb = new StringBuffer(Integer.toBinaryString(Integer.parseInt(ipSegment[n])));
  791. str = sb.reverse().toString();
  792. count = 0;
  793. for (int i = 0; i < str.length(); i++) {
  794. i = str.indexOf("1", i);
  795. if (i == -1)
  796. break;
  797. count++;
  798. }
  799. inetmask += count;
  800. }
  801. return inetmask;
  802. }
  803. private void saveIpSettingInfo(){
  804. Settings.System.putString(mContext.getContentResolver() , "test_static_ipaddress" , this.mEthIpAddress);
  805. Settings.System.putString(mContext.getContentResolver() , "test_static_mask" , this.mEthNetmask);
  806. Settings.System.putString(mContext.getContentResolver() , "test_static_gateway" , this.mEthGateway);
  807. Settings.System.putString(mContext.getContentResolver() , "test_static_dns1" , this.mEthdns1);
  808. }
  809. private boolean setStaticIpConfiguration() {
  810. //mStaticIpConfiguration = new StaticIpConfiguration();
  811. /*
  812. * get ip address, netmask,dns ,gw etc.
  813. */
  814. Inet4Address inetAddr = getIPv4Address(this.mEthIpAddress);
  815. int prefixLength = maskStr2InetMask(this.mEthNetmask);
  816. InetAddress gatewayAddr = getIPv4Address(this.mEthGateway);
  817. InetAddress dnsAddr = getIPv4Address(this.mEthdns1);
  818. if (inetAddr.getAddress().toString().isEmpty() || prefixLength == 0 || gatewayAddr.toString().isEmpty()
  819. || dnsAddr.toString().isEmpty()) {
  820. log("ip,mask or dnsAddr is wrong");
  821. return false;
  822. }
  823. saveIpSettingInfo();
  824. /*mStaticIpConfiguration.setIpAddress(new LinkAddress(inetAddr, prefixLength));
  825. mStaticIpConfiguration.setGateway(gatewayAddr);
  826. mStaticIpConfiguration.addDnsServers(dnsAddr);*/
  827. List<InetAddress> dnsAddrs = new ArrayList<InetAddress>();
  828. dnsAddrs.add(dnsAddr);
  829. if(mEthdns2 != null){
  830. dnsAddrs.add(getIPv4Address(mEthdns2));
  831. }
  832. mStaticIpConfiguration = new StaticIpConfiguration.Builder()
  833. .setIpAddress(new LinkAddress(inetAddr, prefixLength))
  834. .setGateway(gatewayAddr)
  835. .setDnsServers(dnsAddrs)
  836. .build();
  837. mIpConfiguration = new IpConfiguration();
  838. mIpConfiguration.setIpAssignment(IpAssignment.STATIC);
  839. mIpConfiguration.setProxySettings(ProxySettings.NONE);
  840. mIpConfiguration.setStaticIpConfiguration(mStaticIpConfiguration);
  841. log("Complete static ip Settings ....");
  842. return true;
  843. }
  844. public void getEthInfoFromDhcp() {
  845. String tempIpInfo;
  846. tempIpInfo = /*SystemProperties.get("dhcp."+ iface +".ipaddress");*/
  847. mEthManager.getIpAddress(mIfaceName);
  848. if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
  849. mEthIpAddress = tempIpInfo;
  850. } else {
  851. mEthIpAddress = nullIpInfo;
  852. }
  853. tempIpInfo = /*SystemProperties.get("dhcp."+ iface +".mask");*/
  854. mEthManager.getNetmask(mIfaceName);
  855. if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
  856. mEthNetmask = tempIpInfo;
  857. } else {
  858. mEthNetmask = nullIpInfo;
  859. }
  860. tempIpInfo = /*SystemProperties.get("dhcp."+ iface +".gateway");*/
  861. mEthManager.getGateway(mIfaceName);
  862. if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
  863. mEthGateway = tempIpInfo;
  864. } else {
  865. mEthGateway = nullIpInfo;
  866. }
  867. tempIpInfo = /*SystemProperties.get("dhcp."+ iface +".dns1");*/
  868. mEthManager.getDns(mIfaceName);
  869. if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
  870. String data[] = tempIpInfo.split(",");
  871. mEthdns1 = data[0];
  872. if (data.length <= 1) {
  873. mEthdns2 = nullIpInfo;
  874. } else {
  875. mEthdns2 = data[1];
  876. }
  877. } else {
  878. mEthdns1 = nullIpInfo;
  879. }
  880. log("getEthInfoFromDhcp mEthIpAddress= " + mEthIpAddress);
  881. log("getEthInfoFromDhcp mEthNetmask= " + mEthNetmask);
  882. log("getEthInfoFromDhcp mEthGateway= " + mEthGateway);
  883. log("getEthInfoFromDhcp mEthdns1= " + mEthdns1);
  884. log("getEthInfoFromDhcp mEthdns2= " + mEthdns2);
  885. }
  886. public void getEthInfoFromStaticIp() {
  887. StaticIpConfiguration staticIpConfiguration = mEthManager.getConfiguration(mIfaceName).getStaticIpConfiguration();
  888. if (staticIpConfiguration == null) {
  889. return;
  890. }
  891. LinkAddress ipAddress = staticIpConfiguration.getIpAddress();
  892. InetAddress gateway = staticIpConfiguration.getGateway();
  893. List<InetAddress> dnsServers = staticIpConfiguration.getDnsServers();
  894. if (ipAddress != null) {
  895. mEthIpAddress = ipAddress.getAddress().getHostAddress();
  896. mEthNetmask = interMask2String(ipAddress.getPrefixLength());
  897. }
  898. if (gateway != null) {
  899. mEthGateway = gateway.getHostAddress();
  900. }
  901. mEthdns1 = dnsServers.get(0).getHostAddress();
  902. if (dnsServers.size() > 1) { /* 只保留两个*/
  903. mEthdns2 = dnsServers.get(1).getHostAddress();
  904. }
  905. log("getEthInfoFromStaticIp mEthIpAddress= " + mEthIpAddress);
  906. log("getEthInfoFromStaticIp mEthNetmask= " + mEthNetmask);
  907. log("getEthInfoFromStaticIp mEthGateway= " + mEthGateway);
  908. log("getEthInfoFromStaticIp mEthdns2= " + mEthdns2);
  909. }
  910. /*
  911. * TODO:
  912. */
  913. public void getEthInfo() {
  914. /*
  915. mEthHwAddress = mEthManager.getEthernetHwaddr(mEthManager.getEthernetIfaceName());
  916. if (mEthHwAddress == null) mEthHwAddress = nullIpInfo;
  917. */
  918. String way = Settings.System.getString(mContext.getContentResolver() , "test_ip_way");
  919. IpAssignment mode = way != null&& way.equals("static") ? IpAssignment.STATIC : IpAssignment.DHCP;
  920. log("IES refreshtestUI way= " + way + " , mode= " + mode);
  921. IpConfiguration ipConfiguration = mEthManager.getConfiguration(mIfaceName);
  922. if (ipConfiguration != null) {
  923. IpAssignment ipAssignment = ipConfiguration.getIpAssignment();
  924. if (mode != ipAssignment) {
  925. mode = ipAssignment;
  926. String ipWay = mode == IpAssignment.STATIC ? "static" : "dhcp";
  927. Settings.System.putString(mContext.getContentResolver() , "test_ip_way" , ipWay);
  928. log("IES refreshtestUI change ipWay= " + ipWay + " , mode= " + mode);
  929. }
  930. }
  931. log("getEthInfo mode= " + mode);
  932. if (mode == IpAssignment.DHCP || mode == IpAssignment.UNASSIGNED) {
  933. /*
  934. * getEth from dhcp
  935. */
  936. getEthInfoFromDhcp();
  937. } else if (mode == IpAssignment.STATIC) {
  938. /*
  939. * TODO: get static IP
  940. */
  941. getEthInfoFromStaticIp();
  942. }
  943. }
  944. /*
  945. * tools
  946. */
  947. private void log(String s) {
  948. Log.d(TAG, s);
  949. }
  950. public static boolean isAvailable() {
  951. return "true".equals(SystemProperties.get("ro.vendor.ethernet_settings"));
  952. }
  953. }

四、总结

        至此关于android13以太网的功能介绍完毕,实际上博主认为技术分享应该是无私的,而并非作为牟利的工具,看到很多技术收费的文章,这其实对于自我的成长进步有很大的限制,微薄的利益回报并不值得,博主后续会继续更新对开发有益的文章,愿人人成为大神。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/527992
推荐阅读
相关标签
  

闽ICP备14008679号