Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 4.4 KitKat 使能有線網絡 Ethernet 的配置與源碼流程

編輯:關於 Android 程式設計

背景

Andriod KitKat 其實已經內置了 Ethernet 支持,只是默認沒有打開。稍微改幾個配置就能直接用起來。實測下瀏覽器和下載都正常,而且能和 WiFi 共存,互不干擾。本文記錄使能步驟,並順著源碼走一遍鏈路。

一、Linux 層

前提是內核已經支持有線網卡,能正常生成 eth0 之類的網絡設備節點。這一步不滿足,後面全是空談。可以用 ifconfig -a 或 ip link 確認。

二、Android 配置

1. overlay 中聲明網絡類型

修改 frameworks/base/core/res/res/values/config.xml(實踐中更推薦放到 device 目錄下的 overlay 裡,避免污染公共代碼):

<string-array translatable="false" name="radioAttributes">
    <item>"1,1"</item>
    <item>"7,1"</item>
    <item>"9,1"</item>
</string-array>

這裡的 9 就是 Ethernet 的網絡類型,定義在 ConnectivityManager.java:

/**
 * The Ethernet data connection. When active, all data traffic
 * will use this network type's interface by default
 * (it has a default route).
 */
public static final int TYPE_ETHERNET = 9;

數組裡每項的格式是「類型,可用性」,第二位 1 表示默認可用。

2. init.rc 中添加 DHCP 服務

在 init.<board>.rc 裡追加兩個 service:

# DHCPCD
service dhcpcd_eth0 /system/bin/dhcpcd -ABKL
    class main
    disabled
    oneshot

# IP Renew
service iprenew_eth0 /system/bin/dhcpcd -n
    class main
    disabled
    oneshot

disabled 表示不隨 class 自動啟動,而是按需觸發;oneshot 表示執行完一次就退出,不重新拉起。-ABKL 幾個參數分別對應 ARP 探測、廣播、避免 fork 等行為。

三、流程分析

ConnectivityService:讀配置建 tracker

構造函數會把 radioAttributes 逐項解析進內存:

public ConnectivityService(Context context,
        INetworkManagementService netManager,
        INetworkStatsService statsService,
        INetworkPolicyManager policyManager, NetworkFactory netFactory) {
    ......
    // Load device network attributes from resources
    String[] raStrings = context.getResources().getStringArray(
            com.android.internal.R.array.radioAttributes);
    for (String raString : raStrings) {
        RadioAttributes r = new RadioAttributes(raString);
        if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
            loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
            continue;
        }
        if (mRadioAttributes[r.mType] != null) {
            loge("Error in radioAttributes - ignoring attempt to redefine type " + r.mType);
            continue;
        }
        mRadioAttributes[r.mType] = r;
    }

接著根據配置為每種網絡類型創建對應的 NetworkStateTracker,並啟動監聽:

// Create and start trackers for hard-coded networks
for (int targetNetworkType : mPriorityList) {
    final NetworkConfig config = mNetConfigs[targetNetworkType];
    final NetworkStateTracker tracker;
    try {
        tracker = netFactory.createTracker(targetNetworkType, config);
        mNetTrackers[targetNetworkType] = tracker;
    } catch (IllegalArgumentException e) {
        Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType) + " tracker: " + e);
        continue;
    }
    tracker.startMonitoring(context, mTrackerHandler);
    if (config.isDefault()) {
        tracker.reconnect();
    }
}

類型為 9 時,createTracker 返回的就是 EthernetDataTracker。

EthernetDataTracker:找網卡、點亮、要 IP

它首先要找到第一個匹配命名規則的網口。規則寫在 config_ethernet_iface_regex:

<!-- Regex of wired ethernet ifaces -->
<string translatable="false" name="config_ethernet_iface_regex">eth\d</string>

然後枚舉系統所有網絡接口,匹配成功就 up 起來並觸發 DHCP:

sIfaceMatch = context.getResources().getString(
        com.android.internal.R.string.config_ethernet_iface_regex);
try {
    final String[] ifaces = mNMService.listInterfaces();
    for (String iface : ifaces) {
        if (iface.matches(sIfaceMatch)) {
            mNMService.setInterfaceUp(iface);
            InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
            if (getEthernetCarrierState(iface) == 1) {
                mIface = iface;
                mLinkUp = true;
                mNetworkInfo.setIsAvailable(true);
                if (config != null && mHwAddr == null) {
                    mHwAddr = config.getHardwareAddress();
                    if (mHwAddr != null) {
                        mNetworkInfo.setExtraInfo(mHwAddr);
                    }
                }
            }
            // 如果之前已為該接口起過 DHCP 客戶端,先停掉
            NetworkUtils.stopDhcp(iface);
        }
    }
    reconnect();
} catch (RemoteException e) {
    Log.e(TAG, "Could not get list of interfaces " + e);
}

DHCP 成功拿到地址後,更新網絡狀態並發消息通知上層:

mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, mHwAddr);
Message msg = mCsHandler.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
msg.sendToTarget();

這條消息會引發 ConnectivityManager.CONNECTIVITY_ACTION 廣播,上層應用收到後就可以正常發網絡請求了。

一個明顯的局限

看上面的代碼就能發現問題:EthernetDataTracker 只保存一個 mIface,找到第一個匹配的接口就停下。如果板子上有兩個以上網口,這個實現顯然不夠用。要支持多網口,必須把它擴展成維護一份接口列表,並為每個接口獨立管理 DHCP 狀態和地址——這部分需要改動 framework,工作量不小。

另外提醒一句:Android 8.0 之後網絡相關架構變化很大,ConnectivityService 被大幅重構,Ethernet 也提供了基於 EthernetNetworkFactory 和 EthernetTracker(後改名 EthernetNetworkInterfaceState)的新實現,並支持 ethernet/interface 屬性配置多網口。本文的代碼路徑只適用於 4.4 及相近版本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved