【android 12】【网络】wifi与以太网共存操作

一、概述

1. android系统原生代码只支持单网存在,即接入eth后,wifi无法使用,也不可以网络切换。下面的代码修改,可以使wifi与以太网共存,并根据场景实现不同的功能

二、代码修改

1. wifi与以太网共存,且wifi优先

Date:   Tue Dec 31 16:19:54 2024 +0800

    other : Supports coexistence of Ethernet and WiFi networks

diff --git a/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java b/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java
old mode 100644
new mode 100755
index 282c4207215..e0d53682211
--- a/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java
+++ b/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java
@@ -70,7 +70,7 @@ public class EthernetNetworkFactory extends NetworkFactory {
     private final static String TAG = EthernetNetworkFactory.class.getSimpleName();
     final static boolean DBG = true;
 
-    private final static int NETWORK_SCORE = 70;
+    private final static int NETWORK_SCORE = 60;
     private static final String NETWORK_TYPE = "Ethernet";
 
     private final ConcurrentHashMap<String, NetworkInterfaceState> mTrackingInterfaces =
@@ -428,13 +428,13 @@ public class EthernetNetworkFactory extends NetworkFactory {
                     new TransportInfo(ConnectivityManager.TYPE_NONE, 1));
             // EthernetNetworkFactory.NETWORK_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_ETHERNET,
-                    new TransportInfo(ConnectivityManager.TYPE_ETHERNET, 70));
+                    new TransportInfo(ConnectivityManager.TYPE_ETHERNET, 60));
             // BluetoothTetheringNetworkFactory.NETWORK_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_BLUETOOTH,
                     new TransportInfo(ConnectivityManager.TYPE_BLUETOOTH, 69));
             // WifiNetworkFactory.SCORE_FILTER / NetworkAgent.WIFI_BASE_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_WIFI,
-                    new TransportInfo(ConnectivityManager.TYPE_WIFI, 60));
+                    new TransportInfo(ConnectivityManager.TYPE_WIFI, 70));
             // TelephonyNetworkFactory.TELEPHONY_NETWORK_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_CELLULAR,
                     new TransportInfo(ConnectivityManager.TYPE_MOBILE, 50));
diff --git a/packages/modules/Connectivity/service/src/com/android/server/ConnectivityService.java b/packages/modules/Connectivity/service/src/com/android/server/ConnectivityService.java
old mode 100644
new mode 100755
index 418e9e33b8d..1e335f018e1
--- a/packages/modules/Connectivity/service/src/com/android/server/ConnectivityService.java
+++ b/packages/modules/Connectivity/service/src/com/android/server/ConnectivityService.java
@@ -291,11 +291,11 @@ public class ConnectivityService extends IConnectivityManager.Stub
     private static final String REQUEST_ARG = "requests";
 
     private static final boolean DBG = true;
-    private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
-    private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
+    private static final boolean DDBG = true;//Log.isLoggable(TAG, Log.DEBUG);
+    private static final boolean VDBG = true;//Log.isLoggable(TAG, Log.VERBOSE);
 
     private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
-
+       private static final boolean ENABLE_NETWORK_COEXIST = true;
     /**
      * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
      * by OEMs for configuration purposes, as this value is overridden by
@@ -1587,7 +1587,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
         handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
                 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
         handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
-                ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
+                ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, true /* defaultValue */);
         final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
                 R.bool.config_vehicleInternalNetworkAlwaysRequested);
         handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
@@ -3797,7 +3797,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
         // 2. If the network was inactive and there are now requests, unset inactive.
         // 3. If this network is unneeded (which implies it is not lingering), and there is at least
         //    one lingered request, set inactive.
-        nai.updateInactivityTimer();
+        /*nai.updateInactivityTimer();
         if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
             if (DBG) log("Unsetting inactive " + nai.toShortString());
             nai.unsetInactive();
@@ -3810,7 +3810,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
             nai.setInactive();
             logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
             return true;
-        }
+        }*/
         return false;
     }
 
@@ -7789,7 +7789,12 @@ public class ConnectivityService extends IConnectivityManager.Stub
                 break;
             }
         }
-        nai.disconnect();
+        //nai.disconnect();
+       if(ENABLE_NETWORK_COEXIST) {
+               log("hcq Skip teardownUnneededNetwork: " + nai.network());
+       }else{
+               nai.disconnect();
+       }               
     }
 
     private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
diff --git a/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java b/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java
old mode 100644
new mode 100755
index d7eb9c8a59b..da7e660d0b3
--- a/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java
+++ b/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java
@@ -85,7 +85,7 @@ public class NetworkRanker {
     }
 
     // Transport preference order, if it comes down to that.
-    private static final int[] PREFERRED_TRANSPORTS_ORDER = { TRANSPORT_ETHERNET, TRANSPORT_WIFI,
+    private static final int[] PREFERRED_TRANSPORTS_ORDER = { TRANSPORT_WIFI,TRANSPORT_ETHERNET, 
             TRANSPORT_BLUETOOTH, TRANSPORT_CELLULAR };
 
     // Function used to partition a list into two working areas depending on whether they
diff --git a/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java b/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
index 8950938fe59..23067ca5dba 100755
--- a/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
@@ -589,8 +589,8 @@ public class NetworkMonitor extends StateMachine {
         setInitialState(mDefaultState);
         // CHECKSTYLE:ON IndentationCheck
 
-        mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled();
-        mPrivateIpNoInternetEnabled = getIsPrivateIpNoInternetEnabled();
+        mIsCaptivePortalCheckEnabled = false;//getIsCaptivePortalCheckEnabled();
+        mPrivateIpNoInternetEnabled = false;//getIsPrivateIpNoInternetEnabled();
         mMetricsEnabled = deps.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
                 NetworkStackUtils.VALIDATION_METRICS_VERSION, true /* defaultEnabled */);
         mUseHttps = getUseHttpsValidation();
diff --git a/packages/modules/Wifi/service/java/com/android/server/wifi/WifiNetworkFactory.java b/packages/modules/Wifi/service/java/com/android/server/wifi/WifiNetworkFactory.java
old mode 100644
new mode 100755
index f6e46a9ad6b..18608ec922a
--- a/packages/modules/Wifi/service/java/com/android/server/wifi/WifiNetworkFactory.java
+++ b/packages/modules/Wifi/service/java/com/android/server/wifi/WifiNetworkFactory.java
@@ -92,7 +92,7 @@ import java.util.stream.Collectors;
 public class WifiNetworkFactory extends NetworkFactory {
     private static final String TAG = "WifiNetworkFactory";
     @VisibleForTesting
-    private static final int SCORE_FILTER = 60;
+    private static final int SCORE_FILTER = 70;
     @VisibleForTesting
     public static final int CACHED_SCAN_RESULTS_MAX_AGE_IN_MILLIS = 30 * 1000;
     @VisibleForTesting
diff --git a/system/netd/server/RouteController.cpp b/system/netd/server/RouteController.cpp
old mode 100644
new mode 100755
index ba305e69a0d..c78a52a0fb6
--- a/system/netd/server/RouteController.cpp
+++ b/system/netd/server/RouteController.cpp
@@ -721,6 +721,17 @@ int RouteController::configureDummyNetwork() {
     return 0;
 }
 
+// Add a new rule to look up the 'main' table, with the same selectors as the "default network"
+// rule, but with a lower priority. We will never create routes in the main table; it should only be
+// used for directly-connected routes implicitly created by the kernel when adding IP addresses.
+// This is necessary, for example, when adding a route through a directly-connected gateway: in
+// order to add the route, there must already be a directly-connected route that covers the gateway.
+[[nodiscard]] static int addDirectlyConnectedRule() {
+
+    return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_DIRECTLY_CONNECTED, RT_TABLE_MAIN,
+                        0, 0, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
+}
+
 // Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
 // relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
 // behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
@@ -1160,7 +1171,10 @@ int RouteController::Init(unsigned localNetId) {
     if (int ret = addUnreachableRule()) {
         return ret;
     }
-    // Don't complain if we can't add the dummy network, since not all devices support it.
+    if (int ret = addDirectlyConnectedRule()) {
+       return ret;
+    }  
+       // Don't complain if we can't add the dummy network, since not all devices support it.
     configureDummyNetwork();
 
     updateTableNamesFile();
diff --git a/system/netd/server/RouteController.h b/system/netd/server/RouteController.h
old mode 100644
new mode 100755
index 38d2d6210a8..43ee1482323
--- a/system/netd/server/RouteController.h
+++ b/system/netd/server/RouteController.h
@@ -30,6 +30,7 @@
 namespace android::net {
 
 // clang-format off
+const uint32_t RULE_PRIORITY_DIRECTLY_CONNECTED  = 9999;
 const uint32_t RULE_PRIORITY_VPN_OVERRIDE_SYSTEM     = 10000;
 const uint32_t RULE_PRIORITY_VPN_OVERRIDE_OIF        = 11000;
 const uint32_t RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL     = 12000;

2. 在1的基础上,解决wifi与以太网共存时,app无法获取以太网ip地址的问题,且设置以太网优先

Date:   Tue Jan 14 16:58:57 2025 +0800

    other : 1. Dealing with the issue where the setting application cannot obtain the Ethernet IP address when both WiFi and Ethernet are connected simultaneously. 2. When WiFi and Ethernet are connected simultaneously, Ethernet takes priority

diff --git a/frameworks/base/core/api/system-current.txt b/frameworks/base/core/api/system-current.txt
index b2b81a7eb47..5a28ea9032c 100644
--- a/frameworks/base/core/api/system-current.txt
+++ b/frameworks/base/core/api/system-current.txt
@@ -7390,6 +7390,24 @@ package android.net {
 
   public class EthernetManager {
     method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_STACK, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public android.net.EthernetManager.TetheredInterfaceRequest requestTetheredInterface(@NonNull java.util.concurrent.Executor, @NonNull android.net.EthernetManager.TetheredInterfaceCallback);
+    field public static final String ACTION_ETHERNET_STATE_CHANGED = "android.net.action.ETHERNET_STATE_CHANGED";
+    field @Deprecated public static final int ETHERNET_STATE_DISABLED = 0; // 0x0
+    field public static final int ETHERNET_STATE_ENABLED = 1; // 0x1
+    field public static final int ETHERNET_STATE_UNKNOWN = 2; // 0x2
+    field public static final int EVENT_DHCP_CONNECT_FAILED = 11; // 0xb
+    field public static final int EVENT_DHCP_CONNECT_SUCCESSED = 10; // 0xa
+    field public static final int EVENT_DHCP_DISCONNECT_FAILED = 13; // 0xd
+    field public static final int EVENT_DHCP_DISCONNECT_SUCCESSED = 12; // 0xc
+    field public static final int EVENT_PHY_LINK_DOWN = 19; // 0x13
+    field public static final int EVENT_PHY_LINK_UP = 18; // 0x12
+    field public static final int EVENT_STATIC_CONNECT_FAILED = 15; // 0xf
+    field public static final int EVENT_STATIC_CONNECT_SUCCESSED = 14; // 0xe
+    field public static final int EVENT_STATIC_DISCONNECT_FAILED = 17; // 0x11
+    field public static final int EVENT_STATIC_DISCONNECT_SUCCESSED = 16; // 0x10
+    field @Deprecated public static final String EXTRA_ETHERNET_FAILED_REASON = "ethernet_failed_reason";
+    field @Deprecated public static final String EXTRA_ETHERNET_STATE = "ethernet_state";
+    field @Deprecated public static final String EXTRA_NETWORK_INFO = "networkInfo";
+    field public static final int FAILED_REASON_INVALID_PARAMETER = 0; // 0x0
   }
 
   public static interface EthernetManager.TetheredInterfaceCallback {
diff --git a/frameworks/base/core/java/android/net/EthernetManager.java b/frameworks/base/core/java/android/net/EthernetManager.java
old mode 100644
new mode 100755
index cbb21e708b1..e4cc93b9f71
--- a/frameworks/base/core/java/android/net/EthernetManager.java
+++ b/frameworks/base/core/java/android/net/EthernetManager.java
@@ -42,6 +42,49 @@ import java.util.concurrent.Executor;
 @SystemService(Context.ETHERNET_SERVICE)
 public class EthernetManager {
     private static final String TAG = "EthernetManager";
+    // 广播名称
+    //@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String ACTION_ETHERNET_STATE_CHANGED = "android.net.action.ETHERNET_STATE_CHANGED";
+
+    // 广播参数字段
+    @Deprecated
+    public static final String EXTRA_NETWORK_INFO = "networkInfo";
+    @Deprecated
+    public static final String EXTRA_ETHERNET_STATE = "ethernet_state";
+    @Deprecated
+    public static final String EXTRA_ETHERNET_FAILED_REASON = "ethernet_failed_reason";
+
+    // 状态定义
+    @Deprecated
+    public static final int ETHERNET_STATE_DISABLED = 0;
+
+    public static final int ETHERNET_STATE_ENABLED = 1;
+
+    public static final int ETHERNET_STATE_UNKNOWN = 2;
+
+    // 广播事件值定义
+
+    public static final int EVENT_DHCP_CONNECT_SUCCESSED = 10;
+
+    public static final int EVENT_DHCP_CONNECT_FAILED = 11;
+
+    public static final int EVENT_DHCP_DISCONNECT_SUCCESSED = 12;
+
+    public static final int EVENT_DHCP_DISCONNECT_FAILED = 13;
+
+    public static final int EVENT_STATIC_CONNECT_SUCCESSED = 14;
+
+    public static final int EVENT_STATIC_CONNECT_FAILED = 15;
+
+    public static final int EVENT_STATIC_DISCONNECT_SUCCESSED = 16;
+
+    public static final int EVENT_STATIC_DISCONNECT_FAILED = 17;
+
+    public static final int EVENT_PHY_LINK_UP = 18;
+
+    public static final int EVENT_PHY_LINK_DOWN = 19;
+
+    public static final int FAILED_REASON_INVALID_PARAMETER = 0;
 
     private final IEthernetManager mService;
     @GuardedBy("mListeners")
diff --git a/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java b/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java
index e0d53682211..9d67d740661 100755
--- a/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java
+++ b/frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetNetworkFactory.java
@@ -21,6 +21,7 @@ import static com.android.internal.util.Preconditions.checkNotNull;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.Context;
+import android.content.Intent;
 import android.net.ConnectivityManager;
 import android.net.EthernetManager;
 import android.net.EthernetNetworkSpecifier;
@@ -70,7 +71,7 @@ public class EthernetNetworkFactory extends NetworkFactory {
     private final static String TAG = EthernetNetworkFactory.class.getSimpleName();
     final static boolean DBG = true;
 
-    private final static int NETWORK_SCORE = 60;
+    private final static int NETWORK_SCORE = 70;
     private static final String NETWORK_TYPE = "Ethernet";
 
     private final ConcurrentHashMap<String, NetworkInterfaceState> mTrackingInterfaces =
@@ -78,7 +79,7 @@ public class EthernetNetworkFactory extends NetworkFactory {
     private final Handler mHandler;
     private final Context mContext;
     private EthernetManager mEthernetManager;
-
+    private static int mEthernetCurrentState = EthernetManager.EVENT_DHCP_DISCONNECT_SUCCESSED;
     private static boolean[] mIfaceStatus = new boolean[2];
 
     public static class ConfigurationException extends AndroidRuntimeException {
@@ -393,6 +394,7 @@ public class EthernetNetworkFactory extends NetworkFactory {
         private @Nullable IpClientCallbacksImpl mIpClientCallback;
         private @Nullable NetworkAgent mNetworkAgent;
         private @Nullable IpConfiguration mIpConfig;
+        private static IpAssignment mConnectMode;
 
         /**
          * An object to contain all transport type information, including base network score and*/
@@ -428,13 +430,13 @@ public class EthernetNetworkFactory extends NetworkFactory {
                     new TransportInfo(ConnectivityManager.TYPE_NONE, 1));
             // EthernetNetworkFactory.NETWORK_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_ETHERNET,
-                    new TransportInfo(ConnectivityManager.TYPE_ETHERNET, 60));
+                    new TransportInfo(ConnectivityManager.TYPE_ETHERNET, 70));
             // BluetoothTetheringNetworkFactory.NETWORK_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_BLUETOOTH,
                     new TransportInfo(ConnectivityManager.TYPE_BLUETOOTH, 69));
             // WifiNetworkFactory.SCORE_FILTER / NetworkAgent.WIFI_BASE_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_WIFI,
-                    new TransportInfo(ConnectivityManager.TYPE_WIFI, 70));
+                    new TransportInfo(ConnectivityManager.TYPE_WIFI, 60));
             // TelephonyNetworkFactory.TELEPHONY_NETWORK_SCORE
             sTransports.put(NetworkCapabilities.TRANSPORT_CELLULAR,
                     new TransportInfo(ConnectivityManager.TYPE_MOBILE, 50));
@@ -512,10 +514,51 @@ public class EthernetNetworkFactory extends NetworkFactory {
             mLegacyType = legacyType;
         }
 
+        private String dumpEthCurrentState(int curState) {
+            if (curState == EthernetManager.EVENT_DHCP_CONNECT_SUCCESSED)
+                return "EVENT_DHCP_CONNECT_SUCCESSED";
+            else if (curState == EthernetManager.EVENT_DHCP_CONNECT_FAILED)
+                return "EVENT_DHCP_CONNECT_FAILED";
+            else if (curState == EthernetManager.EVENT_DHCP_DISCONNECT_SUCCESSED)
+                return "EVENT_DHCP_DISCONNECT_SUCCESSED";
+            else if (curState == EthernetManager.EVENT_DHCP_DISCONNECT_FAILED)
+                return "EVENT_DHCP_DISCONNECT_FAILED";
+            else if (curState == EthernetManager.EVENT_STATIC_CONNECT_SUCCESSED)
+                return "EVENT_STATIC_CONNECT_SUCCESSED";
+            else if (curState == EthernetManager.EVENT_STATIC_CONNECT_FAILED)
+                return "EVENT_STATIC_CONNECT_FAILED";
+            else if (curState == EthernetManager.EVENT_STATIC_DISCONNECT_SUCCESSED)
+                return "EVENT_STATIC_DISCONNECT_SUCCESSED";
+            else if (curState == EthernetManager.EVENT_STATIC_DISCONNECT_FAILED)
+                return "EVENT_STATIC_DISCONNECT_FAILED";
+            else if (curState == EthernetManager.EVENT_PHY_LINK_UP)
+                return "EVENT_PHY_LINK_UP";
+            else if (curState == EthernetManager.EVENT_PHY_LINK_DOWN)
+                return "EVENT_PHY_LINK_DOWN";
+            else if (curState == EthernetManager.ETHERNET_STATE_ENABLED)
+                return "ETHERNET_STATE_ENABLED";
+            else if (curState == EthernetManager.ETHERNET_STATE_DISABLED)
+                return "ETHERNET_STATE_DISABLED";
+            else
+                return "ETHERNET_CONNECT_STATE_DISCONNECT";
+        }
+
+        private void sendEthernetStateChangedBroadcast(int curRusult, int errcode) {
+            if (mEthernetCurrentState == curRusult)
+                return ;
+            mEthernetCurrentState = curRusult;
+            Log.d(TAG, "sendEthernetStateChangedBroadcast: curRusult = " + dumpEthCurrentState(curRusult));
+            final Intent intent = new Intent(EthernetManager.ACTION_ETHERNET_STATE_CHANGED);
+            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+            intent.putExtra(EthernetManager.EXTRA_ETHERNET_STATE, curRusult);
+            intent.putExtra(EthernetManager.EXTRA_ETHERNET_FAILED_REASON, errcode);
+            //mContext.sendStickyBroadcast(intent);
+            mContext.sendBroadcast( intent,android.Manifest.permission.BROADCAST_NETWORK_PRIVILEGED);
+        }
+
         void setIpConfig(IpConfiguration ipConfig) {
             if (Objects.equals(this.mIpConfig, ipConfig)) {
                 if (DBG) Log.d(TAG, "ipConfig have not changed,so ignore setIpConfig");
-                return;
             }
             this.mIpConfig = ipConfig;
             if (mNetworkAgent != null) {
@@ -619,6 +662,10 @@ public class EthernetNetworkFactory extends NetworkFactory {
             };
             mNetworkAgent.register();
             mNetworkAgent.markConnected();
+            if (mConnectMode == IpAssignment.STATIC)
+                sendEthernetStateChangedBroadcast(EthernetManager.EVENT_STATIC_CONNECT_SUCCESSED, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+            else
+                sendEthernetStateChangedBroadcast(EthernetManager.EVENT_DHCP_CONNECT_SUCCESSED, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
         }
 
         void onIpLayerStopped(LinkProperties linkProperties) {
@@ -644,6 +691,14 @@ public class EthernetNetworkFactory extends NetworkFactory {
             if (mLinkUp == up) return false;
             mLinkUp = up;
 
+            if (up) {
+                sendEthernetStateChangedBroadcast(EthernetManager.EVENT_PHY_LINK_UP, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+                //sendNetStateChangedBroadcast(EthernetManager.ETHERNET_STATE_ENABLED, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+            } else {
+                sendEthernetStateChangedBroadcast(EthernetManager.EVENT_PHY_LINK_DOWN, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+                //sendNetStateChangedBroadcast(EthernetManager.ETHERNET_STATE_DISABLED, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+            }
+
             stop();
             if (up) {
                 start();
@@ -666,6 +721,10 @@ public class EthernetNetworkFactory extends NetworkFactory {
                 mNetworkAgent = null;
             }
             mLinkProperties.clear();
+            if (mConnectMode == IpAssignment.STATIC)
+                sendEthernetStateChangedBroadcast(EthernetManager.EVENT_STATIC_DISCONNECT_SUCCESSED, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+            else
+                sendEthernetStateChangedBroadcast(EthernetManager.EVENT_DHCP_DISCONNECT_SUCCESSED, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
         }
 
         private void updateAgent() {
@@ -686,6 +745,7 @@ public class EthernetNetworkFactory extends NetworkFactory {
 
         private static void provisionIpClient(IIpClient ipClient, IpConfiguration config,
                 String tcpBufferSizes) {
+            mConnectMode = config.getIpAssignment();
             if (config.getProxySettings() == ProxySettings.STATIC ||
                     config.getProxySettings() == ProxySettings.PAC) {
                 try {
diff --git a/packages/apps/Settings/src/com/android/settings/ethernet/EthernetSettings.java b/packages/apps/Settings/src/com/android/settings/ethernet/EthernetSettings.java
old mode 100644
new mode 100755
index 143e4762b07..13c9dcbd195
--- a/packages/apps/Settings/src/com/android/settings/ethernet/EthernetSettings.java
+++ b/packages/apps/Settings/src/com/android/settings/ethernet/EthernetSettings.java
@@ -176,6 +176,29 @@ public class EthernetSettings extends SettingsPreferenceFragment
         public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
             log("Action " + action);
+            if(EthernetManager.ACTION_ETHERNET_STATE_CHANGED.equals(action)){
+                int ethernetState = intent.getIntExtra(EthernetManager.EXTRA_ETHERNET_STATE, EthernetManager.ETHERNET_STATE_UNKNOWN);
+                int errorCode = intent.getIntExtra(EthernetManager.EXTRA_ETHERNET_FAILED_REASON, EthernetManager.FAILED_REASON_INVALID_PARAMETER);
+                log("hcq ethernetState = " + ethernetState + " errorCode " + errorCode);
+
+                long currentTime = System.currentTimeMillis();
+                int delayTime = 0;
+
+                if (currentTime - mChangeTime < 1000) {
+                    delayTime = 2000;
+                }
+                
+                if(ethernetState == EthernetManager.EVENT_STATIC_CONNECT_SUCCESSED || ethernetState == EthernetManager.EVENT_DHCP_CONNECT_SUCCESSED){
+
+                        log("hcq enter ETHER_STATE_CONNECTED");
+                        handleEtherStateChange(ETHERNET_STATE.ETHER_STATE_CONNECTED, delayTime);   
+
+                }
+                if(ethernetState == EthernetManager.EVENT_PHY_LINK_DOWN){
+                    log("hcq enter ETHER_STATE_DISCONNECTED");
+                    handleEtherStateChange(ETHERNET_STATE.ETHER_STATE_DISCONNECTED, delayTime);     
+                }
+            }                  
             if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
                 NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                 Log.v(TAG, "===" + info.toString());
@@ -198,6 +221,7 @@ public class EthernetSettings extends SettingsPreferenceFragment
     public EthernetSettings() {
         mIntentFilter = new IntentFilter();
         mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
+               mIntentFilter.addAction(EthernetManager.ACTION_ETHERNET_STATE_CHANGED);
     }
 
     private void handleEtherStateChange(ETHERNET_STATE EtherState, long delayMillis) {
diff --git a/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java b/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java
index da7e660d0b3..cb18eafd7c2 100755
--- a/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java
+++ b/packages/modules/Connectivity/service/src/com/android/server/connectivity/NetworkRanker.java
@@ -85,7 +85,7 @@ public class NetworkRanker {
     }
 
     // Transport preference order, if it comes down to that.
-    private static final int[] PREFERRED_TRANSPORTS_ORDER = { TRANSPORT_WIFI,TRANSPORT_ETHERNET, 
+    private static final int[] PREFERRED_TRANSPORTS_ORDER = { TRANSPORT_ETHERNET,TRANSPORT_WIFI, 
             TRANSPORT_BLUETOOTH, TRANSPORT_CELLULAR };
 
     // Function used to partition a list into two working areas depending on whether they

diff --git a/frameworks/base/core/res/AndroidManifest.xml b/frameworks/base/core/res/AndroidManifest.xml
index a7aa0f49226..abafe593601 100755
--- a/frameworks/base/core/res/AndroidManifest.xml
+++ b/frameworks/base/core/res/AndroidManifest.xml
@@ -101,7 +101,8 @@
     <protected-broadcast android:name="android.intent.action.MY_PACKAGE_SUSPENDED" />
     <protected-broadcast android:name="android.intent.action.MY_PACKAGE_UNSUSPENDED" />
     <protected-broadcast android:name="android.app.action.MANAGED_PROFILE_PROVISIONED" />
-
+       
+       <protected-broadcast android:name="android.net.action.ETHERNET_STATE_CHANGED" />
     <protected-broadcast android:name="android.os.action.POWER_SAVE_MODE_CHANGED" />
     <protected-broadcast android:name="android.os.action.DEVICE_IDLE_MODE_CHANGED" />
     <protected-broadcast android:name="android.os.action.POWER_SAVE_WHITELIST_CHANGED" />

3. 在2的基础上做网络动态切换,当双网共存时,以太网此时没有网络,切换到wifi,且能互切

Date:   Tue Jan 14 19:16:18 2025 +0800

    other : When Ethernet and WiFi are connected simultaneously, Ethernet takes priority in connecting to the external network. When Ethernet cannot connect to the external network, switch to WiFi to connect to the external network

diff --git a/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java b/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
index 23067ca5dba..4f32a13d639 100755
--- a/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/packages/modules/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
@@ -212,14 +212,17 @@ import java.util.function.Function;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;
-
+import android.content.Intent;
+import android.content.IntentFilter;
+import java.lang.reflect.Method;
+import android.os.SystemProperties;    
 /**
  * {@hide}
  */
 public class NetworkMonitor extends StateMachine {
     private static final String TAG = NetworkMonitor.class.getSimpleName();
     private static final boolean DBG  = true;
-    private static final boolean VDBG = false;
+    private static final boolean VDBG = true;
     // TODO(b/185082309): For flaky test debug only, remove it after fixing.
     private static final boolean DDBG_STALL = "cf_x86_auto-userdebug".equals(
             SystemProperties.get("ro.build.flavor", ""));
@@ -3290,6 +3293,27 @@ public class NetworkMonitor extends StateMachine {
         return mLastProbeTime;
     }
 
+       private static void setProperty(String key, String value) {
+               try {
+                               Class<?> c = Class.forName("android.os.SystemProperties");
+                               Method set = c.getMethod("set", String.class, String.class);
+                               set.invoke(c, key, value );
+               } catch (Exception e) {
+                                               e.printStackTrace();
+               }
+       }
+
+       public static boolean isInetReachable(String host, Integer timeOut) {
+               try {
+                       return InetAddress.getByName(host).isReachable(timeOut);
+               } catch (UnknownHostException e) {
+                       e.printStackTrace();
+               } catch (IOException e) {
+                       e.printStackTrace();
+               }
+               return false;
+       }       
+
     @VisibleForTesting
     protected boolean isDataStall() {
         if (!isValidationRequired()) {
@@ -3362,6 +3386,22 @@ public class NetworkMonitor extends StateMachine {
             notifyDataStallSuspected(p);
         }
 
+       String host = "8.8.8.8";
+       int timeOut = 3000;
+       if(!isInetReachable(host,timeOut)){
+               log("hcq check the internet network");
+               if(SystemProperties.get("sys.network.net_prio", "eth").equals("eth")){
+                       setProperty("sys.network.net_prio", "wlan");
+                       typeToCollect = 1;
+               }
+       }else{
+            if(SystemProperties.get("sys.network.net_prio", "eth").equals("wlan")){
+               setProperty("sys.network.net_prio", "eth");
+            }
+
+        }
+
+       log("hcq debug get net_prio = " + SystemProperties.get("sys.network.net_prio", ""));
         // log only data stall suspected.
         if ((DBG && (typeToCollect > 0)) || VDBG_STALL || DDBG_STALL) {
             log("isDataStall: result=" + typeToCollect + ", " + msg);
diff --git a/packages/modules/Wifi/service/java/com/android/server/wifi/WifiScoreReport.java b/packages/modules/Wifi/service/java/com/android/server/wifi/WifiScoreReport.java
old mode 100644
new mode 100755
index 067181b3c50..035c547cec0
--- a/packages/modules/Wifi/service/java/com/android/server/wifi/WifiScoreReport.java
+++ b/packages/modules/Wifi/service/java/com/android/server/wifi/WifiScoreReport.java
@@ -44,6 +44,8 @@ import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.LinkedList;
 import java.util.Locale;
+import android.os.SystemProperties;
+import android.net.NetworkAgent;
 
 /**
  * Class used to calculate scores for connected wifi networks and report it to the associated*/
@@ -54,7 +56,7 @@ public class WifiScoreReport {
 
     private static final int DUMPSYS_ENTRY_COUNT_LIMIT = 3600; // 3 hours on 3 second poll
 
-    private boolean mVerboseLoggingEnabled = false;
+    private boolean mVerboseLoggingEnabled = true;
     private static final long FIRST_REASONABLE_WALL_CLOCK = 1490000000000L; // mid-December 2016
 
     private static final long MIN_TIME_TO_KEEP_BELOW_TRANSITION_SCORE_MILLIS = 9000;
@@ -528,6 +530,16 @@ public class WifiScoreReport {
         mVerboseLoggingEnabled = enable;
     }
 
+       private int adjustScore() {
+               int score = 60; //default 60
+               String net_prio = SystemProperties.get("sys.network.net_prio", "eth");
+       
+               if (net_prio.equals("wlan")) {
+                       score += 20;
+               }
+               return score;
+       }
+
     /**
      * Calculate wifi network score based on updated link layer stats and send the score to
      * the WifiNetworkAgent.*/
@@ -598,6 +610,8 @@ public class WifiScoreReport {
             score = 0;
         }
 
+        score = adjustScore();
+        Log.d(TAG, "new score " + score + " old score " + mWifiInfo.score);
         // report score
         mLegacyIntScore = score;
         reportNetworkScoreToConnectivityServiceIfNecessary();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值