0

I have use of internet in my android application. I get data from server for that I have to check for internet connectivity befor user try to request on server. What can I do for that?

Vikram
  • 85
  • 1
  • 11

1 Answers1

0

This is the function I used to check whether my application is connected to Internet or not.

private void CheckEnabledInternet() {
    boolean isConnected = false;
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo[]  networkInfos = connectivityManager.getAllNetworkInfo();
    for(NetworkInfo networkInfo : networkInfos) {
        if(networkInfo.getState()== NetworkInfo.State.CONNECTED) {
            isConnected = true;
            break;
        }
    }
    if(!isConnected) {
        AlertDialog.Builder networkDialog = new AlertDialog.Builder(this);
        networkDialog.setTitle("Not Connected");
        networkDialog.setMessage("Please connect to internet to proceed");
        networkDialog.setCancelable(false);
        networkDialog.setPositiveButton("Okay!",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                CheckEnabledInternet();
            }
        });
        networkDialog.create().show();
    }
}
Adarsh
  • 827
  • 9
  • 23