[小代码]判断网络是否可用

来源:互联网 发布:大图打印 软件 编辑:程序博客网 时间:2024/06/16 13:24

可以两种方法:

/*   *@当网络可以时返回TRUE*/    private boolean haveInternet(){         NetworkInfo info=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();         if(info==null || !info.isConnected()){             return false;         }         if(info.isRoaming()){             return true;         }         return true;     }
另一种:

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;     }



原创粉丝点击