GeekyNuns
GeekyNuns

Reputation: 298

Xamarin check internet connection

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.

Upvotes: 0

Views: 2323

Answers (1)

jzeferino
jzeferino

Reputation: 7850

  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.

Upvotes: 4

Related Questions