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

Android 系統移植:在開發者選項中新增「Wifi 調試」開關的完整實現

編輯:關於 Android 程式設計

adb 無線調試本身並不新鮮,但每次都要先用 USB 連上、敲幾條命令設置,實在麻煩。更合理的做法是在「開發者選項」裡放一個「Wifi 調試」開關,打開即可無線連接。本文記錄從命令原理到 Settings 界面再到 framework 與 init.rc 的完整落地過程。

先看原理:手動怎麼做

手機端:開啟 adb 的 TCP 監聽端口

:/$ setprop service.adb.tcp.port 5555
:/$ stop adbd
:/$ start adbd

setprop 用於設置系統屬性,這裡只需 su 權限,不必 root。可以透過 adb shell 執行,也可以在手機上安裝 Terminal 應用直接敲。

電腦端:連接與斷開

adb connect phone_ipaddress:portnumber
adb shell
adb disconnect phone_ipaddress:port

其中 phone_ipaddress 是手機的 IP,portnumber 就是剛才設置的 5555。

界面效果

最終要做到的是三種狀態:

開關打開且已連接 Wifi——顯示完整的 adb connect 命令與當前 IP。

開關打開但未連接 Wifi——提示需要連接 Wifi。

開關關閉——恢復常態說明文字。

整體思路

第一步:在【設置】→【開發者選項】中新增一個類似【USB 調試】的開關。第二步:開關打開時激活 5555 端口監聽,關閉時停止監聽。第三步:在開關的 toggle 邏輯中調用合適的接口。第四步:把該接口的底層實現補上。

第一步:布局與字串資源

找到 packages/apps/Settings/res/xml/development_prefs.xml,定位【USB 調試】開關,在其後追加新開關:

<!-- USB 調試開關,原有 -->
<SwitchPreference
    android:key="enable_adb"
    android:title="@string/enable_adb"
    android:summary="@string/enable_adb_summary" />

<!-- 新增的 Wifi 調試開關 -->
<SwitchPreference
    android:key="enable_wifi_adb"
    android:title="@string/enable_wifi_adb"
    android:summary="@string/enable_wifi_adb_summary" />

接著補上中英文串。packages/apps/Settings/res/values-zh-rCN/strings.xml:

<string name="enable_wifi_adb">Wifi調試</string>
<string name="enable_wifi_adb_openwifi">Wifi沒連接,請連接wifi</string>
<string name="enable_wifi_adb_summary">連接Wifi後啟用調試模式</string>
<string name="enable_wifi_adb_connected_summary">
Wifi調試已打開,在電腦端你可以輸入以下命令進行調試:
adb connect %1$s:5555</string>

packages/apps/Settings/res/values/strings.xml:

<string name="enable_wifi_adb">Wifi debugging</string>
<string name="enable_wifi_adb_openwifi">
Wifi is not connected, please turn wifi on and connect it</string>
<string name="enable_wifi_adb_summary">Debug mode when Wifi is connected</string>
<string name="enable_wifi_adb_connected_summary">
adb wifi is on, from your computer run: adb connect %1$s:5555</string>

注意 %1$s 是佔位符,會在執行期被替換為實際 IP。

第二步:DevelopmentSettings 中的邏輯

先定義常量與成員變量:

private static final String ENABLE_WIFI_ADB = "enable_wifi_adb";
private static final String ADB_WIFI_ENABLED_KEY = "ADB_WIFI_ENABLED";
private static SwitchPreference mEnableWifiAdb;

在 onCreate() 中初始化開關:

mEnableAdb = findAndInitSwitchPref(ENABLE_ADB);
mEnableWifiAdb = findAndInitSwitchPref(ENABLE_WIFI_ADB);

接著在 onPreferenceTreeClick() 中處理開關行為。這段是整個功能的核心:

else if (preference == mEnableWifiAdb) {
    if (mEnableWifiAdb.isChecked()) {
        // 1. 記錄開關狀態
        Settings.Global.putInt(getActivity().getContentResolver(),
                ADB_WIFI_ENABLED_KEY, 1);
        // 2. 設置系統屬性,觸發 init 腳本開啟端口監聽
        android.os.SystemProperties.set("sys.connect.adb.wifi", "1");

        // 3. 取得當前 Wifi IP 並組裝字串
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ipAddressString = (ipAddress & 0xFF) + "."
                + ((ipAddress >> 8) & 0xFF) + "."
                + ((ipAddress >> 16) & 0xFF) + "."
                + (ipAddress >> 24 & 0xFF);

        if ("0.0.0.0".equals(ipAddressString)) {
            // 未連上 Wifi
            mEnableWifiAdb.setSummary(
                    getResources().getString(R.string.enable_wifi_adb_openwifi));
        } else {
            mEnableWifiAdb.setSummary(getResources().getString(
                    R.string.enable_wifi_adb_connected_summary, ipAddressString));
        }
    } else {
        Settings.Global.putInt(getActivity().getContentResolver(),
                ADB_WIFI_ENABLED_KEY, 0);
        android.os.SystemProperties.set("sys.connect.adb.wifi", "0");
        mEnableWifiAdb.setSummary(
                getResources().getString(R.string.enable_wifi_adb_summary));
    }
}

IP 地址的組裝方式值得說明一下:WifiInfo.getIpAddress() 回傳的是 little-endian 的 int,最低位元組才是第一段,因此需要 & 0xFF 後依次右移拼接,直接 toString 會得到錯誤結果。

第三步:狀態持久化與界面刷新

ADB_WIFI_ENABLED_KEY 的作用是記住上次的開關狀態。在 onResume() 中讀回來,同時註冊廣播以監聽 Wifi 狀態變化:

IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(wifiBroadcastReceiver, filter);

boolean isAdbWifiChecked = Settings.Global.getInt(
        getActivity().getContentResolver(), ADB_WIFI_ENABLED_KEY, 0) != 0;
mEnableWifiAdb.setChecked(isAdbWifiChecked);

在 updateAllOptions() 中同樣要刷新一次:

boolean isAdbWifiChecked = Settings.Global.getInt(cr, ADB_WIFI_ENABLED_KEY, 0) != 0;
updateSwitchPreference(mEnableWifiAdb, isAdbWifiChecked);

廣播接收者的職責是動態更新說明文字:

BroadcastReceiver wifiBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean isAdbWifiChecked = mEnableWifiAdb.isChecked();

        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo net = connectivityManager.getActiveNetworkInfo();
        if (net == null) {
            if (isAdbWifiChecked) {
                mEnableWifiAdb.setSummary(
                        getResources().getString(R.string.enable_wifi_adb_openwifi));
            }
        }

        State wifi = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
            WifiManager wifiManager =
                    (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            String ipAddressString = (ipAddress & 0xFF) + "."
                    + ((ipAddress >> 8) & 0xFF) + "."
                    + ((ipAddress >> 16) & 0xFF) + "."
                    + (ipAddress >> 24 & 0xFF);
            if (isAdbWifiChecked) {
                mEnableWifiAdb.setSummary(getResources().getString(
                        R.string.enable_wifi_adb_connected_summary, ipAddressString));
            }
        } else if (wifi == State.DISCONNECTED || wifi == State.DISCONNECTING) {
            if (isAdbWifiChecked) {
                mEnableWifiAdb.setSummary(
                        getResources().getString(R.string.enable_wifi_adb_openwifi));
            }
        }
    }
};

這樣一來,使用者從開著 Wifi 走到沒訊號的環境,說明文字會自動跟著變化,不必重進頁面。

第四步:底層接口的實現

SystemProperties.set() 的 Java 層實現很薄,最終會走到 native 方法:

public static void set(String key, String val) {
    if (key.length() > PROP_NAME_MAX) {
        throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
    }
    if (val != null && val.length() > PROP_VALUE_MAX) {
        throw new IllegalArgumentException("val.length > " + PROP_VALUE_MAX);
    }
    native_set(key, val);
}

private static native void native_set(String key, String def);

其 JNI 實現位於 frameworks/base/core/jni/android_os_SystemProperties.cpp,核心是最終呼叫 property_set(key, val)。這條鏈路不必改動——我們要做的只是提供一個「誰來響應這個屬性變化」的監聽者。

答案就在 init.rc。在 device/<vendor>/<project>/E580/init.rc 中加入:

# 開啟 adb wifi 調試
on property:sys.connect.adb.wifi=1
    setprop service.adb.tcp.port 5555
    stop adbd
    start adbd

on property:sys.connect.adb.wifi=0
    setprop service.adb.tcp.port ""
    stop adbd
    start adbd

也就是說:屬性設為 1 時監聽 5555 端口,設為 0 時清空端口配置。adbd 必須先 stop 再 start,新的端口設定才會生效——這一步常被遺漏,導致「看起來設置成功但連不上」。

驗證

重新連接 Wifi、打開【Wifi 調試】開關,可以看到當前 IP(例如 192.168.107.168):

在 PC 端執行連接與斷開:

C:\Documents and Settings\Administrator>adb connect 192.168.107.168
connected to 192.168.107.168:5555

C:\Documents and Settings\Administrator>adb shell
shell@lentk6735_66t_l1:/ $ ll
drwxr-xr-x root   root             2015-12-21 10:15 acct
drwxrwx--- system cache           2015-12-17 19:01 cache
lrwxrwxrwx root   root             1970-01-01 08:00 charger -> /sbin/healthd
dr-x------ root   root             2015-12-21 10:15 config
drwxr-xr-x root   root             2015-12-21 10:15 custom
lrwxrwxrwx root   root             2015-12-21 10:15 d -> /sys/kernel/debug
drwxrwx--x system system           2015-12-21 10:16 data
-rw-r--r-- root   root      385    1970-01-01 08:00 default.prop
drwxr-xr-x root   root             2015-12-21 10:15 dev
lrwxrwxrwx root   root             2015-12-21 10:15 etc -> /system/etc
-rw-r--r-- root   root      1851   1970-01-01 08:00 factory_init.project.rc
-rw-r--r-- root   root      18861  1970-01-01 08:00 factory_init.rc
-rw-r--r-- root   root      31413  1970-01-01 08:00 file_contexts
-rw-r----- root   root      1980   1970-01-01 08:00 fstab.mt6735
-rwxr-x--- root   root      543928 1970-01-01 08:00 init
-rwxr-x--- root   root      22787  1970-01-01 08:00 init.rc
drwxr-xr-x root   root             1970-01-01 08:00 sbin
lrwxrwxrwx root   root             2015-12-21 10:15 sdcard -> /storage/sdcard0
drwxr-xr-x root   root             1970-01-01 08:00 system
-rw-r--r-- root   root      8642   1970-01-01 08:00 ueventd.rc
lrwxrwxrwx root   root             2015-12-21 10:15 vendor -> /system/vendor

shell@lentk6735_66t_l1:/ $ exit

C:\Documents and Settings\Administrator>adb disconnect 192.168.107.168

無線調試一切正常。再把開關關掉,此時執行 adb connect 就會失敗:

C:\Documents and Settings\Administrator>adb connect 192.168.107.168
unable to connect to 192.168.107.168:5555

整個改動橫跨四層:Settings 的布局與字串、DevelopmentSettings 的開關邏輯、SystemProperties 到 property_set 的 JNI 鏈路,以及 init.rc 中對屬性變化的響應。缺任何一層,功能都不會通。理解這條鏈路之後,同類的「用系統屬性驅動 native 行為」需求都能照樣複製。

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