Pregunta

I want to check internet connection in whole app. I've googled for it, but the result was everyone creates an instance method in each class and tries to check the internet connection. My plan is to create a class with static method and check it without instantiating my class. Is it good idea to do that? Or should I try another way? My plan is to do something like this:

public class CheckInternetConnecting {

    public static boolean isOnline(Context context) {
         ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        return cm.getActiveNetworkInfo() != null &&
            cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }
}
¿Fue útil?

Solución 2

Your approach is totally fine. I would recommend to add a package Utils to your project and put Helper-Classes in there. So instead of a class CheckInternetConnecting, create a class NetworkHelper and put your static method in there.

Adding a package:
On the left side of eclipse, in your package explorer right click your src folder and add a new package. It's important to include your package name, e.g when your package name is com.my.project than add a package called com.my.project.utils... Then you can add your NetworkHelper class to the new package by e.g right clicking and adding a new file. Copy your static code into the NetworkHelper and then you're all set...

Otros consejos

You can also check the internet connectivity in the following way..

public boolean testConnection() {

    try {
        boolean connectionStatus=false;

        InetAddress addr=InetAddress.getByName("8.8.8.8");//google dns 8.8.8.8


        connectionStatus=addr.isReachable(1000); // 1second time for response

    }                               
    catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.toString());
    }

    return connectionStatus;
}

Perhaps you can consider registering a broadcast receiver and listening out for connectivity changes as explained here.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top