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
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