It is always a good practice to keep the user informed on any HTTP based operations that are occurring on the background. For this, determining  network connectivity is a key step for any Mobile app.

If you are creating a Cross-platform App or even multiple Native Apps, checking for Connectivity becomes a challenge as Network Connectivity APIs are extremely specific to the  Mobile Platform.

Xam.Plugin.Connectivity is nifty little PCL that can be very helpful.

Begin by adding the Plugin to your project.

By Command Line:

Install-Package Xam.Plugin.Connectivity

Or Adding a package

Screen Shot 2016-10-24 at 11.54.17 AM.png

For Android

If you are planning to use this in Android, then add the ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE permissions to the Android manifest.

Checking for Connectivity

 CrossConnectivity.Current.IsConnected

This returns True if Any form  of connectivity is available. If the device is in Flight mode it will return False.

Connection Change

You can subscribe for connection change also.


CrossConnectivity.Current.ConnectivityChanged += HandleConnectivityChanged;

void HandleConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
		{
			var connections = CrossConnectivity.Current.ConnectionTypes;

			foreach (var connection in connections)
			{
				switch (connection)
				{
					case ConnectionType.Cellular:
						{
							System.Diagnostics.Debug.WriteLine("Cellular Connection Available");
							break;
						}

					case ConnectionType.WiFi:
						{
							System.Diagnostics.Debug.WriteLine("WiFi Connection Available");
							break;
						}
					case ConnectionType.Desktop:
						{
							System.Diagnostics.Debug.WriteLine("Desktop Connection Available");
							break;
						}
				}
			}

		}

The Plugin  also provides Bandwith information (Does not work for iOS).

You can also ping a website.

  CrossConnectivity.Current.IsReachable("www.google.com", 5000);

In all it is a cool plugin. That can save you some time.

Advertisements