如何检查我的应用是否已连接到互联网?
我找到了这篇文章,但似乎你只能检查连接是否可用。 Detect whether there is an Internet connection available on Android
那个帖子确实有正确的答案,我离我的wifi太远了,总是不及测试。问题解决了。
我希望能够检查这样的事情:
if(!isConnectedToInternet())
{
Toast.makeText(getApplicationContext(), "Please connect to the internet.",
Toast.LENGTH_LONG).show();
}
答案 0 :(得分:1)
尝试像这样检查:
private boolean isConnectedToInternet() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
在这里查看:
if(!isConnectedToInternet())
{
Toast.makeText(getApplicationContext(), "Please connect to the internet.",
Toast.LENGTH_LONG).show();
}
答案 1 :(得分:1)
检查此代码对我来说没问题
public boolean isConnectingToInternet() {
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) {
return true;
}
}
return false;
}
像这样检查
boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
} else {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.internet_error),
Toast.LENGTH_LONG).show();
}
答案 2 :(得分:1)
answer from the link you attached实际上与您要实现的目标几乎相同。你只需修改几行:
private boolean isConnectedToInternet() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork= connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
您可以查看Android中的documentation & guides
答案 3 :(得分:0)
您需要检查是否存在已建立的连接
private boolean isConnected() {
ConnectivityManager cm
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected() && cm.requestRouteToHost(activeNetworkInfo.getType(), yourHostAddress);
}
然后检查是否有到您想要的主机的路由(您可以使用Google进行测试)。检查http://developer.android.com/reference/android/net/ConnectivityManager.html#requestRouteToHost(int,int)
希望它有所帮助。