{"id":38742,"date":"2019-02-12T14:06:36","date_gmt":"2019-02-12T22:06:36","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=38742"},"modified":"2019-04-04T15:53:46","modified_gmt":"2019-04-04T22:53:46","slug":"easily-check-mobile-device-connectivity-with-xamarin-essentials","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/easily-check-mobile-device-connectivity-with-xamarin-essentials\/","title":{"rendered":"Easily Check Mobile Device Connectivity with Xamarin.Essentials"},"content":{"rendered":"<p>\t\t\t\tOne of the best parts of a mobile device is their instant access to the internet. As a mobile app developer, it&#8217;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&#8217; 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 <a href=\"https:\/\/aka.ms\/motz-essentials\">Xamarin.Essentials<\/a>, we can do just that with a few lines of code.<\/p>\n<h2>Setup<\/h2>\n<p>To get started with Xamarin.Essentials simply install the <a href=\"https:\/\/www.nuget.org\/packages\/Xamarin.Essentials\/\">NuGet package<\/a>. Use Xamarin.Essentials for your .NET Standard library if you are using one and your iOS, Android, and UWP app projects.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-38745\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Install.png\" alt=\"\" width=\"764\" height=\"232\" \/><\/p>\n<p>After installing the NuGet, there is just a small amount of code on Android that is required to initialize Xamarin.Essentials.<\/p>\n<p>In the Android project&#8217;s `MainLauncher` or any `Activity` that is launched Xamarin.Essentials must be initialized in the `OnCreate` method:<\/p>\n<pre class=\"lang:c# decode:true \">protected override void OnCreate(Bundle savedInstanceState) {\r\n  \/\/...\r\n  base.OnCreate(savedInstanceState);\r\n  Xamarin.Essentials.Platform.Init(this, savedInstanceState); \/\/ add this line to your code, it may also be called: bundle\r\n  \/\/...\r\n<\/pre>\n<p>To handle runtime permissions on Android, Xamarin.Essentials must receive any `OnRequestPermissionsResult`. Add the following code to all `Activity` classes:<\/p>\n<pre class=\"lang:c# decode:true \">public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)\r\n{\r\n  Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);\r\n\r\n  base.OnRequestPermissionsResult(requestCode, permissions, grantResults);\r\n}\r\n<\/pre>\n<h3>Android Permissions<\/h3>\n<p>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:<\/p>\n<p>Open the AssemblyInfo.cs file under the Properties folder and add:<\/p>\n<pre class=\"lang:c# decode:true \">[assembly: UsesPermission(Android.Manifest.Permission.AccessNetworkState)]\r\n<\/pre>\n<p>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:<\/p>\n<pre class=\"lang:xml decode:true \">\r\n\r\n<\/pre>\n<h2>Check Network Access<\/h2>\n<p>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.<\/p>\n<pre class=\"lang:c# decode:true\">var current = Connectivity.NetworkAccess;\r\n\r\nswitch(current)\r\n{\r\n  case NetworkAccess.Internet:\r\n    \/\/ Connected to internet\r\n    break;\r\n  case NetworkAccess.Local:\r\n    \/\/ Only local network access\r\n    break;\r\n  case NetworkAccess.ConstrainedInternet:\r\n    \/\/ Connected, but limited internet access such as behind a network login page\r\n    break;\r\n  case NetworkAccess.None:\r\n    \/\/ No internet available\r\n    break;\r\n  case NetworkAccess.Unknown:\r\n    \/\/ Internet access is unknown\r\n    break;\r\n}\r\n<\/pre>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-38749\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Connected.png\" alt=\"\" width=\"1145\" height=\"579\" \/><\/p>\n<h2>Subscribe to Connectivity Changes<\/h2>\n<p>In addition to checking the current network access state, we can also register for events whenever the connectivity or the type of connection changes.<\/p>\n<pre class=\"lang:c# decode:true \">public class ConnectivityTest\r\n{\r\n    public void StartListening()\r\n    {\r\n        \/\/ Register for connectivity changes\r\n        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;\r\n    }\r\n\r\n    public void StopListening()\r\n    {\r\n        \/\/ Un-register listener for changes\r\n        Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;\r\n    }\r\n\r\n    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs  e)\r\n    {\r\n        var access = e.NetworkAccess;\r\n        \/\/ Update UI or notify the user\r\n    }\r\n}\r\n<\/pre>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-38750\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/ConnectivityChanges.gif\" alt=\"\" width=\"1224\" height=\"816\" \/><\/p>\n<p>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.<\/p>\n<h2>See It In Action<\/h2>\n<p>Each week on The Xamarin Show on <a href=\"https:\/\/www.youtube.com\/playlist?list=PLlrxD0HtieHjcWsAFoFnPy6I0dn9fDOjS\">YouTube<\/a> and <a href=\"https:\/\/channel9.msdn.com\/Shows\/XamarinShow\">Channel 9<\/a>, we highlight how to set up, get started, and use the APIs in Xamarin.Essentials. Check out this episode on Connectivity:<\/p>\n<p><iframe width=\"560\" height=\"315\" src=\"https:\/\/channel9.msdn.com\/Shows\/XamarinShow\/Connectivity-Essential-API-of-the-Week\/player\" allowfullscreen=\"allowfullscreen\" frameborder=\"0\"><\/iframe><\/p>\n<h2>Learn More<\/h2>\n<p>Browse through the <a href=\"https:\/\/aka.ms\/motz-essentials\">Xamarin.Essentials documentation<\/a> to learn more about all of the great cross-platform native APIs. Be sure to check out the <a href=\"https:\/\/aka.ms\/motz-essentials-connectivity\">Connectivity documentation<\/a> to learn of the APIs available, additional implementation, and limitation details. Xamarin.Essentials is also <a href=\"https:\/\/github.com\/xamarin\/essentials\">open source on GitHub<\/a> where you can report issues, ask for features, and contribute to the library.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As a mobile app developer, it&#8217;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&#8217; 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 the connectivity API in Xamarin.Essentials, we can do just that with a few lines of code.<\/p>\n","protected":false},"author":544,"featured_media":40885,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2,556,291],"tags":[24],"class_list":["post-38742","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","category-integrations","category-xamarin-platform","tag-xamarin-essentials"],"acf":[],"blog_post_summary":"<p>As a mobile app developer, it&#8217;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&#8217; 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 the connectivity API in Xamarin.Essentials, we can do just that with a few lines of code.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/38742","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/544"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=38742"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/38742\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/40885"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=38742"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=38742"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=38742"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}