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

前端 未结 3 1381
梦如初夏
梦如初夏 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;
    }
    

提交回复
热议问题