Learn Android together how to get the network type and determine if it is available (20)

Source: Internet
Author: User

Connectivitymanager main management and network connection related operations , Obtained by Getsystemservice (Context.connectivity_service)


Services that take the network connection. so we can pass Connectivitymanager the getactivenetworkinfo () method under this class to get the current network


connection state, this method returns the Networkinfo Object , Networkinfo describes the current network mobile and WiFi the state. the networkinfo class has


three methods: ( 1 ) GetType () gets the type of the current network, such as Mobileor Wi-Fi . (2)gettypename () Gets the type of the current network


names, such as "WIFI" or "MOBILE". (3) Theisavailable () method is used to determine whether the current network connection is available, returns true, and returns false .


For information on how to view the current network type, see the following code:


Public  String Getnetworkstatename (context context) {    Connectivitymanager Mconnectivitymanager = ( Connectivitymanager) Context.getsystemservice (Context.connectivity_service); Networkinfo mnetworkinfo = Mconnectivitymanager.getactivenetworkinfo (), if (mnetworkinfo.isavailable ()) {//Get network type int Networktype =mnetworkinfo.gettype (); if (Networktype==connectivitymanager.type_wifi) {return "current network is WiFi";} else if (networktype==connectivitymanager.type_mobile) {return "current network is 3G";} else{return "other means";}} Else{return "currently no Network";}        }


Finally, add access permissions in the androidmainfest file:

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>



Reprint Please specify source:http://blog.csdn.net/hai_qing_xu_kong/article/details/44057903 Emotional Control _

Learn Android together how to get the network type and determine if it is available (20)

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.