Android Detects network connection status

Source: Internet
Author: User

When the Android app needs to connect to the network, it does not connect to the network every time, so the program needs to detect the current device's network status in order to alert the user in a timely manner.

To determine the status of the network, you need to have the appropriate permission code as follows (Androidmanifest.xml):

?
12 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"><uses-permission android:name="android.permission.INTERNET"></uses-permission></uses-permission>


Code to detect the current network status:

?
12345678910111213141516 public void checkNetworkState(Context context){    if (context != null) {        ConnectivityManager mConnectivityManager = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();        //1.判断是否有网络连接         boolean networkAvailable = networkInfo.isAvailable();        //2.获取当前网络连接的类型信息        int networkType = networkInfo.getType();        if(ConnectivityManager.TYPE_WIFI == networkType){            //当前为wifi网络        }else if(ConnectivityManager.TYPE_MOBILE == networkType){            //当前为mobile网络        }    }}

A companion tour, a free dating site: www.jieberu.com

Push family, free tickets, scenic spots: www.tuituizu.com

Android Detects network connection status

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.