Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android APN 設定與手機號碼獲取實作

編輯:進階開發

由於筆者目前任職於電信業,僅專注於電信業務,因此以下程式碼中的 APN 清單也只涵蓋電信的資訊。

定義電信 APN 清單

首先,我們把電信的 APN 類型定義成一個常數類別,方便後續判斷使用:

/**
 * 電信 APN 列表
 */
public class APNNET {
    public static String CTWAP = "ctwap";
    public static String CTNET = "ctnet";
}

取得 APN 類型

接著,透過查詢系統的設定資料庫,判斷目前的 APN 屬於哪一種類型:

/**
 * 獲得 APN 類型
 */
public class ApnUtil {
    private static Uri PREFERRED_APN_URI = Uri
            .parse("content://telephony/carriers/preferapn");

    /**
     * get apntype
     */
    public static String getApnType(Context context) {
        String apntype = "nomatch";
        Cursor c = context.getContentResolver().query(PREFERRED_APN_URI,
                null, null, null, null);
        c.moveToFirst();
        String user = c.getString(c.getColumnIndex("user"));
        if (user.startsWith(APNNET.CTNET)) {
            apntype = APNNET.CTNET;
        } else if (user.startsWith(APNNET.CTWAP)) {
            apntype = APNNET.CTWAP;
        }
        return apntype;
    }
}

至於取得手機號碼的部分,做法是將 IMSI 碼傳送到指定的介面。基於某些原因,這個介面的位址不便公開,但這裡可以透露一個關鍵:整個流程必須走 CTWAP,這也正是我們要先判斷 APN 類型的原因所在。

設定 APN 的代理資訊

筆者發現,許多應用一旦 APN 走代理連線便無法連網,因此這裡順道說明一下如何依 APN 的設定來配置網絡代理:

Cursor c = context.getContentResolver().query(PREFERRED_APN_URI,
        null, null, null, null);
c.moveToFirst();
String proxy = c.getString(c.getColumnIndex("proxy"));
if (!"".equals(proxy) && proxy != null) {
    Properties prop = System.getProperties();
    System.getProperties().put("proxySet", "true");
    prop.setProperty("http.proxyHost", c.getString(c.getColumnIndex("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.encode(authentication);
    uc.setRequestProperty("Proxy-Authorization", " Basic " + encodedLogin);
}
c.close();

透過這段邏輯,程式便能讀取系統 APN 的代理主機、連接埠與認證資訊,並據此設定 HTTP 連線的代理,讓應用得以在代理環境下正常連網。

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