Last active
December 18, 2015 10:39
-
-
Save OnorioCatenacci/5770427 to your computer and use it in GitHub Desktop.
F# Code To Check For Connection Type With Xamarin.Android
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
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