How to check if Network is available in Android Studio app

After working and searching for hours and you can’t get the solution you are looking for. You are welcome to the home of Android Developer. If you have being using Android Studio for writing Java apps, Java codes is everything sensitive raging from capital letters, punctuation errors, misspelled of words and plugin updates.

Android Studio comes up with new updates always which depreciated the older once. A code you write today, use it and develop an app may be outdated and depreciated tomorrow. If you copy somebody’s code or forked a code from github, there are chances that the code which worked earlier won’t work again unless you do serious editing.

Use the below codes


1.


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(!isNetworkStatusAvialable (getApplicationContext())) {
            //if there is no internet do this
            new AlertDialog.Builder(this) //alert the person knowing they are about to close
                    .setTitle(“You need an internet connection to use this app”)
                    .setMessage(“Check to see if you’re mobile data is on or you are connected to a wi-fi network.”)
                    .setPositiveButton(“Okay”, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    //.setNegativeButton(“No”, null)
                    .show();
        }
        else
        {
       

.2.
public static boolean isNetworkStatusAvialable (Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null)
        {
            NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
            if(netInfos != null)
                if(netInfos.isConnected())
                    return true;
        }
        return false;
    }


3.
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();


ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMetered = cm.isActiveNetworkMetered();

Note: If your app needs to support Android 4.0 (API level 15) and lower, use ConnectivityManagerCompat.isActiveNetworkMetered instead of ConnectivityManager.isActiveNetworkMetered().