Android 官方DEMO BasicNetworking

本示例演示如何使用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));
    }
}