Search code examples
androidcrashandroid-internet

Checking if a user is connected to the network in android


In my main activity i have

 if (isNetworkAvailable() == true) {
        Log.i("testing", "available");

    } else {
        Log.i("test", "unaivalibale");
    }

Then below i have the method as

  private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

I have also set

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In the manifest and yet when i run tha application it always stops, killing the application what is wrong


Solution

  • Make a class and add method properly:

    public class ConnectivityStatus extends ContextWrapper{
    public ConnectivityStatus(Context base) {
        super(base);
    }
    
    public static boolean isConnected(Context context){
    
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = manager.getActiveNetworkInfo();
        if (connection != null && connection.isConnectedOrConnecting()){
            return true;
        }
        return false;
     }
    }
    

    Get status, in Activity where you using as:

    if(!ConnectivityStatus.isConnected(your_class_name.this)){
                //not connected
    }else {
                //connected
    }