First add permissions in Androidmanifest.xml
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
1. Determine if there is an Internet connection
public Boolean isnetworkconnected (context context) { if (context! = null) { Connectivitymanager Mconnectivitymanager = (connectivitymanager) context . Getsystemservice (context.connectivity_service); Networkinfo mnetworkinfo = Mconnectivitymanager.getactivenetworkinfo (); if (mnetworkinfo! = null) { return mnetworkinfo.isavailable ();} } return false; }
2. Determine if the WiFi network is available
public Boolean iswificonnected (context context) { if (context! = null) { Connectivitymanager Mconnectivitymanager = (connectivitymanager) context . Getsystemservice (context.connectivity_service); Networkinfo mwifinetworkinfo = Mconnectivitymanager . Getnetworkinfo (Connectivitymanager.type_wifi); if (mwifinetworkinfo! = null) { return mwifinetworkinfo.isavailable ();} } return false; }
3. Determine if the mobile network is available
public Boolean ismobileconnected (context context) { if (context! = null) { Connectivitymanager Mconnectivitymanager = (connectivitymanager) context . Getsystemservice (context.connectivity_service); Networkinfo mmobilenetworkinfo = Mconnectivitymanager . Getnetworkinfo (connectivitymanager.type_mobile); if (mmobilenetworkinfo! = null) { return mmobilenetworkinfo.isavailable ();} } return false; }
4. Determine the network type
return value-1: No network 1:wifi Network 2:WAP Network 3:net Network public static int Getnetype (context context) { int netType = -1;< C5/>connectivitymanager connmgr = (connectivitymanager) context.getsystemservice (context.connectivity_service); Networkinfo networkinfo = Connmgr.getactivenetworkinfo (); if (networkinfo==null) { return netType; } int nType = Networkinfo.gettype (); if (ntype==connectivitymanager.type_mobile) { if (Networkinfo.getextrainfo (). toLowerCase (). Equals (" Cmnet ")) { netType = 3; } else { netType = 2; } } else if (Ntype==connectivitymanager.type_wifi) { netType = 1; } return netType; }
Android to get network status