0

I want to add in my app boolean to check if device is connected to Internet or not. I found this question

But I can't get it to work in my app. This is the code:

private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
             = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
    public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500); 
                urlc.connect();
                return (urlc.getResponseCode() == 200);
            } catch (IOException e) {
            }
        } else {
        }
        return false;

    }

It's in my MainActivity. I get this error:

The method isNetworkAvailable() in the type MainActivity is not applicable for the arguments (Context)

Why am I getting this error? What's wrong with my code? or I just need to put those methods in separate activities?

Community
  • 1
  • 1
user3231871
  • 181
  • 3
  • 16

2 Answers2

2

make sure that you are adding particular permission in androidmanifest.xml then

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

replace with this code

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager 
         = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}
public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
        }
    } else {
    }
    return false;

}
Jeekiran
  • 465
  • 3
  • 10
0

your isNetworkAvailable, takes not parameter but your invoking it with a context object

if (isNetworkAvailable(context))

causing the compile time error. You can change the signature of isNetworkAbailable like

private static boolean isNetworkAvailable(Context context) {

}
Blackbelt
  • 148,780
  • 26
  • 271
  • 285