Android determines whether the current android device is online.
First, to determine whether the current android device is online, android itself provides us with a service
Private ConnectivityManager connectivityManager; // used to determine whether there is a network connectivityManager = (ConnectivityManager) getActivity (). getSystemService (Context. CONNECTIVITY_SERVICE); // gets the network connection service NetworkInfo info = connectivityManager. getActiveNetworkInfo (); // gets the active network connection information
First, we need to obtain the android Network Service and add a permission to the configuration file.
<! -- Get information about whether your mobile phone is connected to the Internet --> <uses-permission android: name = "android. permission. ACCESS_NETWORK_STATE"/>
Then we get the system service through Context. getSystemService (Context. CONNECTIVITY_SERVICE ).
Then we use the NetworkInfo class provided by android to store the network service information returned by the system.
If (info = null) {// There is no activated network connection currently (indicating that the data traffic service is disabled or other data services such as WiFi are not enabled) Toast. makeText (getActivity (), "check whether the network connection is enabled", Toast. LENGTH_SHORT ). show ();} else {// There are currently activated Network Connections}
Of course, we can also use this code to determine whether our network connection is available.
// To return whether it is valid. If it is True, it indicates that the current Android mobile phone is connected to the Internet, which may be WiFi, GPRS, HSDPA, etc. You can use the getActiveNetworkInfo () method of the ConnectivityManager class to determine the detailed access method connectivityManager. getActiveNetworkInfo (). isAvailable ();