{"id":31069,"date":"2017-04-24T13:51:39","date_gmt":"2017-04-24T20:51:39","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=31069"},"modified":"2019-04-04T08:33:10","modified_gmt":"2019-04-04T15:33:10","slug":"implementing-push-notifications-android-apps","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/implementing-push-notifications-android-apps\/","title":{"rendered":"Implementing Push Notifications in Your Android Apps"},"content":{"rendered":"<p>\t\t\t\tAn important feature of almost every app is the ability to support push notifications. With push notifications, you can update your users without requiring the app to run at all times or having it poll a server, potentially running down the battery. With the introduction of Firebase Cloud Messaging (FCM), Google made it a little bit easier to implement push notifications in Android apps. FCM is the new and improved version of Google Cloud Messaging (GCM) that you can use to send remote notifications to your client app. For apps that will be targeting multiple platforms or need to take advantage of advanced push operations (like segmented push), we can use FCM with <a href=\"https:\/\/azure.microsoft.com\/en-us\/services\/notification-hubs\/\">Azure Notification Hubs<\/a>.<\/p>\n<p>Unlike GCM, FCM takes care of most of the underlying messaging plumbing for you. With FCM, you no longer have to write code to register your app or include retry logic to update subscription tokens. You can add basic FCM push notifications to your app by doing the following:<\/p>\n<ol style=\"list-style-type: decimal\">\n<li>Install a couple of Xamarin.Android NuGets and a credentials file.<\/li>\n<li>Add a couple of <code>&lt;service&gt;<\/code> declarations to your <strong>AndroidManifest.xml<\/strong>.<\/li>\n<li>Write a few lines of code to pull it all together.<\/li>\n<\/ol>\n<p>Also, instead of writing a test program to send notifications, you can use the new web-based Firebase Console to send test notifications to your app.<\/p>\n<p>Today, we&#8217;ll take a look at how to use the <a href=\"https:\/\/www.nuget.org\/packages\/Xamarin.Firebase.Messaging\/\" target=\"_blank\">Xamarin.Firebase.Messaging<\/a> package to build FCM-based push notification features into your app.<\/p>\n<h2 id=\"setup-firebase-cloud-messaging\">Set Up Firebase Cloud Messaging<\/h2>\n<p>Before you can use FCM services in your app, you have to create a <em>Firebase Project<\/em> in the <a href=\"https:\/\/console.firebase.google.com\/\" target=\"_blank\">Firebase Console<\/a>. After you log in, click <strong>CREATE NEW PROJECT<\/strong>, enter a project name, and click <strong>CREATE PROJECT<\/strong>:<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-31070\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/01-create-project.png\" alt=\"\" width=\"907\" height=\"404\" \/><\/p>\n<p>Next, click <strong>Add Firebase to your Android app<\/strong>. When prompted, enter the package name for your app and click <strong>REGISTER APP<\/strong>:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screen-Shot-2017-04-24-at-20.01.571.png\" alt=\"\" width=\"600\" height=\"334\" class=\"aligncenter size-full wp-image-31155\" \/><br \/>\n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screen-Shot-2017-04-24-at-19.57.001.png\" alt=\"\" width=\"521\" height=\"431\" class=\"aligncenter size-full wp-image-31156\" \/><\/p>\n<p>When you click <strong>REGISTER APP<\/strong>, credentials are automatically generated for your app to access Firebase servers. These credentials are packaged in a file called <strong>google-services.json<\/strong>, which is automatically downloaded after you click the <strong>REGISTER APP<\/strong> button. Save this file, as you&#8217;ll need it later!<\/p>\n<h2 id=\"add-packages-to-your-project\">Add Packages to Your Project<\/h2>\n<p>Next, you&#8217;ll need to add two Xamarin NuGet packages to your app. Start the <strong>NuGet Package Manager<\/strong> (in Visual Studio, right-click <strong>References<\/strong> in the Solution Explorer and select <strong>Manage NuGet Packages<\/strong>), browse for <strong>Xamarin.GooglePlayServices.Base<\/strong>, select it, and click <strong>Install<\/strong>.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-31072\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/03-gps-nuget.png\" alt=\"\" width=\"1154\" height=\"161\" \/><\/p>\n<p>The Google Play Services package must be installed in order for FCM to work. Next, do the same for <strong>Xamarin.Firebase.Messaging<\/strong>:<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-31073\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/04-fbm-nuget.png\" alt=\"\" width=\"1162\" height=\"154\" \/><\/p>\n<p>Extra dependency packages will be installed for each of these packages.<\/p>\n<p>Also, make sure that you have the <a href=\"https:\/\/play.google.com\/store\/apps\/details?id=com.google.android.gms&amp;hl=en\" target=\"_blank\">Google Play Services<\/a> APK installed on your Android device. Firebase Messaging uses the Google Play Services APK to communicate with Firebase servers.<\/p>\n<h2 id=\"add-the-google-services-json-file-to-your-project\">Add the Google Services JSON File to Your Project<\/h2>\n<p>When you created a new project in the Firebase Console, you downloaded a <strong>google-services.json<\/strong> credentials file&ndash;it&#8217;s time to plug that file into your app!<\/p>\n<p>Copy <strong>google-services.json<\/strong> to your project folder and add it to your project (in Visual Studio, you can click the <strong>Show All Files<\/strong> icon in the <strong>Solution Explorer<\/strong>, right-click <strong>google-services.json<\/strong>, then select <strong>Include in Project<\/strong>).<\/p>\n<p>Save changes and <strong>close<\/strong> the Solution. <strong>Re-open<\/strong> the Solution and set the Build Action for <strong>google-services.json<\/strong> to <strong>GoogleServicesJson<\/strong> (in Visual Studio, the <strong>Build Action<\/strong> pull-down menu is in the <strong>Advanced<\/strong> section of the <strong>Properties<\/strong> pane):<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/05-build-action.png\" alt=\"\" width=\"349\" height=\"241\" class=\"aligncenter size-full wp-image-31074\" \/><\/p>\n<p>Now that <strong>google-services.json<\/strong> is part of your project, the Xamarin build process can extract the credentials and merge them into the generated <strong>AndroidManifest.xml<\/strong> file. <strong>Xamarin.Firebase.Messaging<\/strong> uses these credentials to access Firebase services.<\/p>\n<h2 id=\"add-an-instance-id-receiver\">Add an Instance ID Receiver<\/h2>\n<p>Your client app has to first register with FCM before it can receive push notifications. The way this works is that <strong>Xamarin.Firebase.Messaging<\/strong> contacts FCM, sends it credentials, and gets back a <em>registration token<\/em>. This token, which is updated on a regular basis, is used to create a secure channel to Firebase servers. You can also forward this token to your app server so that it can communicate with Firebase.<\/p>\n<p>Your client app must implement a <code>FirebaseInstanceIdService<\/code> to handle the creation and updating of registration tokens. This is actually a lot simpler than it sounds, as you&#8217;ll see next.<\/p>\n<h3 id=\"declare-the-instance-id-receiver-in-the-android-manifest\">Declare the Instance ID Receiver in the Android Manifest<\/h3>\n<p>Edit <strong>AndroidManifest.xml<\/strong> (under <strong>Properties<\/strong> in the Solution Explorer) and insert the following <code>&lt;receiver&gt;<\/code> elements into the <code>&lt;application&gt;<\/code> section:<\/p>\n<pre><code>\n\n    \n        \n        \n        \n    \n<\/code><\/pre>\n<p>This declares the necessary receivers that will be used for managing registration tokens.<\/p>\n<h3 id=\"add-internet-permissions\">Add Internet Permissions<\/h3>\n<p>If your app does not already have the <code>INTERNET<\/code> permission enabled, enable it under <strong>Properties &gt; Android Manifest &gt; Required permissions<\/strong>:<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-31075\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/06-internet-permissions.png\" alt=\"\" width=\"486\" height=\"248\" \/><\/p>\n<h3 id=\"implement-the-firebase-instance-id-service\">Implement the Firebase Instance ID Service<\/h3>\n<p>Now it&#8217;s time to write some code! Add a new C# file to your project (in Visual Studio, right click your project name and select <strong>Add &gt; New Item &gt; Class<\/strong>). Give it the name <strong>MyFirebaseIIDService.cs<\/strong> and input the following code:<\/p>\n<pre><code>using System;\nusing Android.App;\nusing Firebase.Iid;\nusing Android.Util;\n\nnamespace FCMExample\n{\n    [Service]\n    [IntentFilter(new[] { \"com.google.firebase.INSTANCE_ID_EVENT\" })]\n    public class MyFirebaseIIDService : FirebaseInstanceIdService\n    {\n        const string TAG = \"MyFirebaseIIDService\";\n        public override void OnTokenRefresh()\n        {\n            var refreshedToken = FirebaseInstanceId.Instance.Token;\n            Log.Debug(TAG, \"Refreshed token: \" + refreshedToken);\n        }\n    }\n}<\/code><\/pre>\n<p>Change the namespace <code>FCMExample<\/code> above to the namespace of your app.<\/p>\n<p>That&#8217;s all there is to it!<\/p>\n<p>The <code>OnTokenRefresh<\/code> method is invoked when the registration token is created or changed. Because the token is logged to the <strong>Output<\/strong> window whenever it&#8217;s updated, you&#8217;ll be able to see it while the app is running. You&#8217;ll enter this token into the Firebase Console when you&#8217;re ready to send a test notification to your app.<\/p>\n<h1 id=\"try-it\">Try it!<\/h2>\n<p>Now that your app has enough functionality to receive background notifications from FCM, it&#8217;s time for a test drive. Before you build your app, make sure that its package name matches the package name that you entered into the Firebase Console when you created your Firebase project.<\/p>\n<p>Rebuild the app, run it, and watch the <strong>Output<\/strong> window until the token is displayed. For example:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/07-token.png\" alt=\"\" width=\"1005\" height=\"128\" class=\"alignnone size-full wp-image-31076\" \/><\/p>\n<p>Copy this token to the clipboard; you&#8217;ll paste it into the Firebase Console in the next step.<\/p>\n<h2 id=\"send-a-message\">Send a Message<\/h2>\n<p>Sign in to the <a href=\"https:\/\/console.firebase.google.com\/\" target=\"_blank\">Firebase Console<\/a>, select your project, click <strong>Notifications<\/strong>, and click <strong>SEND YOUR FIRST MESSAGE<\/strong>:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/08-first-message.png\" alt=\"\" width=\"1352\" height=\"559\" class=\"alignnone size-full wp-image-31077\" \/><\/p>\n<p>On the <strong>Compose message<\/strong> page, enter in a message under <strong>Message text<\/strong>. Select <strong>Single device<\/strong> as the target and paste in the registration token that you copied from the IDE <strong>Output<\/strong> window:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/09-compose-message.png\" alt=\"\" width=\"350\" class=\"aligncenter size-full wp-image-31080\" \/><\/p>\n<p>Before you click <strong>SEND MESSAGE<\/strong>, background your app (you can tap the Android overview button and touch the home screen). Click <strong>SEND MESSAGE<\/strong> in the Firebase Console when you&#8217;re ready. When the <strong>Review message<\/strong> dialog is displayed, click <strong>SEND<\/strong>. The notification icon should appear on the Android device:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/10-notification-icon.png\" alt=\"\" width=\"400\" class=\"aligncenter size-full wp-image-31078\" \/><\/p>\n<p>Open the notification to view the message; the notification message should be exactly what you typed into the Firebase Console:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/11-notification-text.png\" alt=\"\" width=\"400\" class=\"aligncenter size-full wp-image-31081\" \/><\/p>\n<p>Congratulations, you&#8217;ve just sent and received your first FCM push notification!<\/p>\n<h2 id=\"learn-more\">Learn More<\/h2>\n<p>This simple example only touches the surface of what you can do with FCM and push notifications using Visual Studio. To learn more about Firebase Cloud Messaging with Xamarin.Android for Visual Studio and other platforms, be sure to read <a href=\"https:\/\/developer.xamarin.com\/guides\/android\/application_fundamentals\/notifications\/firebase-cloud-messaging\/\" target=\"_blank\">Firebase Cloud Messaging<\/a> and <a href=\"https:\/\/developer.xamarin.com\/guides\/android\/application_fundamentals\/notifications\/remote-notifications-with-fcm\/\" target=\"_blank\">Remote Notifications with Firebase Cloud Messaging<\/a>. The <a href=\"https:\/\/developer.xamarin.com\/samples\/monodroid\/Firebase\/FCMNotifications\/\" target=\"_blank\">FCMNotifications<\/a> sample app is also a good place to borrow code from if you&#8217;re building an app that uses FCM push notifications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An important feature of almost every app is the ability to support push notifications. With push notifications, you can update your users without requiring the app to run at all times or having it poll a server, potentially running down the battery. With the introduction of Firebase Cloud Messaging (FCM), Google made it a little [&hellip;]<\/p>\n","protected":false},"author":555,"featured_media":31081,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[5,4,16],"class_list":["post-31069","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-android","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>An important feature of almost every app is the ability to support push notifications. With push notifications, you can update your users without requiring the app to run at all times or having it poll a server, potentially running down the battery. With the introduction of Firebase Cloud Messaging (FCM), Google made it a little [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/31069","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\/555"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=31069"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/31069\/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=31069"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=31069"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=31069"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}