首页 > 系统 > Android > 正文

Android中判断有无可用网络的代码(是否是3G或者WIFI网络)

2019-10-24 21:06:27
字体:
来源:转载
供稿:网友
在android开发中经常会遇到的判断有无可用网络的代码,防止客户流量损失
 
复制代码代码如下:

ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
TelephonyManager mTelephony = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE); 
//检查网络连接,如果无网络可用,就不需要进行连网操作等 
NetworkInfo info = mConnectivity.getActiveNetworkInfo(); 

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


//判断网络连接类型,只有在3G或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; 

别忘了在 AndroidManifest.xml 中加上 检查网络的权限 

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表