復制代碼 代碼如下:
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"/>