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
This Code works fine If Intenet is available then starts app smoothly If not then pops a dialog asking to turn on or exit out of app
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.setPositiveButton("Turn On", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
}).show();
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).show();
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;
}
}