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

Android 判斷 SIM 卡所屬運營商的實現思路與代碼

編輯:關於 Android 程式設計

有些功能需要按運營商做差異化處理——短信網關號碼、彩信配置、充值入口等等。判斷依據是 IMSI(國際移動用戶識別碼)的前五位,即 MCC + MNC。

核心邏輯是從 TelephonyManager 取出 getSubscriberId(),再按號段前綴匹配:

public String getProvidersName() {
    String str = "N/A";
    try {
        this.IMSI = this.telephonyManager.getSubscriberId();
        if (this.IMSI == null) {
            return str;
        }
        // 中國移動:46000、46002、46007
        if (this.IMSI.startsWith("46000")
                || this.IMSI.startsWith("46002")
                || this.IMSI.startsWith("46007")) {
            str = "中國移動";
        }
        // 中國聯通:46001、46006、46009
        else if (this.IMSI.startsWith("46001")
                || this.IMSI.startsWith("46006")
                || this.IMSI.startsWith("46009")) {
            str = "中國聯通";
        }
        // 中國電信:46003、46005、46011
        else if (this.IMSI.startsWith("46003")
                || this.IMSI.startsWith("46005")
                || this.IMSI.startsWith("46011")) {
            str = "中國電信";
        }
    } catch (Exception localException) {
        localException.printStackTrace();
    }
    return str;
}

其中 telephonyManager 的獲取:

this.telephonyManager =
        (TelephonyManager) paramContext.getSystemService("phone");

幾個實踐提醒

1. 別忘了空值判斷。平板、無 SIM 卡設備、以及飛行模式下的 getSubscriberId() 都可能回傳 null,直接調 startsWith 會拋空指針。

2. 分支結構要理清。運營商判斷本質是「多個前綴對應一個運營商」,用 || 把同運營商的號段並在一起,再用 else if 串起運營商之間的互斥關係,比連續寫多個獨立 if 更清晰,也不容易出錯。

3. 號段會隨時間變化。隨著工信部持續放號,運營商號段是在增加的。硬編碼一份列表遲早過時,若業務對準確性要求高,建議把號段表放在配置或服務端下發,便於隨時更新。

4. 權限聲明。讀取 SIM 信息需要 READ_PHONE_STATE 權限,在 Android 6.0 及以上還屬於運行時權限,需要動態申請。

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