This example demonstrates how to use the Android API to check network connectivity.
Demo download address: https://github.com/googlesamples/android-BasicNetworking/#readme
相关API:https://developer.android.google.cn/reference/android/net/ConnectivityManager.html
Use ConnectivityManager to check whether the network has been connected, and if so, determine the network type. Obtain the NetworkInfo object through the ConnectivityManager.getActiveNetworkInfo() method to obtain network status information.
Key code:
/** * Check whether the network is connected, if connected, determine whether it is WIFI status or other network types. */ 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)); } }