Android determines whether the current android device is online.

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.