App stops when using Connectivity manager

0

I have a class in which I pretend to see if the user is connected or not. However, the whole method did not work, so I was removing things to see what the problem was and I have seen that only with the code in this way the app stops when executing it:

public class Conectividad 
{
    static Context context;
    @org.jetbrains.annotations.Contract(value = " -> false", pure = true)
    public static boolean conectado()
    {
        ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        return false;
    }
}

Regarding the call to that method, I simply do the following: if(Conectividad.conectado()==false)

At the time I tried to do everything in the same class, but that, although it made that work, made the screen go blank when executing it. The previous method in question was the following:

 public static boolean conectado()
    {
        ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return (info!=null && info.isConnectedOrConnecting());
    }

And the call to it was: if(conectado()==false) .

On the other hand, in the manifest I have added

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

Neither of these two methods worked for me. Does anyone know how to make this work?

    
asked by pepito 13.07.2017 в 08:43
source

1 answer

1

This looks like you have forgotten to add the corresponding permission to check the status of the network:

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

You can use the following code to check whether it is connected or not

public boolean conectado() {
        ConnectivityManager connectivity  = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivity.getActiveNetworkInfo();
        return (activeNetworkInfo != null && activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected());
 }

EDITED

Reviewing your code I realized that you are using the context that you have defined in your class Conectividad but you have not put if that parameter you have given value somewhere. An alternative to solve this would be that instead of defining it in your class Conectividad you pass the context of the Activity as a parameter every time you want to check the connection, leaving your function as follows:

public static boolean conectado(Context context)
{
        ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return (info!=null && info.isConnectedOrConnecting());
}
    
answered by 13.07.2017 / 08:59
source