Display an alert when internet connection not available in android application

后端 未结 13 775
有刺的猬
有刺的猬 2020-12-08 11:48

In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn\'t, it gives an alert

13条回答
  •  青春惊慌失措
    2020-12-08 12:29

    You can use these methods anywhere

    public void checkNetworkConnection(){
        AlertDialog.Builder builder =new AlertDialog.Builder(this);
        builder.setTitle("No internet Connection");
        builder.setMessage("Please turn on internet connection to continue");
        builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
    
    public boolean isNetworkConnectionAvailable(){
        ConnectivityManager cm =
                (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnected();
        if(isConnected) {
            Log.d("Network", "Connected");
            return true;
            }
        else{
            checkNetworkConnection();
            Log.d("Network","Not Connected");
            return false;
        }
    }
    

    when you need to check connection available call isNetworkConnectionAvailable() method.If the network not available it will pop up your dialog box. If you need to check network in multiple screen add these methods to the super class and inherit that class to other class and call this method when need

提交回复
热议问题