Created
August 12, 2014 10:09
-
-
Save prashantvc/a80d07c57d18c75d3cda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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