检查android中可用的网络

时间:2013-04-30 07:35:47

标签: java android networking connectivity

我必须开发一个Android应用程序。

这里我要开发一个twitter集成android应用程序。

我使用下面的代码:

public void onClickTwitt() {
    if (isNetworkAvailable()) {
        Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key);
        twitt.shareToTwitter(_Title);
    } else {
        showToast("No Network Connection Available !!!");
    }
}
public boolean isNetworkAvailable() {
     ConnectivityManager connectivity =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity == null) {
        return false;
    } 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;
}

这里得到以下错误:

The method getSystemService(String) is undefined for the type 
 SubCate

请帮帮我......我怎样才能解决这些错误????

2 个答案:

答案 0 :(得分:6)

 public static  boolean isNetworkAvailable(Context context) {
    if(context == null) { return false; }
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    // if no network is available networkInfo will be null, otherwise check if we are connected
    try {
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            return true;
        }
    } catch (Exception e) {
        AppLog.e(TAG, "isNetworkAvailable()" , e.getMessage());
    }
    return false;
}

然后执行此操作

if(isNetworkAvailable(TempOrderActivity.this)) {
                //do something

            } else {
                //do something
            }

答案 1 :(得分:4)

public void onClickTwitt() {
    if (isNetworkAvailable(this)) {
        Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key);
        twitt.shareToTwitter(_Title);
    } else {
        showToast("No Network Connection Available !!!");
    }
}
public boolean isNetworkAvailable(Context context) {
     ConnectivityManager connectivity =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity == null) {
        return false;
    } 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;
}