Android 判断是否有网络

首先需要添加权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

判断是否有网络的代码:

public boolean isNetworkAvailable() {
        Context context = getApplicationContext();
        ConnectivityManager connect = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connect == null) {
            return false;
        } else {// get all network info
            NetworkInfo[] info = connect.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

或者

    public boolean isNetworkAvailable() {
        Context context = getApplicationContext();
        ConnectivityManager connect = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connect == null) {
            return false;
        } else {
            return connect.getActiveNetworkInfo().isAvailable();
        }
    }

 

 

posted on 2013-02-28 09:14  program_lover  阅读(202)  评论(0编辑  收藏  举报

导航