Android detect Network Java Codes!

You can have separated class for checking internet as I called “CheckNetwork” below.

The method to check whether the device connected to internet or not in this class is isInternetAvailable which returns a boolean variable.

public class CheckNetwork {
   
public static boolean isInternetAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.
CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();

       
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
            NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.
TYPE_WIFI);
            NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.
TYPE_MOBILE);

           
if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
               
return true;
           
else return false;
        }
else return false;
    }
}

And in MainActivity.java simply type: 

if (CheckNetwork.isInternetAvailable(MainActivity.this)) {
        // do your stuff….      
} else {
Toast.makeText(MainActivity.this,MainActivity.this.getResources().getString(R.string.no_internet),//show message here Toast.LENGTH_SHORT).show();
    return;
}
Done and done.

I have used all these codes in my app, to check working code on a real application, please check it here


Comments

Popular posts from this blog

Gove confirms mandatory housebuilding targets for councils will be abolished in face of Tory rebellion – UK politics live

Kotak Mahindra Bank Recruitment 2022 Released for Graduate Candidates And Apply Online