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

Android 網路訪問代理的判斷與實現

編輯:關於 Android 程式設計

在 Android 網路開發中,我們往往需要判斷當前的網路連接方式是 WiFi 還是 WAP。若是 WAP,則需要透過代理來訪問網路。本文將說明其中的原理與實現方法。

為什麼 WAP 需要使用代理訪問?

WAP 只是一種 GPRS 應用模式,它與 GPRS 的接入方式無關。WAP 應用採用「終端 + WAP 網關 + WAP 伺服器」的模式,有別於一般網際網路的「終端 + 伺服器」工作模式。其主要目的是透過 WAP 網關完成 WAP-WEB 的協議轉換,以達到節省網路流量並相容現有 WEB 應用的目的。正因存在這樣的網關轉換,WAP 網路環境下才需要設定代理才能正常訪問。

實現方法

透過 ConnectivityManager 判斷當前活躍網路的類型:若是 WiFi 則無需代理;若是 MOBILE(行動網路),則嘗試從系統取得代理主機與埠,若存在則需要透過代理訪問:

private boolean isNeedProxy(final Context context) {

boolean ret = false;

final ConnectivityManager connectManager = (ConnectivityManager)

context.getSystemService(Context.CONNECTIVITY_SERVICE);

final NetworkInfo activeNetInfo = connectManager.getActiveNetworkInfo();

if (activeNetInfo != null) {

final String type = activeNetInfo.getTypeName();

if (type.equalsIgnoreCase("WIFI")) {

ret = false;

} else if (type.equalsIgnoreCase("MOBILE")) {

final String mobileProxyIp = android.net.Proxy.getHost(context);

final int mobileProxyPort = android.net.Proxy.getPort(context);

if (mobileProxyIp == null || "".equals(mobileProxyIp) || mobileProxyPort == 0) {

ret = false;

} else {

hostUrl = mobileProxyIp;

hostPort = mobileProxyPort;

ret = true;

}

}

}

return ret;

}

透過以上邏輯,應用即可根據當前網路環境自動判斷是否需要走代理,從而確保在 WAP 網路下也能正確訪問網路資源。

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