如何检查网络是否可用在应用程序启动时的Andr​​oid?

如何检查网络是否可用在应用程序启动时的Andr​​oid?

问题描述:

我在第一次加载的应用程序从互联网DATAS(我使用web服务) 我要检查在应用程序启动网络连接。

My app at first loads the datas from internet(I am using webservice) I want to check internet access at app startup.

  1. 我会想检查互联网3G或者WIFI或GPRS或其他任何形式的可用与否。
  2. 如果不可用,给信息给用户,如您需要上网和退出程序。 (目前,我得到强制关闭错误在我的应用程序,如果没有互联网接入)
  3. 如果速效,正常启动我的应用程序。
  4. 另外,我的应用程序是取的DATAS从web服务在不同的阶段,每个阶段或操作之前,我会想检查网络连接在第一。
  1. I will like to check if any forms of internet either 3G or WIFI or GPRS or any other is available or not.
  2. If not available, give message to user like "You need internet access" and exit the app. (Currently i am getting force close error in my app if there is no internet access)
  3. If availabe, start my app normally.
  4. Also, my app is fetches the datas from webservice at different phase, before each phase or operation, i will like to check internet access at first.

我该怎么办呢?

您可以用我的方法:

public static boolean isNetworkAvailable(Context context) 
{
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null) 
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();

        if (info != null) 
        {
            for (int i = 0; i < info.length; i++) 
            {
                Log.i("Class", info[i].getState().toString());
                if (info[i].getState() == NetworkInfo.State.CONNECTED) 
                {
                    return true;
                }
            }
        }
    }
    return false;
}