如何检查网络是否可用在应用程序启动时的Andr​​oid? [英] How to check if internet is available or not in app startup in android?

查看:114
本文介绍了如何检查网络是否可用在应用程序启动时的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;
}

这篇关于如何检查网络是否可用在应用程序启动时的Andr​​oid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆