可能重複:
Android - detect whether there is an Internet connection available
How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?如何檢查在Android手機的網絡連接
在我的手機,當我跑我的應用程序,然後這個應用程序崩潰,因爲網絡連接不那麼如何傳達這樣的信息,即連接不存在。或您的WIF
請幫我
謝謝
可能重複:
Android - detect whether there is an Internet connection available
How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?如何檢查在Android手機的網絡連接
在我的手機,當我跑我的應用程序,然後這個應用程序崩潰,因爲網絡連接不那麼如何傳達這樣的信息,即連接不存在。或您的WIF
請幫我
謝謝
請參見下面的代碼。
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
// internet connection is wroking
} else {
return false;
// internet connection is not wroking
}
使用此方法在你的活動,當你想知道網絡是否可用不叫這個。
public boolean isInternetOn(Context ctx) {
this.mContext = ctx;
ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
State connected = NetworkInfo.State.CONNECTED;
State connecting = NetworkInfo.State.CONNECTING;
State disconnected = NetworkInfo.State.DISCONNECTED;
State info0 = Connect_Manager.getNetworkInfo(0).getState();
State info1 = Connect_Manager.getNetworkInfo(1).getState();
// ARE WE CONNECTED TO THE NET
if (info0 == connected || info0 == connecting || info1 == connecting
|| info1 == connected) {
// MESSAGE TO SCREEN FOR TESTING (IF REQ)
// Toast.makeText(this, connectionType + " connected",
// Toast.LENGTH_SHORT).show();
Log.d("Internet", "Connected");
return true;
} else if (info0 == disconnected || info1 == disconnected) {
Log.d("Internet", "DisConnected");
// System.out.println("Not Connected");
return false;
}
return false;
}
現在檢查互聯網Conncetion,
if (isInternetOn(this))
{
//Do stuff
}
else
{
//show alert
}
檢查相關問題。 – Shoban 2011-12-29 07:33:37
網上有很多相同的例子:** Android檢查網絡連接** – 2011-12-29 07:36:05