这是我的 class ,检查设备是否连接到互联网 .
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000);
urlc.setReadTimeout(4000);
urlc.connect();
// networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return (false);
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
然后我在这里称它但它似乎没有返回真或假 . 没有错误,我的应用程序没有崩溃它只是没有打印任何东西 . 谁知道为什么?
public void CheckInternet(){
// Boolean isInternetPresent;
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// isInternetPresent = cd.isConnectingToInternet();
if (cd.isConnectingToInternet()) {
// Internet Connection is Present
Log.i(TAG, "INTERNET IS GUUD");
} else {
// Internet connection is not present
// Ask user to connect to Internet
Log.i(TAG, "INTERNET IS NOOOO GUUD");
}
}
4 回答
创建一个类:
然后从活动中调用methode,它将返回true或false:
并且不要忘记为android清单添加权限
这不是ConnectivityManager为此 Build 的ConnectivityManager类 .
它使用起来非常简单,您只需执行以下操作即可检查网络连接:
这还可以让您确定连接类型,监控等等,以便您可以对正在执行的网络任务做出明智的决策 .
Android开发者网站上的this lesson中有更多信息 .
你必须在asynctask中做到这一点 . 我使用http://clients3.google.com/generate_204来检测连接 .
叫这个功能: