Search code examples
androidandroid-networking

Detecting android network through external non-static class method


I was wondering if anyone could explain a problem i've been having. Below is a segment of code that i have currently put in each of my classes to check if the Android phones network is available:

private boolean isNetworkAvailable() {

    ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;

    if(networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }

    return isAvailable;
}   

This works very well when placed at the bottom of each class as a private method, however this does not hold much weight as far as the DRY principle goes, so i attempted to put it in an external class called 'appHelpers' and make it public, then simply call the appHelpers class each time i wish to make use of the method:

public boolean isNetworkAvailable() {
    ...
}

Now if i attempt to call the method directly from its class, like so:

if(appHelpers.isNetworkAvailable()) {
    ...
}

I get the familiar "Cannot make a static reference to the non-static method isNetworkAvailable() from the type appHelpers". However if i attempt to make the method static inside appHelpers () , i get a red line under the "getSystemService(Context…) aspect of this line:

ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

With the error reporting as "Cannot make a static reference to the non-static method getSystemService(String) from the type ContextWrapper".

I just cant seem to see what the issue is here, nor am i any closer to solving the problem. Does anyone have any knowledge of this? My appreciations in advance.


Solution

  • You need to pass the Context (from getContext() or "this" if it is an activity, as a new parameter to the static method and call context.getSystemService.

    public static boolean isNetworkAvailable (Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    

    Basically, you are probably used to calling getSystemService from a class that extends Context like an Activity.

    Now from an activity call something like if (appHelpers.isNetworkAvailable (this)) {

    or

    if (appHelpers.isNetworkAvailable (getContext ())) {
    

    depending on where you are calling it from.

    You can make the helper methods static, or add a constructor to your helper to pass in the context and have the helper keep the context as a member.