Skip to content

Instantly share code, notes, and snippets.

@OnorioCatenacci
Last active December 18, 2015 10:39
Show Gist options
  • Save OnorioCatenacci/5770427 to your computer and use it in GitHub Desktop.
Save OnorioCatenacci/5770427 to your computer and use it in GitHub Desktop.
F# Code To Check For Connection Type With Xamarin.Android
open Android.App
open Android.Content
open Android.Net
let IsConnectionAvailable (app:Activity) connTypeToCheckFor =
let n = app.GetSystemService(Context.ConnectivityService)
let cm =
match n with
| :? ConnectivityManager as cm -> Some(cm)
| null | _ -> None
let cs = if cm.IsSome then Some(cm.Value.get_ActiveNetworkInfo()) else None
if cs.IsSome then (cs.Value.Type = connTypeToCheckFor) else false
(* Call this with code like this:
// From inside of MainActivity type
wifiStatus.Text <- sprintf "WiFi is %s" <| if IsConnectionAvailable this Android.Net.ConnectivityType.Wifi then "available" else "unavailable"
*)
(* Dave Thomas also suggested a few other alternative approaches for this:
let IsConnectionAvailable (app:Activity) connTypeToCheckFor =
match app.GetSystemService(Context.ConnectivityService) with
| :? ConnectivityManager as cm -> (cm.get_ActiveNetworkInfo()).Type = connTypeToCheckFor
| _ -> false
//Alternatively we could use an active pattern
let (|ConnectionAvailable|_|) connTypeToCheckFor (app:Activity) =
match app.GetSystemService(Context.ConnectivityService) with
| :? ConnectivityManager as cm -> match cm.get_ActiveNetworkInfo() with
| x when x.Type = connTypeToCheckFor -> Some()
| _ -> None
| _ -> None
// Then the check could then be parameterised:
let text = sprintf "WiFi is %s" <| match this with
| ConnectionAvailable ConnectivityType.Wifi () -> "available"
| _ -> "unavailable"
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment