Android to determine if there is any available network code (whether 3G or WiFi network) _android

Source: Internet
Author: User
Copy code code as follows:

Connectivitymanager mconnectivity = (connectivitymanager) getsystemservice (Context.connectivity_service);
Telephonymanager mtelephony = (telephonymanager) this.getsystemservice (Telephony_service);
Check network connection, if no network is available, do not need to do networking operations, etc.
Networkinfo info = Mconnectivity.getactivenetworkinfo ();

if (info = null | |!mconnectivity.getbackgrounddatasetting ()) {
return false;
}

To determine the type of network connection, only some data updates are made in 3G or WiFi.
int nettype = Info.gettype ();
int netsubtype = Info.getsubtype ();

if (NetType = = Connectivitymanager.type_wifi) {
return info.isconnected ();
else if (NetType = Connectivitymanager.type_mobile
&& Netsubtype = = Telephonymanager.network_type_umts
&&!mtelephony.isnetworkroaming ()) {
return info.isconnected ();
} else {
return false;
}

Don't forget to add a check to the Androidmanifest.xml network permissions

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

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.