Android - Programmatically check internet connection and display dialog if notConnected

You could checkout this library:

https://github.com/novoda/merlin

You just implement Connectable and you will get a callback when the network goes down or comes up.

Therefore you can show your dialog in this scenario.

You can also query the library for the current state and choose not to do your network task

example

Create Merlin (using Merlin.Builder())

merlin = new Merlin.Builder().withConnectableCallbacks().build(context);

Bind and unbind the service in your activity

@Override
protected void onResume() {
    super.onResume();
    merlin.bind();
}

@Override
protected void onPause() {
    super.onPause();
    merlin.unbind();
}

Register for callbacks

merlin.registerConnectable(new Connectable() {
        @Override
        public void onConnect() {
            // Do something!
        }
});

The MerlinActivity within the demo shows a simple way to declutter Merlin from your main application code.


Finally, I got the answer.

ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
    Description.setVisibility(View.INVISIBLE);
    new AlertDialog.Builder(WelcomePage.this)
        .setTitle(getResources().getString(R.string.app_name))
        .setMessage(getResources().getString(R.string.internet_error))
        .setPositiveButton("OK", null).show();
}else{
    dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,false);
    new Welcome_Page().execute();
}

Check internet connection

 ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo netInfo = mgr.getActiveNetworkInfo();

        if (netInfo != null) {
            if (netInfo.isConnected()) {
                // Internet Available
            }else {
               //No internet
            }
        } else {
            //No internet
        }