One of the best parts of a mobile device is their instant access to the internet. As a mobile app developer, it’s great to be able to pull data from the server to our apps to provide users with a delightful experience. Of course, until your user puts their device on airplane mode or hits a rough patch with no cell reception. To provide the best user experience we need access to the current network state of our users’ device. Better yet, be able to register for changes to that network state. Doing this will allow our mobile apps to react to different network conditions to provide users with instant feedback. With connectivity API in Xamarin.Essentials, we can do just that with a few lines of code.
Setup
To get started with Xamarin.Essentials simply install the NuGet package. Use Xamarin.Essentials for your .NET Standard library if you are using one and your iOS, Android, and UWP app projects.
After installing the NuGet, there is just a small amount of code on Android that is required to initialize Xamarin.Essentials.
In the Android project’s `MainLauncher` or any `Activity` that is launched Xamarin.Essentials must be initialized in the `OnCreate` method:
protected override void OnCreate(Bundle savedInstanceState) { //... base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle //...
To handle runtime permissions on Android, Xamarin.Essentials must receive any `OnRequestPermissionsResult`. Add the following code to all `Activity` classes:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
Android Permissions
In addition to Xamarin.Essentials standard initialization, we must also ensure that our application has the correct permissions to access the connectivity APIs. Android is the only platform that needs permissions added which can be accomplished by updating the AssemblyInfo.cs file or the AndroidManifest.xml file directly:
Open the AssemblyInfo.cs file under the Properties folder and add:
[assembly: UsesPermission(Android.Manifest.Permission.AccessNetworkState)]
You can also update the Android manifest by opening the AndroidManifest.xml file under the Properties folder. Then add the following inside of the manifest node:
Check Network Access
When getting or posting data for building mobile applications, it is important to check the current network access of the device. This enables us to handle situations where the user put the device into airplane mode or simply has no internet connection. Xamarin.Essentials provides a simple API to check the current network access state at any moment.
var current = Connectivity.NetworkAccess; switch(current) { case NetworkAccess.Internet: // Connected to internet break; case NetworkAccess.Local: // Only local network access break; case NetworkAccess.ConstrainedInternet: // Connected, but limited internet access such as behind a network login page break; case NetworkAccess.None: // No internet available break; case NetworkAccess.Unknown: // Internet access is unknown break; }
Subscribe to Connectivity Changes
In addition to checking the current network access state, we can also register for events whenever the connectivity or the type of connection changes.
public class ConnectivityTest { public void StartListening() { // Register for connectivity changes Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged; } public void StopListening() { // Un-register listener for changes Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged; } void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e) { var access = e.NetworkAccess; // Update UI or notify the user } }
There you have it. In just a few lines of code, we have checked our network access and registered for changes to the network state.
See It In Action
Each week on The Xamarin Show on YouTube and Channel 9, we highlight how to set up, get started, and use the APIs in Xamarin.Essentials. Check out this episode on Connectivity:
Learn More
Browse through the Xamarin.Essentials documentation to learn more about all of the great cross-platform native APIs. Be sure to check out the Connectivity documentation to learn of the APIs available, additional implementation, and limitation details. Xamarin.Essentials is also open source on GitHub where you can report issues, ask for features, and contribute to the library.
Hi James,
I want to write code to switch Preferred Network Type From 3G to 4G.
Can you Please help me.
I am using Xamarin.Forms and Xamarin.Essentials
Thanks.