The code of in Android determines whether there is a 3G or WIFI network with no network available

  • 2020-05-09 19:14:42
  • OfStack

 
ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
TelephonyManager mTelephony = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE); 
// Check the network connection, if there is no network available, there is no need to connect  
NetworkInfo info = mConnectivity.getActiveNetworkInfo(); 

if (info == null || !mConnectivity.getBackgroundDataSetting()) { 
return false; 
} 

// Determine the network connection type only in 3G or wifi in 1 Some data updates.  
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 include network check permissions in AndroidManifest.xml

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

Related articles: