0

I have to check internet connection in my application, fallowing this answer I have added lines to my manifest file. However I have an issue with getSystemServiceMethod it is not defined in my case, context does not contain such a method.

As well I`ve been trying to do something like this:

public static bool isInternetOn()
{
    ConnectivityManager connectivityManager = (ConnectivityManager)Context.ConnectivityService;
    NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
    bool isWifi = networkInfo.Type == ConnectivityType.Wifi; // wifi check
    return networkInfo.IsConnected;
}

But it throws an exception. How could I fix this issue and check whether the phone has access to the internet.

GeekyNuns
  • 287
  • 2
  • 20

1 Answers1

4
  1. You could pass the Context as parameter of isInternetOn.

or

  1. Use connectivityManager = (ConnectivityManager)(Application.Context.GetSystemService(Context.ConnectivityService));

or

  1. Better than the above ones, you should use the ConnectivityPlugin

Your code have a bug, you must check networkInfo nullity. It should look like this:

public static bool isInternetOn()
{
    var connectivityManager = (ConnectivityManager)(Application.Context.GetSystemService(Context.ConnectivityService));
    NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
    return networkInfo != null && networkInfo.IsConnected;
}

FINAL NOTE:

Your implementation don't cover all the cases, please see. You should use ConnectivityPlugin.

jzeferino
  • 7,700
  • 1
  • 39
  • 59