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

Android 透過 APN 判斷網路類型與設定代理

編輯:關於 Android 程式設計

早期很多文章說「無法可靠取得手機號碼」,這句話到今天仍然成立——不同電信、不同 SIM 卡差異很大,多數情況下已經取不到了。但如果你的需求是「判斷使用者目前走的是哪一種 APN」,那還有另一條思路。本文說明如何讀取 APN 資訊,並順帶處理代理設定。

一、定義 APN 常數

先把電信業者常用的 APN 名稱收攏成常數,避免程式碼裡散落一堆魔法字串:

/** 電信 APN 列表 */
public class APNNET {
    public static final String CTWAP = "ctwap";   // 電信 WAP 閘道
    public static final String CTNET = "ctnet";   // 電信 直接聯網
}

二、讀取目前使用的 APN 類型

透過 ContentResolver 查詢系統的 APN 設定表,讀出 user 欄位再比對前綴:

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class ApnUtil {

    private static final Uri PREFERRED_APN_URI =
            Uri.parse("content://telephony/carriers/preferapn");

    /** 取得目前的 APN 類型,找不到時回傳 nomatch */
    public static String getApnType(Context context) {
        String apntype = "nomatch";

        Cursor c = context.getContentResolver()
                .query(PREFERRED_APN_URI, null, null, null, null);
        if (c == null) return apntype;

        try {
            if (c.moveToFirst()) {
                int userIndex = c.getColumnIndex("user");
                String user = (userIndex != -1) ? c.getString(userIndex) : null;
                if (user != null) {
                    if (user.startsWith(APNNET.CTNET)) {
                        apntype = APNNET.CTNET;
                    } else if (user.startsWith(APNNET.CTWAP)) {
                        apntype = APNNET.CTWAP;
                    }
                }
            }
        } finally {
            c.close();     // Cursor 一定要關
        }
        return apntype;
    }
}

這裡補了兩處防禦:查詢可能回傳 null(使用者未設定 APN 或無權限),以及 getColumnIndex 可能回傳 -1。原範例直接 c.moveToFirst() 後取值,在空 Cursor 上會引發 SQLException。

三、讀取並設定代理資訊

APN 設定裡除了 user,還有 proxy、port、password 等欄位。有些企業網路必須透過代理才能對外連線,若 App 沒有跟著設定,就會出現「明明有網路卻連不上」的狀況。

Cursor c = context.getContentResolver()
        .query(PREFERRED_APN_URI, null, null, null, null);
if (c != null && c.moveToFirst()) {
    String proxy = c.getString(c.getColumnIndex("proxy"));
    if (proxy != null && !"".equals(proxy)) {
        Properties prop = System.getProperties();
        prop.put("proxySet", "true");
        prop.setProperty("http.proxyHost", proxy);
        prop.setProperty("http.proxyPort", c.getString(c.getColumnIndex("port")));

        // 若代理需要認證
        String authentication = c.getString(c.getColumnIndex("user"))
                + ":" + c.getString(c.getColumnIndex("password"));
        String encodedLogin = Base64.encodeToString(
                authentication.getBytes(), Base64.DEFAULT);
        // 記得在實際請求時帶上這個標頭
        // urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
    }
    c.close();
}

原範例的 Base64.encode(authentication) 有兩個問題:Android 的 Base64.encode 需要傳入 byte 陣列,且靜態方法回傳 byte 陣列而非 String,直接字串串接會得到陣列的 toString() 結果。正確寫法如上,使用 encodeToString。

關於「取得手機號碼」這件事

需要老實說明:TelephonyManager.getLine1Number() 這個 API 從很早以前就存在,但實際上多數國家的電信業者並不會把號碼寫進 SIM 卡的 EF_MSISDN 檔案,因此它經常回傳空字串或 null。加上 Android 10 之後對 READ_PHONE_STATE 等權限收緊、隱私政策審核趨嚴,以「讀 SIM 卡拿號碼」作為註冊流程的做法已經不可靠,也不容易通過應用商店審核。

目前的正確解法是:用簡訊驗證碼或手機號碼一鍵登入。號碼由使用者主動輸入並驗證,App 完全不需要嘗試讀取;電信業者的一鍵登入服務則由运营商 SDK 取得 token 後向後端換號碼,全程不接觸 SIM 卡隱私資料。

另外,content://telephony/carriers 屬於受保護的系統表,在較新的 Android 版本上一般應用查詢會被拒絕或回傳空結果。因此這段 APN 邏輯在現代 App 中的實用性有限,主要價值在於理解 Android 的 ContentProvider 查詢寫法。

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