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

Android 判斷網絡是否可用的標準寫法

編輯:關於 Android 程式設計

幾乎每個需要聯網的 App 都得先問一句「現在有網嗎」。Android 提供了 ConnectivityManager 來查詢連接狀態,封裝成一個工具類會更順手。

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity =
                (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

調用方式:

ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet();

記得在清單文件中加入 android.permission.ACCESS_NETWORK_STATE 權限,否則 getSystemService 拿到的對象會受限。

另外要提醒的是,這種判斷只能確認「有網絡接口連着」,並不能保證真的能上網(比如連上了沒有認證的 WiFi、或者需要網頁登入的熱點)。如果要更可靠,可以在判斷之後發一個輕量的 HEAD 請求探活。

感謝閱讀,希望能幫助到大家。

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