Wednesday, February 14, 2018

How to check Internet is Connected or Not



In Android many times we need to check whetehr Intener is connected or not.

Internt can be connected by Mobile Data or Wifi.


Here I will discuss, how to do it by code.





 public void checkInternetConnectionAndShowDialog()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE );


NetworkInfo activeNetInfoMobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE );
NetworkInfo activeNetInfoWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI );
NetworkInfo activeNetInfoWimax = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIMAX );



boolean isConnectedMobileData = activeNetInfoMobile != null && activeNetInfoMobile.isConnectedOrConnecting(); 
boolean isConnectedWiFi = activeNetInfoWifi != null && activeNetInfoWifi.isConnectedOrConnecting();
boolean isConnectedWiMax = activeNetInfoWimax != null && activeNetInfoWimax.isConnectedOrConnecting();


boolean isConncted=isConnectedMobileData||isConnectedWiFi||isConnectedWiMax;

if(isConncted == false)
{
mWebView.setVisibility(View.INVISIBLE);
AlertDialog dialog;
            dialog = new AlertDialog.Builder(getActivity()).create();
            dialog.setTitle("Not Connected");
            dialog.setIcon(android.R.drawable.ic_dialog_info);
            dialog.setMessage("Internet not Available. Please connect to Internet and try again.\n\n");
           
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which)
                {
                       
                //finish();
                }   
            });
           
            dialog.show();
            dialog.setOnDismissListener(new OnDismissListener() {


@Override
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub


}
});
           
           
}

}

No comments:

Post a Comment