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

Android 系統定制:APN 配置項無法顯示的源碼追蹤全記錄

編輯:關於 Android 程式設計

在定製系統原生 Settings.apk 時,遇到過這樣一個問題:手動增加了 APN 配置選項,但界面始終看不到。原本以為只是簡單的頁面顯示問題,結果一路追下去,差點追到 HAL 層。本文把整個排查過程記錄下來。

一、ApnSettings 的入口邏輯

Settings 的源碼位於 packages/apps/Settings/src/com/android/settings/ 目錄下。APN 相關的核心類是 ApnSettings,它繼承自 PreferenceActivity 並實現 Preference.OnPreferenceChangeListener 接口。PreferenceActivity 是 Android 中專門用於構建設置界面與存儲參數的 Activity 類型。

public class ApnSettings extends PreferenceActivity
        implements Preference.OnPreferenceChangeListener {

    // 恢復出廠設置的 URI
    public static final String RESTORE_CARRIERS_URI = "content://telephony/carriers/restore";
    // 用於 ContentProvider 保存 APN 配置信息的 URI
    public static final String PREFERRED_APN_URI = "content://telephony/carriers/preferapn";

    private static final Uri DEFAULTAPN_URI = Uri.parse(RESTORE_CARRIERS_URI);
    private static final Uri PREFERAPN_URI = Uri.parse(PREFERRED_APN_URI);
}

在 onCreate 中,它透過 addPreferencesFromResource(R.xml.apn_settings) 加載界面。值得注意的是,res/xml/apn_settings.xml 實際上只是一個空的 PreferenceScreen,真正的列表內容需要運行時動態填充。

二、界面為什麼是空的

onCreate 中還創建了一個 Intent 過濾器,過濾的動作是 ACTION_ANY_DATA_CONNECTION_STATE_CHANGED;onResume 中則註冊了對應的廣播接收者:

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mMobileStateReceiver, mMobileStateFilter);
    if (!mRestoreDefaultApnMode) {
        fillList();   // 填充 Activity 的列表
    } else {
        showDialog(DIALOG_RESTORE_DEFAULTAPN);
    }
}

也就是說,APN 列表並不是寫死在布局裡的,而是由 fillList() 在運行時從數據庫查詢後動態生成。如果 fillList 查不到數據,界面自然一片空白——這正是問題的根源所在。

三、fillList 的關鍵:運營商碼匹配

private void fillList() {
    // 獲取系統的 gsm.sim.operator.numeric 屬性
    String where = "numeric=\"" +
        android.os.SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, "") + "\"";

    // 調用系統提供的 ContentProvider 查詢數據庫
    Cursor cursor = getContentResolver().query(Telephony.Carriers.CONTENT_URI,
            new String[] { "_id", "name", "apn", "type" },
            where, null, Telephony.Carriers.DEFAULT_SORT_ORDER);

    PreferenceGroup apnList = (PreferenceGroup) findPreference("apn_list");
    apnList.removeAll();

    mSelectedKey = getSelectedApnKey();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        String name = cursor.getString(NAME_INDEX);
        String apn = cursor.getString(APN_INDEX);
        String key = cursor.getString(ID_INDEX);
        String type = cursor.getString(TYPES_INDEX);

        ApnPreference pref = new ApnPreference(this);
        pref.setKey(key);
        pref.setTitle(name);
        pref.setSummary(apn);
        pref.setPersistent(false);
        pref.setOnPreferenceChangeListener(this);

        boolean selectable = ((type == null) || !type.equals("mms"));
        pref.setSelectable(selectable);
        if (selectable && mSelectedKey != null && mSelectedKey.equals(key)) {
            pref.setChecked();
        }
        apnList.addPreference(pref);
        cursor.moveToNext();
    }
    cursor.close();
}

這段代碼揭示了一個關鍵事實:查詢 APN 列表時,條件是 numeric = 系統屬性 gsm.sim.operator.numeric。這個屬性來自 SIM 卡的運營商碼(MCC+MNC)。數據庫位於 /data/data/com.android.providers.Telephony 下的 telephony.db 文件中的 carriers 表。

因此,如果你手動插入了一條 APN 記錄,但它的 numeric 字段與當前 SIM 卡的運營商碼不一致,那麼這條記錄永遠不會出現在界面上。這正是「加了卻看不見」的最常見原因。

四、自定義 APN 條目的入口

添加與編輯 APN 都透過 Options Menu 觸發:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(0, MENU_NEW, 0, getResources().getString(R.string.menu_new))
        .setIcon(android.R.drawable.ic_menu_add);
    menu.add(0, MENU_RESTORE, 0, getResources().getString(R.string.menu_restore))
        .setIcon(android.R.drawable.ic_menu_upload);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case MENU_NEW:
            addNewApn();          // 新增 APN
            return true;
        case MENU_RESTORE:
            restoreDefaultApn();  // 恢復出廠設置
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private void addNewApn() {
    startActivity(new Intent(Intent.ACTION_INSERT, Telephony.Carriers.CONTENT_URI));
}

// 響應列表項目的單擊事件,進入編輯界面
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    int pos = Integer.parseInt(preference.getKey());
    Uri url = ContentUris.withAppendedId(Telephony.Carriers.CONTENT_URI, pos);
    startActivity(new Intent(Intent.ACTION_EDIT, url));
    return true;
}

五、編輯界面 ApnEditor

無論新增還是編輯,都會進入 ApnEditor。它同樣繼承自 PreferenceActivity,並實現 SharedPreferences.OnSharedPreferenceChangeListener 與 Preference.OnPreferenceChangeListener 兩個接口,界面由 R.xml.apn_editor 定義。

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    addPreferencesFromResource(R.xml.apn_editor);

    mName = (EditTextPreference) findPreference("apn_name");
    mApn = (EditTextPreference) findPreference("apn_apn");
    mProxy = (EditTextPreference) findPreference("apn_http_proxy");
    mPort = (EditTextPreference) findPreference("apn_http_port");
    mUser = (EditTextPreference) findPreference("apn_user");
    mServer = (EditTextPreference) findPreference("apn_server");
    mPassword = (EditTextPreference) findPreference("apn_password");
    mMmsProxy = (EditTextPreference) findPreference("apn_mms_proxy");
    mMmsPort = (EditTextPreference) findPreference("apn_mms_port");
    mMmsc = (EditTextPreference) findPreference("apn_mmsc");
    mMcc = (EditTextPreference) findPreference("apn_mcc");
    mMnc = (EditTextPreference) findPreference("apn_mnc");
    mApnType = (EditTextPreference) findPreference("apn_type");

    final Intent intent = getIntent();
    final String action = intent.getAction();
    mFirstTime = icicle == null;

    if (action.equals(Intent.ACTION_EDIT)) {
        mUri = intent.getData();
    } else if (action.equals(Intent.ACTION_INSERT)) {
        if (mFirstTime || icicle.getInt(SAVED_POS) == 0) {
            mUri = getContentResolver().insert(intent.getData(), new ContentValues());
        } else {
            mUri = ContentUris.withAppendedId(Telephony.Carriers.CONTENT_URI,
                    icicle.getInt(SAVED_POS));
        }
        mNewApn = true;
        if (mUri == null) {
            finish();
            return;
        }
        setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
    } else {
        finish();
        return;
    }

    mCursor = managedQuery(mUri, sProjection, null, null);
    mCursor.moveToFirst();
    fillUi();
}

可以看到,ACTION_INSERT 時會先向 ContentProvider 插入一條空記錄取得 URI,再透過 fillUi() 把數據填進各個 Preference;保存時則把界面上的值寫回同一 URI 對應的記錄。

六、排查結論

回過頭看,APN 配置「加了卻看不見」的排查路徑其實很清晰:

  1. 確認界面數據來源——不是布局文件,而是 fillList() 的數據庫查詢結果。
  2. 檢查查詢條件 numeric 是否與當前 SIM 卡的運營商碼一致。
  3. 確認插入的記錄 type 字段是否為 mms(mms 類型的 APN 默認不可選中,會被排到列表末尾)。
  4. 檢查 telephony.db 中 carriers 表的數據是否真正寫入成功。

系統源碼的追蹤往往比想像中曲折,但只要沿著「數據從哪裡來」這條線索走,大多數看似玄學的顯示問題都能找到明確答案。

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