Skip to content
This repository has been archived by the owner on Apr 3, 2023. It is now read-only.

Commit

Permalink
Add documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesmontemagno committed Jul 6, 2017
1 parent bc78b78 commit a2464a1
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 102 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2016 James Montemagno
Copyright (c) 2017 James Montemagno

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
110 changes: 9 additions & 101 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

Simple cross platform plugin to check connection status of mobile device, gather connection type, bandwidths, and more.

### Setup
* Available on NuGet: http://www.nuget.org/packages/Xam.Plugin.Connectivity [![NuGet](https://img.shields.io/nuget/v/Xam.Plugin.Connectivity.svg?label=NuGet)](https://www.nuget.org/packages/Xam.Plugin.Connectivity/)
* Install into your PCL project and Client projects.
## Documentation
Get started by reading through the [Connectivity Plugin documentation](docs).

Build Status:
## NuGet
* Available on NuGet: [Xam.Plugin.Connectivity](http://www.nuget.org/packages/Xam.Plugin.Connectivity) [![NuGet](https://img.shields.io/nuget/v/Xam.Plugin.Connectivity.svg?label=NuGet)](https://www.nuget.org/packages/Xam.Plugin.Connectivity/)

## Build:
* [![Build status](https://ci.appveyor.com/api/projects/status/k6l4x6ovp5ysfbar?svg=true)](https://ci.appveyor.com/project/JamesMontemagno/connectivityplugin)
* CI NuGet Feed: https://ci.appveyor.com/nuget/connectivityplugin

**Platform Support**
## Platform Support

|Platform|Version|
| ------------------- | :------------------: |
Expand All @@ -21,99 +23,5 @@ Build Status:
|Xamarin.Mac|All|
|.NET 4.5/WPF|All|


### API Usage

Call **CrossConnectivity.Current** from any project or PCL to gain access to APIs.


**IsConnected**
```csharp
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
bool IsConnected { get; }
```

**ConnectionTypes**
```csharp
/// <summary>
/// Gets the list of all active connection types.
/// </summary>
IEnumerable<ConnectionType> ConnectionTypes { get; }
```

**Bandwidths**
```csharp
/// <summary>
/// Retrieves a list of available bandwidths for the platform.
/// Only active connections.
/// </summary>
IEnumerable<UInt64> Bandwidths { get; }
```

#### Pinging Hosts

**IsReachable**
```csharp
/// <summary>
/// Tests if a host name is pingable
/// </summary>
/// <param name="host">The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address (127.0.0.1)</param>
/// <param name="msTimeout">Timeout in milliseconds</param>
/// <returns></returns>
Task<bool> IsReachable(string host, int msTimeout = 5000);
```

**IsRemoteReachable**
```csharp
/// <summary>
/// Tests if a remote host name is reachable (no http:// or www.)
/// </summary>
/// <param name="host">Host name can be a remote IP or URL of website</param>
/// <param name="port">Port to attempt to check is reachable.</param>
/// <param name="msTimeout">Timeout in milliseconds.</param>
/// <returns></returns>
Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000);
```

#### Changes in Connectivity
When any network connectivity is gained, changed, or loss you can register for an event to fire:
```csharp
/// <summary>
/// Event handler when connection changes
/// </summary>
event ConnectivityChangedEventHandler ConnectivityChanged;
```

You will get a ConnectivityChangeEventArgs with the status if you are connected or not:
```csharp
public class ConnectivityChangedEventArgs : EventArgs
{
public bool IsConnected { get; set; }
}

public delegate void ConnectivityChangedEventHandler(object sender, ConnectivityChangedEventArgs e);
```

Usage sample from Xamarin.Forms:
```csharp
CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
page.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
};
```


### **IMPORTANT**
### Android:
The ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE permissions are required and will be automatically added to your Android Manifest.

By adding these permissions [Google Play will automatically filter out devices](http://developer.android.com/guide/topics/manifest/uses-feature-element.html#permissions-features) without specific hardware. You can get around this by adding the following to your AssemblyInfo.cs file in your Android project:

```
[assembly: UsesFeature("android.hardware.wifi", Required = false)]
```

### iOS:
Bandwidths are not supported and will always return an empty list.
## License
The MIT License (MIT) see [License file](LICENSE)
82 changes: 82 additions & 0 deletions docs/1-GettingStarted.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Getting Started


## Setup
* NuGet: [Xam.Plugin.Connectivity](http://www.nuget.org/packages/Xam.Plugin.Connectivity): [![NuGet](https://img.shields.io/nuget/v/Xam.Plugin.Connectivity.svg?label=NuGet)]
(https://www.nuget.org/packages/Xam.Plugin.Connectivity/)
* `PM> Install-Package Xam.Plugin.Connectivity`
* Install into ALL of your projects, include client projects.


## Using Connectivity APIs
It is drop dead simply to gain access to the Connectivity APIs in any project by getting a reference to the current instance of IConnectivity with `CrossConnectivity.Current`:

```csharp
public bool DoIHaveInternet()
{
return CrossConnectivity.Current.IsConnected;
}
```

Additionally, there may be instances where you install a plugin into a platform that it isn't support yet. You can make a simple check before calling the API to see if it is supported on the platform where the code is running. This if nifty when unit testing:

```csharp
public bool DoIHaveInternet()
{
if(!CrossConnectivity.IsSupported)
return true;

return CrossConnectivity.Current.IsConnected;
}
```

## Disposing of Connectivity Plugin
This plugin also implements IDisposable on all implmentations. This ensure that all events are unregistered from the platform. There isn't a great need to dispose from any of my findings. The next time you gain access to the `CrossConnectivity.Current` a new instance will be created.

```csharp
public bool DoIHaveInternet()
{
if(!CrossConnectivity.IsSupported)
return true;

using(var connectivity = CrossConnectivity.Current)
{
return connectivity.IsConnected;
}
}
```


## Permissions & Additional Setup Considerations

### Android:
The `ACCESS_NETWORK_STATE` and `ACCESS_WIFI_STATE` permissions are required and will be automatically added to your Android Manifest.

By adding these permissions [Google Play will automatically filter out devices](http://developer.android.com/guide/topics/manifest/uses-feature-element.html#permissions-features) without specific hardware. You can get around this by adding the following to your AssemblyInfo.cs file in your Android project:

```csharp
[assembly: UsesFeature("android.hardware.wifi", Required = false)]
```

## Architecture

### What's with this .Current Global Variable? Why can't I use $FAVORITE_IOC_LIBARY
You totally can! Every plugin I create is based on an interface. The static singleton just gives you a super simple way of gaining access to the platform implementation. Realize that the implementation of the plugin lives in your iOS, Android, Windows, etc. Thies means you will need to register it there by instantiating a `CrossConnectivityImplementation` from the platform specific projects.

If you are using a ViewModel/IOC approach your code may look like:

```csharp
public MyViewModel()
{
readonly IConnectivity connectivity;
public MyViewModel(IConnectivity connectivity)
{
this.connectivity = connectivity;
}

public bool IsConnected => connectivity?.IsConnected ?? false;
}
```

### What About Unit Testing?
To learn about unit testing strategies be sure to read my blog: [Unit Testing Plugins for Xamarin](http://motzcod.es/post/159267241302/unit-testing-plugins-for-xamarin)
91 changes: 91 additions & 0 deletions docs/2-CheckingConnectivity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
## Checking Connectivity
There are a few properties that can be used to easily check connection information using the plugin.

### Check Connectivity
`IsConnected`: The easiest and most common use case of simply chcking if there is interent access:

```csharp
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
bool IsConnected { get; }
```

Example:
```csharp
public async Task<string> MakeWebRequest()
{
if(!CrossConnectivity.Current.IsConnected)
{
//You are offline, notify the user
return null;
}

//Make web request here
}
```

### Check Type of Connection
Easily check what type of internet connection is currently active.

```csharp
/// <summary>
/// Gets the list of all active connection types.
/// </summary>
IEnumerable<ConnectionType> ConnectionTypes { get; }
```

Example:
```csharp
public async Task<string> MakeWebRequestWifiOnly()
{
var wifi = Plugin.Connectivity.Abstractions.ConnectionType.WiFi;
var connectionTypes = CrossConnectivity.Current.ConnectionTypes;
if(!connectionTypes.Contains(wifi))
{
//You do not have wifi
return null;
}

//Make web request here
}
```

### Speed of Connection

You can query all bandwidths of the active connections in Bits Per Second.

```csharp
/// <summary>
/// Retrieves a list of available bandwidths for the platform.
/// Only active connections.
/// </summary>
IEnumerable<UInt64> Bandwidths { get; }
```

Example:
```csharp
public async Task<string> MakeWebRequestOneMeg()
{
var optimalSpeed = 1000000; //1Mbps
var speeds = CrossConnectivity.Current.Bandwidths;

//If on iOS or none were returned
if(speeds.Length == 0)
return null;

if(!connectionTypes.Any(speed => speed > optimalSpeed))
{
//You do not have wifi
return null;
}

//Make web request here
}
```

**Platform Tweaks**:
* Apple Platforms: Bandwidths are not supported and will always return an empty list.
* Android: In releases earlier than 3.0.2 this was returned as Mbps.
* Android: Only returns bandwidth of WiFi connections. For all others you can check the

60 changes: 60 additions & 0 deletions docs/3-ConnectivityChanges.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
## Detecting Connectivity Changes
Often you may need to notify your user or respond based on network changes. You can do this by subscribing several different events.

#### Changes in Connectivity
When any network connectivity is gained, changed, or loss you can register for an event to fire:
```csharp
/// <summary>
/// Event handler when connection changes
/// </summary>
event ConnectivityChangedEventHandler ConnectivityChanged;
```

You will get a ConnectivityChangeEventArgs with the status if you are connected or not:
```csharp
public class ConnectivityChangedEventArgs : EventArgs
{
public bool IsConnected { get; set; }
}

public delegate void ConnectivityChangedEventHandler(object sender, ConnectivityChangedEventArgs e);
```

```csharp
CrossConnectivity.Current.ConnectivityChanged += async (sender, args) =>
{
Debug.WriteLine($"Connectivity changed to {args.IsConnected}");
};
```


### Changes in Connectivity Type
When any network connectivity type is changed this event is triggered. Often it also is accompanied by a `ConnectivityChanged` event.

```csharp
/// <summary>
/// Event handler when connection type changes
/// </summary>
event ConnectivityTypeChangedEventHandler ConnectivityTypeChanged;
```

When this occurs an event will be triggered with EventArgs that have the most recent information:

```csharp
public class ConnectivityTypeChangedEventArgs : EventArgs
{
public bool IsConnected { get; set; }
public IEnumerable<ConnectionType> ConnectionTypes { get; set; }
}
public delegate void ConnectivityTypeChangedEventHandler(object sender, ConnectivityTypeChangedEventArgs e);
```

Example:
```csharp
CrossConnectivity.Current.ConnectivityTypeChanged += async (sender, args) =>
{
Debug.WriteLine($"Connectivity changed to {args.IsConnected}");
foreach(var t in args.ConnectionTypes)
Debug.WriteLine($"Connection Type {t}");
};
```
Loading

0 comments on commit a2464a1

Please sign in to comment.