如何检查在Android上的互联网连接? [英] How do you check the internet connection in android?

查看:139
本文介绍了如何检查在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(0).getState() == NetworkInfo.State.CONNECTED 
    || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ) {

    // notify user you are online

}
else if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED 
    || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

    // notify user you are not online
}

请注意,该常数0和1重新present连接类型和这两个值并不详尽。请参见这里一个详尽的清单。

Note that the constants 0 and 1 represent connection types and these two values are not exhaustive. See here for an exhaustive list.

另外,还要确保你有监控网络状态所需的权限。你需要这个权限添加到您的Andr​​oidManifest.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆