在寫App時,一定多少都會用到網路,但如果沒有做網路連線的判斷,會造成App強制關閉

需先加入Manifest加入權限

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

Java:

//先取得此CONNECTIVITY_SERVICE
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
//取得網路相關資訊
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();

//判斷是否有網路
if (networkInfo == null || !networkInfo.isConnected()){ 
	Log.i("INFO","沒網路");
}
else {
	Log.i("INFO","有網路");
}
Categories: Android