Skip to content

Instantly share code, notes, and snippets.

@prashantvc
Created August 12, 2014 10:09
Show Gist options
  • Save prashantvc/a80d07c57d18c75d3cda to your computer and use it in GitHub Desktop.
Save prashantvc/a80d07c57d18c75d3cda to your computer and use it in GitHub Desktop.
using System;
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
using Android.Net;
using System.Threading.Tasks;
namespace NetworkCheck
{
[Activity (Label = "NetworkCheck", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += async delegate {
var connected = await IsConnectedToNetwork();
Console.WriteLine ("Connected: {0}", connected);
};
}
Task<bool> IsConnectedToNetwork ()
{
var tsc = new TaskCompletionSource<bool> ();
Task.Factory.StartNew (() => {
var connectivityManager = (ConnectivityManager)GetSystemService (Context.ConnectivityService);
var wifiState = connectivityManager.GetNetworkInfo (ConnectivityType.Wifi).GetState ();
var internetState = connectivityManager.GetNetworkInfo (ConnectivityType.Mobile).GetState ();
bool connected = (wifiState == NetworkInfo.State.Connected || internetState == NetworkInfo.State.Connected);
tsc.TrySetResult (connected);
});
return tsc.Task;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment