{"id":28932,"date":"2016-12-07T13:33:37","date_gmt":"2016-12-07T21:33:37","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=28932"},"modified":"2016-12-07T13:33:37","modified_gmt":"2016-12-07T21:33:37","slug":"google-awareness-api-for-android-query-and-react-to-signals","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/google-awareness-api-for-android-query-and-react-to-signals\/","title":{"rendered":"Google Awareness API for Android: Query and React to Signals"},"content":{"rendered":"<p>\t\t\t\t<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Awareness-API.png\" alt=\"awareness-api\" width=\"275\" class=\"alignright size-full wp-image-28933\" \/>Google Play services offers a plethora of amazing APIs for developers to integrate into their iOS and Android applications. For Android developers, specifically, there are several more APIs available that can give you even more power and integration with the Android OS when developing apps for the platform. One of the newest APIs, <a href=\"https:\/\/developers.google.com\/awareness\/\">Awareness<\/a>, brings together <strong>seven<\/strong> different location and context signals into a single easy to use API, including time, location, places, beacons, headphones, activity, and even weather. The <a href=\"https:\/\/www.nuget.org\/packages\/Xamarin.GooglePlayServices.Awareness\/\">NuGet package<\/a> for the Awareness API launches alongside our release of Google Play services 9.6.1 (32.961.0) for Xamarin.<\/p>\n<p>The Awareness API offers two different ways to get insight to these signals, the Fence and the Snapshot APIs. The Fence API allows you to react to changes in the user&#8217;s environment and the signals. You can create multiple conditions that need to be met and when they occur, you receive a callback to react to them. The Snapshot API on the other hand, which we&#8217;ll look at today, gives you direct access to the signals from one simple asynchronous API. In addition to being a simple API, the Awareness API delivers better battery performance and memory usage due to its intelligent caching and cross-app optimizations. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SnapShotandFence.png\" alt=\"snapshotandfence\" width=\"2549\" height=\"850\" class=\"aligncenter size-full wp-image-28934\" \/><\/p>\n<h2>Install the Awareness NuGet<\/h2>\n<p>The first step to accessing the Awareness APIs is to add the Google Play services &#8211; Awareness NuGet to your Xamarin.Android application. As of this blog post, the current version is 32.961.0. The easiest way to find the NuGet is to directly enter the package name <b>Xamarin.GooglePlayServices.Awareness<\/b>. The additional dependencies of Google Play services Places, Location, Base packages, and required Support Packages will also come along when the NuGet is added.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AddNuGet.png\" alt=\"addnuget\" width=\"2251\" height=\"647\" class=\"aligncenter size-full wp-image-28935\" \/><\/p>\n<h2>Register for API Keys<\/h2>\n<p>Google Play services often require a unique API key for each application using them. These are created and enabled in the <a href=\"https:\/\/console.developers.google.com\">Google API Developer Console<\/a>. First create a new project: \n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/1-New-Project.png\" alt=\"1-new-project\" width=\"400\" class=\"aligncenter size-full wp-image-28937\" \/><\/p>\n<p>Once it is created, you&#8217;ll want to enable three different APIs:<\/p>\n<ul>\n<li>Awareness API<\/li>\n<li>Google Places API for Android (for Places API)<\/li>\n<li>Nearby Messages API (for Beacons API)<\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/2-Add-APIs.png\" alt=\"2-add-apis\" width=\"3000\" height=\"655\" class=\"aligncenter size-full wp-image-28938\" \/><\/p>\n<p>You&#8217;ll need to enter your application&#8217;s package name and the keystore&#8217;s SHA1 you&#8217;re using for debug and release when ready to deploy to the app store to register these. You can read through <a href=\"https:\/\/developer.xamarin.com\/guides\/android\/platform_features\/maps_and_location\/maps\/obtaining_a_google_maps_api_key\/#Obtaining_your_Signing_Key_Fingerprint\">Obtaining your Signing Key Fingerprint in our Android documentation<\/a>.<\/p>\n<p>Simply create new credentials using these keys.\n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/3-Credentials.png\" alt=\"3-credentials\" width=\"2397\" height=\"132\" class=\"aligncenter size-full wp-image-28939\" \/><\/p>\n<h3>Add Keys to the Android Manifest<\/h3>\n<p>Once you have registered for the APIs, you&#8217;ll receive a unique API Key that needs to be added to your Android Manifest file. It&#8217;s the same API Key for each of the meta-data tags that we&#8217;ll add to the application node, which will look like this:<\/p>\n<pre class=\"theme:vs2012 lang:xml decode:true\">\n\n    \n    \n    \n\n<\/pre>\n<h2>Create GoogleAPIClient<\/h2>\n<p>With all of the API Key registration out of the way, it&#8217;s now time to actually start using the Awareness API. To use any Google Play service API, we&#8217;ll need to create a <b>GoogleApiClient<\/b>. First let&#8217;s bring in a few namespaces:<\/p>\n<pre class=\"theme:vs2012 lang:csharp decode:true\">\nusing Android.Gms.Common.Apis;\nusing Android.Gms.Awareness;\nusing Android.Gms.Awareness.State;\nusing Android.Gms.Extensions;\n<\/pre>\n<p>Now, in our Activity, we can create and connect to the <b>GoogleApiClient<\/b>:<\/p>\n<pre class=\"theme:vs2012 lang:csharp decode:true\">\npublic class MainActivity : Activity\n{\n  GoogleApiClient client;\n  protected async override void OnCreate(Bundle bundle)\n  {\n    base.OnCreate(bundle);\n\n    client = await new GoogleApiClient.Builder(this)\n                       .AddApi(Awareness.Api)\n                       .AddConnectionCallbacks(() =&gt;\n                        {\n                          \/\/Connected Successful\n                        })\n                        .BuildAndConnectAsync((i) =&gt;{ });\n            \n  }\n}\n<\/pre>\n<h2>Query Signals<\/h2>\n<p>We can now start using the API to query signals, such as headphones.<\/p>\n<pre class=\"theme:vs2012 lang:csharp decode:true\">\nvar headPhones = await Awareness.SnapshotApi.GetHeadphoneStateAsync(client);\nif (headPhones?.Status?.IsSuccess ?? false)\n{\n  if(headPhones.HeadphoneState.State == HeadphoneState.PluggedIn)\n    Debug.WriteLine(Headphones plugged in\");\n  else\n    Debug.WriteLine(Headphones not plugged in\");\n}\nelse\n{\n  Debug.WriteLine(\"Could not get headphone state\");\n}\n<\/pre>\n<p>Other signals besides headphones <a href=\"https:\/\/developers.google.com\/awareness\/android-api\/required-permissions\">require additional permissions<\/a> such as location and activity recognition. We must add two specific permissions to the Android Manifest:<\/p>\n<pre class=\"theme:vs2012 lang:xml decode:true\">\n\n\n<\/pre>\n<p>To check and request permissions, we can use the <a href=\"https:\/\/github.com\/jamesmontemagno\/PermissionsPlugin\">Permissions Plugin<\/a> that helps abstract the functionality into a simple call. If we want to query the location and weather, we can use the Permissions Plugin along side the Awareness API:<\/p>\n<pre class=\"theme:vs2012 lang:csharp decode:true\">\n\/\/Check and request permissions\nvar status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);\nif (status != PermissionStatus.Granted)\n{\n  var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);\n  if (results[Permission.Location] != PermissionStatus.Granted)\n    return; \/\/handle rejection\n}\n\n\/\/Get current location\nvar location = await Awareness.SnapshotApi.GetLocationAsync(client);\nif (location?.Status?.IsSuccess ?? false)\n  Debug.WriteLine($\"Location: {location.Location.Latitude},{location.Location.Longitude}\");\n\n\/\/Get weather information\nvar weather = await Awareness.SnapshotApi.GetWeatherAsync(client);\nif (weather?.Status?.IsSuccess ?? false &amp;&amp; weather.Weather != null)\n{\n  Debug.WriteLine($\"Temperature: {weather.Weather.GetTemperature(1)} \";\n  Debug.WriteLine($\"Humidity: {weather.Weather.Humidity}%\";\n  Debug.WriteLine($\"Feels Like: {weather.Weather.GetFeelsLikeTemperature(1)} \";\n  Debug.WriteLine($\"Dew Point: {weather.Weather.GetDewPoint(1)} \";\n}\n<\/pre>\n<p>We can even take it a step further and detect the user&#8217;s current activity, such as running or cycling, by requesting the Detected Activity:<\/p>\n<pre class=\"theme:vs2012 lang:csharp decode:true\">\nvar detectedActivity= await Awareness.SnapshotApi  .GetDetectedActivityAsync(client);\nif (detectedActivity?.Status?.IsSuccess ?? false)\n{\n  var probablyActivity = detectedActivity?.ActivityRecognitionResult ?.MostProbableActivity;\n  Debug.WriteLine(probablyActivity?.ToString() ?? \"No activity\"); \n}\n<\/pre>\n<h2>Learn More<\/h2>\n<p>The Awareness API is extremely powerful and at the same time extremely energy efficient when querying signals on the device. You can download a full source code example from my <a href=\"https:\/\/github.com\/jamesmontemagno\/xamarinawareness\">GitHub page<\/a> that walks through using each of the Snapshot APIs, and you can also learn more about the Awareness API from the <a href=\"https:\/\/developers.google.com\/awareness\/\">Google Developer portal<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Google Play services offers a plethora of amazing APIs for developers to integrate into their iOS and Android applications. For Android developers, specifically, there are several more APIs available that can give you even more power and integration with the Android OS when developing apps for the platform. One of the newest APIs, Awareness, brings [&hellip;]<\/p>\n","protected":false},"author":544,"featured_media":28933,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[5,4],"class_list":["post-28932","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-android","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Google Play services offers a plethora of amazing APIs for developers to integrate into their iOS and Android applications. For Android developers, specifically, there are several more APIs available that can give you even more power and integration with the Android OS when developing apps for the platform. One of the newest APIs, Awareness, brings [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/28932","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=28932"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/28932\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=28932"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=28932"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=28932"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}