如何检查网络可用性? [英] How to check the network availability?

查看:149
本文介绍了如何检查网络可用性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用两种无线服务器连接我的应用程序(如果可用), 或GPRS(如果无线网络不可用)。 这是我的code检查连接的可用性

I have to connect my app with server using either wifi (if it is available), or gprs (if wifi is not available). Here is my code to check the connection availability

public static final boolean isConnectionAvailable(Activity a)
{  

  ConnectivityManager cm = (ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE);

  State mobile = cm.getNetworkInfo(0).getState();

  State wifi = cm.getNetworkInfo(1).getState();

  if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
    {
        return true;
    }
  if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
    {
        return true;
    }

   return false;
}      

这是一个正确的方法是什么?任何人都可以给我建议一个更好的办法?

Is this a correct way? Can anyone suggest me a better way?

推荐答案

下面的非常相似的方式工作,但不关心什么底层介质的额外的好处,因为它看起来好像有更多的不仅仅是WiFi的支持。也许这些也包括在移动,但该文档是不是超级清楚的:

The following very similar approach works, but has the added advantage of not caring what the underlying medium, since it looks as though there is support for more than just WiFi. Maybe these are also covered by mobile, but the docs aren't super clear:

// added as an instance method to an Activity
boolean isNetworkConnectionAvailable() {  
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();     
    if (info == null) return false;
    State network = info.getState();
    return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);
}     

这篇关于如何检查网络可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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