androidclassandroid-activitytimeoutnetwork-state

Calling a network State check from other activities


I realize this question has been answered before but couldn't find an answer that deals with my specific case.

I want to create a class called "InternetConnectionChecks" that will handle checking a network state and http timeouts. I'll call the methods twice in the app (once at the beginning to get data from a server, and once at the end to send user orders to the server).

For good form I'd like to put all these methods in a single class rather than copy/paste at different points in my code.

To check the network state, I'm using ConnectivityManager; thing is, getSystemService requires a class that extends Activity.

package arbuckle.app;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class InternetConnectionChecks extends Activity {

    public boolean isNetworkAvailable(){
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if ((activeNetworkInfo != null)&&(activeNetworkInfo.isConnected())){
            return true;
        }else{
            return false;
        }
    }

}

QUESTION: I need to use this code in classes that are NOT activities; in fact I want to set up this method in a separate class that is not an activity. How do I do that?


Solution

  • Create util class with static method

    public class Utils{
    
    public static boolean isNetworkAvailable(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if ((activeNetworkInfo != null)&&(activeNetworkInfo.isConnected())){
            return true;
        }else{
            return false;
        }
    }
    

    }

    usage inside activities

    boolean isNetworkAvailable = Utils.isNetworkAvailable(this);