Browse » Home » Resource, Tips » Blog article: 检测当前网络环境的方法

通过下列代码可以检测当前手机所在区域是否存在可用网络,在操作代码之前首先在Manifest中声明使用用户的 android.permission.ACCESS_NETWORK_STATE许可。

函数代码:

public boolean isNetworkAvailable() {
   Context context = getApplicationContext();
   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity == null) {
      boitealerte(this.getString(R.string.alert),"getSystemService rend null");
   } else {
      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;
}

ConnectivityManager : 用来管理当前网络连通状态。
NetworkInfo:装载网络状态对象的类。

文章来源:Android Snippets

Tags: , ,

Posted in Resource, Tips |

Related Posts

One Response to “检测当前网络环境的方法”


给程序添加一个控制WIFI的Switcher | Android Resource | 资源 资讯 教程 October 22nd, 2009 at 1:10 am

[...] 作为手机平台应用最广泛的一种无限网络协议(中国受限),其在地球上的覆盖面积达到了惊人的程度(结论凭主观判断,目前还没有确切的数据来源)。此前有文章讨论“如何检测当前区域内可用的网络资源?” ,下面将围绕网络应用的话题介绍与WIFI应用开发的一些方法。 [...]



Leave a Reply

You must be logged in to post a comment.