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

Android 5.0 以上移動網路開關失效的追查過程

編輯:關於 Android 程式設計

最近遇到一個頗有意思的 bug,記錄下來分享。

那天早上陽光正好,一封 bug 郵件飄進信箱。來回確認之後,症狀很明確:我負責的 Widget 網路開關,在 Android 5.0 以上的系統上完全沒反應。

傳統做法是什麼

做過移動網路開關的人大概都熟悉這條路:在 ConnectivityManager 上反射 setMobileDataEnabled 與 getMobileDataEnabled 這兩個方法。它們在早期版本中確實存在:

/** @hide */
public boolean getMobileDataEnabled() {
    try {
        return mService.getMobileDataEnabled();
    } catch (RemoteException e) {
        return true;
    }
}

/** @hide */
public void setMobileDataEnabled(boolean enabled) {
    try {
        mService.setMobileDataEnabled(enabled);
    } catch (RemoteException e) {
    }
}

問題是,翻開 5.0 以上的原始碼,這兩個方法已經被移除了。反射找不到方法,自然什麼都不會發生。

換一條路:TelephonyManager

同事提醒我往 TelephonyManager 的方向試。查了 5.0 之後的原始碼,確實多了這對新方法:

/** @hide */
@SystemApi
public void setDataEnabled(boolean enable) {
    try {
        getITelephony().setDataEnabled(enable);
    } catch (RemoteException e) {
        Log.e(TAG, "Error calling ITelephony#setDataEnabled", e);
    }
}

/** @hide */
@SystemApi
public boolean getDataEnabled() {
    try {
        return getITelephony().getDataEnabled();
    } catch (RemoteException e) {
        Log.e(TAG, "Error calling ITelephony#getDataEnabled", e);
    }
    return false;
}

於是改寫成這樣:

public void setMobileDataState(Context cxt, boolean mobileDataEnabled) {
    TelephonyService telephonyService = (TelephonyManager)
            cxt.getSystemService(Context.TELEPHONY_SERVICE);
    try {
        Method method = telephonyService.getClass()
                .getDeclaredMethod("setDataEnabled", boolean.class);
        if (null != method) {
            method.invoke(telephonyService, mobileDataEnabled);
        }
    } catch (Exception e) {
        LogHelper.v(TAG, "Error setting " + e + telephonyService);
    }
}

結果拋出了 InvocationTargetException。這個例外只是反射的外層包裝,真正的錯誤要透過 ((InvocationTargetException) e).getTargetException() 才看得到:

java.lang.SecurityException: Neither user 10240 nor current process
has android.permission.MODIFY_PHONE_STATE

權限不足。而 MODIFY_PHONE_STATE 是 signature 等級的權限,普通應用簽不出來,宣告在 manifest 裡也沒用。

意外發現

同事建議把 App 丟到 system/app 底下試試,幾番嘗試仍然是同樣的結果。後來某次無意間把 App 放到了 system/priv-app,居然就成功了——這個目錄下的應用屬於 privileged 等級,能拿到 signature 權限。

當然,一般應用不可能裝在這裡,最終只能退而求其次採取折衷方案。不過整個過程還是很過瘾:這是我第一次這麼直接地感受到不同 Android 版本之間原始碼的差異,也再次確認了「@hide 的 API 隨時可能消失」這件事。反射呼叫系統隱藏方法從來不是長久之計,能走官方 API 或搭配系統簽章的方案,才是穩定的做法。

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