Implementing push notifications in Android apps

Source: Internet
Author: User
Tags home screen

An important feature of almost every application is the ability to support push notifications. With push notifications, you can update users without requiring the application to run or poll the server at any time to avoid potential battery power shortages. With the introduction of Firebase Cloud Information (FCM), Google makes it easy to implement push notifications in Android applications. FCM is a new version and an improved version of Google Cloud Messaging (GCM) that you can use to send remote notifications to the client application. For applications that will target multiple platforms or need to take advantage of advanced push operations such as segmented push, we can use FCM with the Azure notification hub.

Unlike GCM, FCM is responsible for providing you with a basic message delivery pipeline. With FCM, you no longer need to write code to register your application, and you do not have to include retry logic to update the subscription token. You can add basic FCM push notifications to your application by doing the following:

    1. Install the Xamarin.android nugets package and a certificate file.

    2. Add a pair of <service> definitions to your ndroidmanifest.xml.

    3. Write a few lines of code to combine them all together.

Also, instead of writing a test program that sends notifications, you can use the new Web-based Firebase console to send notifications to your application tests.

Today, let's look at how to use the Xamarin.Firebase.Messaging package to build an FCM-based message notification feature into your app

Build Firebase Cloud Messaging

Before you can use the FCM service in your application, you create a firebase project from the Firebase console. After you log in, click Create NEWproject, enter the project name, and click Createprojects:

650) this.width=650; "class=" Alignnone size-full wp-image-31070 "src=" https://s3.amazonaws.com/blog.xamarin.com/ Wp-content/uploads/2017/04/18132658/01-create-project.png "width=" 907 "height=" 404 "/>

Next, click Add Firebase to your Android app. When prompted, enter the application's package name and click Register Application:

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/24120408/ Screen-shot-2017-04-24-at-20.01.571.png "class=" AlignCenter size-full wp-image-31155 "width="-height= "334"/>
650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/24120409/ Screen-shot-2017-04-24-at-19.57.001.png "class=" AlignCenter size-full wp-image-31156 "width=" 521 "height=" 431 "/>

When you click on the register APP, the certificate is automatically generated so that your app can access the Firebase server. The certificate is packaged into a file called Google-services.json , and when you click the REGISTER APP button, the certificate is automatically downloaded, the file is saved, and you will use it later.

Add a package to a project

Next, you need to add two Xamarin NuGet packages to your app. Start the NuGet Package Manager (in Visual Studio, right-click References in the Solution browser and select Manage NuGet Packages) to browse Xamarin.GooglePlayServices.Base, select it, and click Install.

650) this.width=650; "class=" Alignnone size-full wp-image-31072 "src=" https://s3.amazonaws.com/blog.xamarin.com/ Wp-content/uploads/2017/04/18132922/03-gps-nuget.png "width=" 1154 "height=" 161 "/>

The Google Play Services package must is installed in order for FCM to work. Next, do the same for Xamarin.Firebase.Messaging:

650) this.width=650; "class=" Alignnone size-full wp-image-31073 "src=" https://s3.amazonaws.com/blog.xamarin.com/ Wp-content/uploads/2017/04/18133008/04-fbm-nuget.png "width=" 1162 "height=" 154 "/>

Additional dependency packages will be installed for each of these packages.

Also, make sure you install and have Google Play Services APK on your anroid device. Firebase messages use Google Play surge apk and Firebase server communication.

Add a Google services JSON file to your project

When you create a project in the Firebase console, you will download the Google-services.json certificate file and now insert it into your app!

Copy the Google-services.json project folder and add it to the project (in Visual Studio, you can click the Show all Files icon in the browser solution, right-click Google-services.json, then select Include in Project).

Save to become and close the solution. Reopen the solution and set the build behavior for Google-services.json to Googleservicesjson (in Visual Studio, Build Action Pop-up menu in the Properties page of the Advanced section):

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/18133307/05- Build-action.png "class=" AlignCenter size-full wp-image-31074 "width=" 349 "height=" 241 "/>

Now that Google-services.json is part of the project, Xamarin build processing can extend the certificate and merge it into the androidmanifest.xml file. Xamarin.Firebase.Messaging uses this certificate to access the Firebase service.

Add an Instance ID sink

Your client application must register FCM before it can receive push notifications. This is the Xamarin.Firebase.Messaging contact FCM method, which sends its certificate and receives the message returned by the registration token ring. This truth, this is regularly updated to create a secure channel for firebase servers. You can also forward this token to your application server, which can be served with the firebase.

Your app must implement Firebaseinstanceidservice to handle creating and updating information loops. This is actually much simpler than it sounds, and then you'll see.

Declaring an instance ID sink in an android manifest

Edit androidmanifest.xml ( Click Properties in the Solution browser ) and insert into <application> section after the <receiver> element:

Click ( here ) to collapse or open

  1. <Receiver

  2. Android:name="Com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"

  3. android:exported="false" />

  4. <Receiver

  5. Android:name="Com.google.firebase.iid.FirebaseInstanceIdReceiver"

  6. android:exported="true"

  7. Android:permission="Com.google.android.c2dm.permission.SEND">

  8. <intent-filter>

  9. <action Android:name="Com.google.android.c2dm.intent.RECEIVE" />

  10. <action Android:name="Com.google.android.c2dm.intent.REGISTRATION" / >

  11. <category Android:name="${applicationid}" />

  12. < /intent-filter>

  13. < /receiver>


This declares the necessary recipients to manage the registration tokens.


Increase access to the Internet

If your permissions list does not have INTERNET rights enabled, enable it in Properties > Android Manifest > Required Permissions :

650) this.width=650; "class=" AlignCenter size-full wp-image-31075 "src=" https://s3.amazonaws.com/blog.xamarin.com/ Wp-content/uploads/2017/04/18134200/06-internet-permissions.png "width=" 486 "height=" 248 "/>

Implement Firebase Instance ID service

Now it's time to write the code! Add a new CE file to your project (in Visual Studio, right-click the project name and select Add > New item > Class). Name it MyFirebaseIIDService.cs and enter the following code:

Click ( here ) to collapse or open

  1. using System ;

  2. using Android. APP;

  3. using Firebase. Iid;

  4. using Android. Util;


  5. namespace Fcmexample

  6. {

  7. [Service]

  8. [intentfilter(new[] { "Com.google.firebase.INSTANCE_ID _event " })]

  9. Public class Myfirebaseiidservice : firebaseinstanceidservice

  10. {

  11. Const string TAG = "Myfirebaseiidservice";

  12. Public Override void Ontokenrefresh()

  13. {

  14. var refreshedtoken = Firebaseinstanceid. Instance . Token;

  15. Log. Debug (TAG, "Refreshed token:" + refreshedtoken) ;

  16. }

  17. }

  18. }



Change the namespace fcmexample for the namespace you apply.

That's all it is!

Executes the Ontokenrefresh method when the registered token is created or changed. Since the token output log to the Output window when It is updated, you can confirm that the app is running. You will enter the token into the Firebase console when you want to improve a test notification to your app.

Now that your application has enough functionality to receive background notifications from streaming media, it's time to test. Before you build your app, make sure that the app package name matches the package name that you entered when you created your Firebase project in the Firebase console.

Re-build your app, run it, and watch the output window until the token information is displayed. For example:

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/18134451/07- Token.png "class=" Alignnone size-full wp-image-31076 "width=" 1005 "height=" "/>"

Copy this token to the Clipboard, and in the following steps you will paste it into the Firebase console.

Send Message

Log in to the Firebase console, select your project, click Notifications, and then click SEND YOUR first MESSAGE:

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/18134513/08- First-message.png "class=" Alignnone size-full wp-image-31077 "width=" + height= "559"/>

On the Compose Message page, enter a message in the text in message. Select single device as the target and paste the token information that you copied from the IDE Output window into the registration token box:

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/18134755/09- Compose-message.png "class=" AlignCenter size-full wp-image-31080 "width="/>

Before clicking send MESSAGE , switch the app to run in the background (you can touch the Android Overview button and click on the Home screen). Click SEND MESSAGEWhen you are ready to firebase the console. When the Review Message dialog box is displayed, click SEND. The notification icon will appear on your Android device:

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/18134605/10- Notification-icon.png "class=" AlignCenter size-full wp-image-31078 "width="-/>

Open the notification view message; The notification message should be exactly what you entered in the Firebase console:

650) this.width=650; "Src=" https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/04/18134903/11- Notification-text.png "class=" AlignCenter size-full wp-image-31081 "width="-/>

Congratulations, you just sent and received the first FCM push notification!

Learn More

This simple example involves only the work that you can do with FCM and push notifications in Visual Studio. To learn more about using Xamarin.android in Visual Studio and other platforms, using the Firebase cloud messaging service, be sure to read Firebase cloud Messaging and remote notifications  With Firebase Cloud Messaging. Fcmnotifications sample Application or if you build an application, use FCM's push notification to borrow code from a good place.


This article from "Wangccsy" blog, reproduced please contact the author!

Implementing push notifications in Android apps

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.