我正在尝试构建一个应用程序,我首先需要检查互联网连接是否可用,即使它连接到没有互联网连接的WIFI路由器?从我知道的来源,为了检查这个,我需要ping网站,例如(www.google.com)。请帮我提供我需要包含的确切片段? 谢谢
答案 0 :(得分:0)
这种方法适合我
public final boolean isInternetOn() {
// get Connectivity Manager object to check connection
ConnectivityManager connec =
(ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connections
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) {
// if connected with internet
// Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
return true;
} else if (
connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
// Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
return false;
}
return false;
}
答案 1 :(得分:0)
试试这个:
public static boolean hasInternet(Context context) {
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}