編輯:進階開發
由於筆者目前任職於電信業,僅專注於電信業務,因此以下程式碼中的 APN 清單也只涵蓋電信的資訊。
首先,我們把電信的 APN 類型定義成一個常數類別,方便後續判斷使用:
/**
* 電信 APN 列表
*/
public class APNNET {
public static String CTWAP = "ctwap";
public static String CTNET = "ctnet";
}
接著,透過查詢系統的設定資料庫,判斷目前的 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 的設定來配置網絡代理:
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 連線的代理,讓應用得以在代理環境下正常連網。
動手做一個 Android 貪食蛇:自訂 View 的繪製與刷新邏輯全解析
本文聚焦在 Android 的 UI 實作上,以經典的 Snake 貪食蛇專案為例,把自訂 View 的初始化、繪製與刷新機制講清楚。基本的操作這裡不多贅述,直接進主題。
新奇解讀:Nexus One背後的Android佈局
對許多Android手機的忠實愛好者而言,Android的問世彌補了他們心裡的那塊缺角。而對整個手機市場來說,它的出現等於多了一名重量級對手,連微軟與諾基亞這幾家一線廠商
解讀Android 2.0的多重難題:支付、功能缺口與應用商店
Android 2.0系統要在國內落地,面臨不少問題,其中最棘手的是支付環節。易聯致遠CTO姚尚朗表示,開發者與用戶都期待更多元的支付平台。 從1.6到2.0的規格演進
細談 Android 手機系統:Widget 更新排程裡那些容易踩到的坑
先把最基本的概念釐清:Android 包含一組由系統中各種不同元件共同使用的 C/C++ 函式庫集,這也是它效能表現的重要基礎之一。 為什麼不能靠 updatePeri