1. 程式人生 > >Android中判斷有無可用網路(是否是3G或者WIFI網路)

Android中判斷有無可用網路(是否是3G或者WIFI網路)

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"/>