This example demonstrates how to use the Android API to check for network connections.
demo:https://github.com/googlesamples/android-basicnetworking/#readme
Related api:https://developer.android.google.cn/reference/android/net/connectivitymanager.html
Use Connectivitymanager to check if the network is connected, and if so, determine the network type. Gets the Networkinfo object through the Connectivitymanager.getactivenetworkinfo () method to obtain network state information.
Key code:
/** * Check if the network is connected,If connected, determine if WiFi status or other network type.*/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 Official Demo Basicnetworking