你如何检查android中的互联网连接? [英] How do you check the internet connection in android?
问题描述
我想检查每个活动中的互联网连接.如果丢失,应显示一条消息.
I want to check the internet connectivity in each activity. If it is lost a message should be displayed.
谁能指导我如何实现这一目标?
Can any one guide me how to achieve this?
推荐答案
您可以使用 ConnectivityManager 检查网络状态.
You can use the ConnectivityManager to check the network state.
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ) {
// notify user you are online
}
else if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED
|| conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {
// notify user you are not online
}
请注意,常量 ConnectivityManager.TYPE_MOBILE 和 ConnectivityManager.TYPE_WIFI 表示连接类型,这两个值并不详尽.请参阅此处获取详尽列表.
Note that the constants ConnectivityManager.TYPE_MOBILE and ConnectivityManager.TYPE_WIFI represent connection types and these two values are not exhaustive. See here for an exhaustive list.
还要确保您拥有监控网络状态所需的权限.您需要将此权限添加到您的 AndroidManifest.xml 中:
Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
这篇关于你如何检查android中的互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!