![](/img/trans.png)
[英]how to determine, if an internet connection is currently available and active on an android device?
[英]android: how to know internet connection is available or not in device?
我想檢查設備中的互聯網連接是否可用,所以我該如何獲取..請為此提供代碼。
非常感謝
嘿,伙計...應用此代碼..可能對提前感謝您很有幫助....
布爾連接;
private boolean checkInternetConnection()
{
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
ConnectivityManager connectionService =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (connectionService.getActiveNetworkInfo().isConnectedOrConnecting()) {
// Device is online
}
// Network is connected or not
public boolean isConnected()
{
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
Log.d("LOG","Network is Available");
return true;
}
}
return false;
}
請使用以下功能為了檢查互聯網連接:
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
boolean result = false;
if(ni != null )
{
if( ni.getState() == NetworkInfo.State.CONNECTED )
{
result = true;
}
}
return result;
}
檢查isOnline()返回的結果。如果為true,則說明已連接Internet,否則未連接Inernet 。 希望這個能對您有所幫助..:)
使用此Answer It的幫助。
public boolean isOnline() {
ConnectivityManager cm =(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
if(temp==true){
genHelper.showToast("Net Connection");
}else{
genHelper.showToast(" Not Connected");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.