Display an alert when internet connection not available in android application
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
And you must add premission for accessing network state and Internet:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
public void onCreate(Bundle obj) {
super.onCreate(obj)
setContextView(layout);
if (isOnline()) {
//do whatever you want to do
} else {
try {
AlertDialog alertDialog = new AlertDialog.Builder(con).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
} catch (Exception e) {
Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
}
}
}