1. 程式人生 > >Android 官方DEMO BasicNetworking

Android 官方DEMO BasicNetworking

如果 info span develop else if gets spa .com evel

本示例演示如何使用Android API檢查網絡連接。

Demo下載地址:https://github.com/googlesamples/android-BasicNetworking/#readme

相關API:https://developer.android.google.cn/reference/android/net/ConnectivityManager.html

利用ConnectivityManager來檢查是否已經連接網絡,如果已經連接,判斷網絡類型。通過ConnectivityManager.getActiveNetworkInfo()方法獲取NetworkInfo對象,可獲取網絡狀態信息。

關鍵代碼:

/**
 * 檢查網絡是否已經連接,如果已連接,判斷是否WIFI狀態或其他網絡類型。
 */
private void checkNetworkConnection() {
    ConnectivityManager connMgr =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
    if (activeInfo != null && activeInfo.isConnected()) {
        wifiConnected 
= activeInfo.getType() == ConnectivityManager.TYPE_WIFI; mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE; if(wifiConnected) { Log.i(TAG, getString(R.string.wifi_connection)); } else if (mobileConnected){ Log.i(TAG, getString(R.string.mobile_connection));
} } else { Log.i(TAG, getString(R.string.no_wifi_or_mobile)); } }

Android 官方DEMO BasicNetworking