我正在使用此代码:
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
但它总是返回true。谁能告诉我为什么?此外,此功能检查设备是使用wifi还是3g连接,还是仅检查其中一个?
答案 0 :(得分:1)
尝试这种方法,适合我
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null)
return activeNetworkInfo.isConnected();
return false;
}
答案 1 :(得分:0)
使用此代码并检查您的权限。有时也可能导致问题。抱歉格式化。
public final boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
// MESSAGE TO SCREEN FOR TESTING (IF REQ)
//Toast.makeText(this, connectionType + ” connected”, Toast.LENGTH_SHORT).show();
return true;
} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {
//System.out.println(“Not Connected”);
return false;
}
return false;
}
以下代码演示了如何调用上述方法;
if(isInternetOn()) {
// INTERNET IS AVAILABLE, DO STUFF..
return true;
}else{
// NO INTERNET AVAILABLE, DO STUFF..
return false;
}
答案 2 :(得分:0)
我用它,它允许我检查一个特定的连接(3g或wifi)(在SO上找到但丢失了参考,对不起)
public boolean isConnected() {
boolean connectedWifi = false;
boolean connectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networks = cm.getAllNetworkInfo();
for (NetworkInfo ni : networks) {
if ("WIFI".equalsIgnoreCase(ni.getTypeName()))
if (ni.isConnected())
connectedWifi = true;
if ("MOBILE".equalsIgnoreCase(ni.getTypeName()))
if (ni.isConnected())
connectedMobile = true;
}
return connectedWifi || connectedMobile;
}
答案 3 :(得分:0)
如果你想知道你的Android设备是否连接到任何网络,那么你可以按照其他人告诉你的方法。
但是如果你想知道互联网是否有效,那么android中没有API来检查它。了解互联网是否正常工作的唯一方法是检查我向任何网址发送http请求。
答案 4 :(得分:-1)
以下代码适用于我
public static boolean haveNetworkConnection(Activity activity) {
int airplane_mode_on = Settings.System.getInt(activity
.getApplicationContext().getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0);
if (airplane_mode_on == 1) {
return false;
} else {
return checkInternetConnection(activity);
}
}
private static boolean checkInternetConnection(Context context) {
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}