Xamarin Android - Using the Broadcast to detect internet connection

PeterMaiPeterMai DKMember

Hey Xamarin peeps! I have watched a lot of links and guides how to detect the internet connection. I have seen one guide from xamarin that are very useful to detect the internet connection for mobile and wifi. But it only detects each time the activity are refreshed or when the app is getting restarted. But i need to detect the internet with a broadcasting. Which means that everytime when the internet goes on or off there will be a toast message to tell that the broadcasting event has been reached.

I know that i have to set the [assembly: UsesPermission(Manifest.Permission.AccessNetworkState)] inside assemblyInfo.cs to get the permission.

Right now i have this code which work each time the activity is refreshed:

    public void CheckNetwork()
    {

    var connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);

    var activeConnection = connectivityManager.ActiveNetworkInfo;

    if ((activeConnection != null) && activeConnection.IsConnected)
        {
            Toast.MakeText (this, "OK", ToastLength.Short).Show ();
        } 

    else 
        {
            Toast.MakeText (this, "NOT OK", ToastLength.Short).Show ();
        }

    }
Sign In or Register to comment.