How to check if internet is available or not in app startup in android?

前端 未结 3 1380
梦如初夏
梦如初夏 2021-02-09 10:11

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

  1. I will like to check if any forms of internet
相关标签:
3条回答
  • 2021-02-09 10:46

    You can use my method:

    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;
    }
    
    0 讨论(0)
  • 2021-02-09 10:55

    You can do all this using ConnectivityManager. All the required info is available here

    http://developer.android.com/reference/android/net/ConnectivityManager.html

    You probably want to stick something like this in the onStart() method of your initial activity (depending on where in your code the connection is fired up and the data is downloaded)

    ConnectivityManager cm =  (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
    if (cm.getAllNetworkInfo().isConnected()) {
     //proceed with loading 
    } else { 
    //showErrorDialog 
    }
    

    I haven't tested te code so cutting and pasting is probably a bad idea, but this should give you a good starting point. There is plenty of other info if you check the docs.

    Also it's might be an idea to handle the lack of connectivity by changing your code so it doesn't just crash if there is no connection, pre haps show a default loading screen? Also your app may fail to get data even if there is a connection available, so you'll want to handle that scenario too.

    0 讨论(0)
  • 2021-02-09 11:06
    NetworkInfo i = conMgr.getActiveNetworkInfo();
      if (i == null)
        return false;
      if (!i.isConnected())
        return false;
      if (!i.isAvailable())
        return false;
      return true;
    
    0 讨论(0)
提交回复
热议问题