Android app crashes on first disconnected network and then on

I use the following function to check the network connection, but the application crashes when the wifi status changes

    public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connec = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connec.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected() == true) {
        return true;
    }
    return false;
}
+3
source share
2 answers

it took some time to switch between networks ...

So, if we turn off Wi-Fi, it will automatically connect to the mobile network in a few seconds .. and if we turn on Wi-Fi, it will reconnect to the Wi-Fi network ...

The thread in your application checks the connection before this change ...

check the conversation here

Android: how to enable / disable wifi or internet connection programmatically

+1
source

Are you missing NullPointerException?

I am using the following method:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        return cm.getActiveNetworkInfo().isConnectedOrConnecting();
    } catch(NullPointerException n) {
        return false;
    }
}
+1

Source: https://habr.com/ru/post/1792791/


All Articles