How to check currently internet connection is available or not in android

前端 未结 18 1448
轮回少年
轮回少年 2020-12-04 15:40

I want to execute my application offline also, so I need to check if currently an internet connection is available or not. Can anybody tell me how to check if internet is av

18条回答
  •  星月不相逢
    2020-12-04 16:06

    Use the method checkConnectivity:

      if (checkConnectivity()){
        //do something 
    
        }
    

    Method to check your connectivity:

    private boolean checkConnectivity() {
            boolean enabled = true;
    
            ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    
            if ((info == null || !info.isConnected() || !info.isAvailable())) {
                                Toast.makeText(getApplicationContext(), "Sin conexión a Internet...", Toast.LENGTH_SHORT).show();
                return false;
            } else {
                return true;
            }
    
            return false;
        }
    

提交回复
热议问题