0
点赞
收藏
分享

微信扫一扫

Android 开发系列7 判断上网方式(Wifi还是数据流量)

首先要在AndroidManifest.xml加上权限:

 

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

判断有无网络连接:

 

 

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;
}

检查网络类型:

 

 

int netType = info.getType(); 
int netSubtype = info.getSubtype();

if (netType == ConnectivityManager.TYPE_WIFI) { //WIFI
return info.isConnected();
} else if (netType == ConnectivityManager.TYPE_MOBILE && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) { //MOBILE
return info.isConnected();
} else {
return false;
}

 

 

 

 

 

判断WiFi是否已连接:

 

/**
* make true current connect service is wifi
* @param mContext
* @return
*/
private static boolean isWifi(Context mContext) {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}

判断WiFi和移动流量是否已连接:

 

 

public static boolean checkNetworkConnection(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if(wifi.isAvailable()||mobile.isAvailable()) //getState()方法是查询是否连接了数据网络
return true;
else
return false;
}

 

 

 

 

 

只判断移动网络连接是否正常:

 

<span style="font-family: Arial, Helvetica, sans-serif;">public boolean isMobileConnected(Context context) {  
</span><span style="font-family: Arial, Helvetica, sans-serif;"> if (context != null) { </span>
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); //获取移动网络信息
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable(); //getState()方法是查询是否连接了数据网络
}
}
return false;
}

 

 

 

 

 


举报

相关推荐

0 条评论