Click here to Skip to main content
15,119,116 members
Articles / Mobile Apps / Android
Technical Blog
Posted 29 Aug 2016

Tagged as

Stats

47.7K views
4 bookmarked

Android Firebase Cloud Messaging Tutorial

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
29 Aug 2016CPOL6 min read
Android Firebase Cloud Messaging Tutorial Hello Developers, We are back with a new android firebase tutorial. This time we will discuss about Firebase Cloud Messaging (FCM). We will be using Firebase to add cloud messaging in android app. What is Firebase Cloud Messaging? Firebase Cloud Messaging is

Hello Developers, We are back with a new android firebase tutorial. This time we will discuss about Firebase Cloud Messaging (FCM). We will be using Firebase to add cloud messaging in android app.

To download the full code for theFirebase Cloud Messaging app, go to the link below and click on Download Now Button.  Android Firebase Cloud Messaging Tutorial

What is Firebase Cloud Messaging?

Firebase Cloud Messaging is a powerful API that lets you deliver messages reliably and independent of the platform you are developing on. Using FCM, developers can notify the users that new data is available for sync and send notification messages. These are very useful for testing, sending marketing and engagement messages. It comes in with built-in targeting and analytics.

We can use Firebase Cloud Message for sending instant messages of upto 4KB in size.

A typical implementation of Firebase Cloud Messaging system will include an app server that interacts with FCM either using HTTP or XMPP protocol, and a client app. Messages and notifications can be sent to the client app using the app server or the Firebase notifications console. In a nutshell FCM makes android cloud messaging very easy even for beginners in android development.

In this tutorial we will create a simple android firebase cloud messaging app that will the user about firebase android login functionality. This post will help you get up and running with integrating Firebase Cloud Messaging to android. It will also act as an android notification tutorial since it we will talking about NotificationCompat for sending push notifications to your phone.

Adding Firebase Cloud Messaging

To add FCM to your app for push notifications using Firebase follow the below steps :

  1. Go to Firebase Website firebase.google.com and create a firebase account to start with. Go to Firebase console and Create a New Project by clicking on the “Create New Project” Button as shown below.

    Image 1

  2. Give the Project name and country you are currently in, Once you are done click on “Create Project” button.

    Image 2

  3. In the next screen choose “Add Firebase to your Android app” and then add the package details and Debug signing certificate SHA-1 key( This is required if you want to enable certain features like Dynamic Links, Invites, and Google Sign-In etc. otherwise it is an optional field).

    Image 3

    This will download the google-services.json file. Download it to your computer. We will add it to our android app later.

    Once you are done with this, We will create a client Android Application that will receive the notification from Firebase Cloud Messaging service.

    To prevent the project from having errors and issues like this, please ensure that you have gone through and implemented the following pre-requisites.

Pre-requisites

  1. Android Studio installed on your PC (Unix or Windows). For working with Firebase you should install Android Studio 1.5 or higher. Also download the latest Google Play services SDK from through Android SDK Manager.
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. The device should be running Android 2.3 (Gingerbread) or newer, and Google Play services 9.2.0 or newer.
  3. Firebase SDK should be added to your android project

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter company domain, this is used to uniquely identify your App’s package worldwide. Remember to use the same package name as used in the Firebase console.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves. Then click on Finish. We have used the Activity Name as MainActivity.

Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.

Add Permissions and Dependencies

  1. After Gradle syncs the project, add the google-services.json file to your project’s app folder as shown below.

    Image 4

  2. Since we need to connect to the Network add the Internet permission in AndroidManifest.xml file. Also add the Vibrate since we would be generating a notification alert on the android device.

    AndroidManifest.xml

    XML
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
  3. Also add the entry for a service that extends FirebaseMessagingService in order to handle the message after receiving notifications on apps in the background. We will extend this service. To receive notifications in apps. This is absolutely necessary for android push notifications to work while the app is not active.
    XML
    <service
        android:name=".MyAndroidFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
  4. Add an entry for a service that extends FirebaseInstanceIdService which will be used to handle the registration token lifecycle. This is required for sending messages to specific devices/device groups.
    XML
    <service
        android:name=".MyAndroidFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
  5. Also add an entry for a result activity, User will be taken to this activity on clicking on the notification. You may want to replace this activity with some special place in your app where you want to drive the user for example, sending the users to an offers page.
    XML
    <activity android:name=".ResultActivity"/>
    

    On completion your AndroidManifest.xml should look like this.

    AndroidManifest.xml

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.androidtutorialpoint.firebasecloudmessagingtutorial">
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.VIBRATE"/>
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".ResultActivity"/>
            <service
                android:name=".MyAndroidFirebaseMsgService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                </intent-filter>
            </service>
            <service
                android:name=".MyAndroidFirebaseInstanceIdService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
                </intent-filter>
            </service>
        </application>
    </manifest>
  6. Now open your project’s build.gradle from the project’s home directory and add the following dependency.

    build.gradle

    Java
    classpath 'com.google.gms:google-services:3.0.0'
    
  7. Next, open your app’s build.gradle from the and add the following at the end.

    build.gradle

    Java
    apply plugin: 'com.google.gms.google-services'
    
  8. To write the Firebase Cloud Messaging Android client app, we have to add FirebaseMessaging API : add the following dependencies in the dependency section in your app’s build.gradle
    Java
    compile 'com.google.android.gms:play-services:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.1'
    

Adding Functionality

  1. Create a new java class MyAndroidFirebaseMsgService and add the following code. It is a service that extends FirebaseMessagingService. It performs all kind of message handling in the background and sends the push notification once it is available.

    MyAndroidFirebaseMsgService

    Java
    package com.androidtutorialpoint.firebasecloudmessagingtutorial;
    
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;
    
    public class MyAndroidFirebaseMsgService extends FirebaseMessagingService {
        private static final String TAG = "MyAndroidFCMService";
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            //Log data to Log Cat
            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
            //create notification
            createNotification(remoteMessage.getNotification().getBody());
        }
    
        private void createNotification( String messageBody) {
            Intent intent = new Intent( this , ResultActivity. class );
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent,
            PendingIntent.FLAG_ONE_SHOT);
    
            Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle("Android Tutorial Point FCM Tutorial")
                            .setContentText(messageBody)
                            .setAutoCancel( true )
                            .setSound(notificationSoundURI)
                            .setContentIntent(resultIntent);
    
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            notificationManager.notify(0, mNotificationBuilder.build());
        }
    }

    On receiving a message onMessageReceived() is called. Inside this function we are logging the message to the LogCat console and calling the createNotification() with the message text. The createNotification() method will create a push notification in the android notification area as shown below.

    Image 5

    We are using NotificationCompat.Builder to create a new notification with default notification sound and passing the ResultActivity to the intent.

  2. Create a java class MyAndroidFirebaseInstanceIdService and add the following code. It is a service that extends FirebaseInstanceIdService and handles the creation, rotation, and updating of registration tokens. It makes sure theat the given message is sent to specific devices/device groups.

    MyAndroidFirebaseInstanceIdService

    Java
    package com.androidtutorialpoint.firebasecloudmessagingtutorial;
    
    import android.util.Log;
    import com.google.firebase.iid.FirebaseInstanceId;
    import com.google.firebase.iid.FirebaseInstanceIdService;
    
    public class MyAndroidFirebaseInstanceIdService extends FirebaseInstanceIdService {
    
        private static final String TAG = "MyAndroidFCMIIDService";
    
        @Override
        public void onTokenRefresh() {
            //Get hold of the registration token
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            //Log the token
            Log.d(TAG, "Refreshed token: " + refreshedToken);
        }
        private void sendRegistrationToServer(String token) {
            //Implement this method if you want to store the token on your server
        }
    }

    The onTokenRefreshcallback fires on generation of a new token. We are calling getToken() in the context of onTokenRefresh() to ensure that we are accessing a currently available registration token.

    Then we are simply logging the refreshed Token.

  3. Open activity_main.xml add the following code. We have only one TextView just to display the activity name.

    activity_main.xml

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".MainActivity">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1"
            android:text="Welcome to Main Activity"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textStyle="bold"
            android:layout_marginTop="100dp"
            android:textAlignment="center" />
    </LinearLayout>

    MainActivity.java

    Java
    package com.androidtutorialpoint.firebasecloudmessagingtutorial;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }
  4. Create a new Activity ResultActivity.java and put the following code.

    ResultActivity.java

    Java
    package com.androidtutorialpoint.firebasecloudmessagingtutorial;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.TextView;
    
    public class ResultActivity extends AppCompatActivity {
        private TextView textView ;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textView = (TextView)findViewById(R.id.textView1);
            textView.setText("Welcome to the Result Activity");
        }
    }

    We are reusing the layout activity_main.xml for the result activity and just changing the Text to “Welcome to the Result Activity”. This activity will be called when the user will click on the Notification received.

    Now the app is complete, we will test the app by sending a notification from the Firebase Notifications panel.

    Log on to Firebase console then follow the steps in the images.Image 6

    Image 7

    This will generate a new Notification message on your android device as shown below.Image 8

    Congrats!! You have successfully integrated Firebase Cloud Messaging to Android Application for messaging and push notifications. You can see all the messages in the notifications panel in the firebase console.

    Image 9

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andy Point
Software Developer (Senior)
India India
Hello Developer!

As a co-founder, I would like to welcome you to the Android Tutorial Point community!. I hope you get the best possible value at of our platform. Stick with us for a while, and we promise you will become an $$Android Rockstar$$!

Android Tutorial Point is the right platform if you want to learn about android development. We have a broad collection of tutorials on different aspects of Android Development and it is growing rapidly. Here at Android Tutorial Point we thrive to deliver the best tutorials. In this direction, we are trying to create a community that will cater to your needs, whether you are a beginner or a seasoned veteran. For the beginners that are getting started on Android Development
journey, we would suggest you to begin with our Android Basics Tutorial available at http://www.androidtutorialpoint.com/category/basics/ . Here, we feature articles on how to start with Android programming.


All the best from the Android Tutorial Point team. Don't forget to subscribe our blog for latest android tutorials. You can reach out to us at our Facebook page https://www.facebook.com/androidtutorialpoint/ or Add us on Twitter https://twitter.com/androidtutpoint/ . Any ideas or suggestions? Shoot us an email at androidtutorialspoint@gmail.com

Comments and Discussions

 
Questionfor android firebase cloudmessaging Pin
Member 128408699-Nov-16 1:03
MemberMember 128408699-Nov-16 1:03 
QuestionThanks Pin
BrunoPichon29-Aug-16 9:37
MemberBrunoPichon29-Aug-16 9:37 
It helps me a lot, thanks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.