如何检查当前的网络连接是否可用在安卓 [英] How to check currently internet connection is available or not in android
问题描述
我想我的应用程序脱机也执行了,所以我需要检查,如果当前的网络连接是否可用。谁能告诉我如何检查网络是否可用在安卓?提供样品code。我试着用code以下和使用模拟器检查,但是它不工作
I want to execute my application offline also, so I need to check if currently an internet connection is available or not. Can anybody tell me how to check if internet is available or not in android? Give sample code. I tried with the code below and checked using an emulator but it's not working
public boolean isInternetConnection()
{
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
}
感谢
推荐答案
这将告诉我们,如果你连接到网络:
This will tell if you're connected to a network:
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
警告:如果您已连接到WiFi网络,不包括网络连接或需要基于浏览器的验证,连接
还是会是真实的。
Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected
will still be true.
您需要这个权限在你的清单:
You will need this permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
这篇关于如何检查当前的网络连接是否可用在安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!