Main navigation

Android Firebase Cloud Messaging Tutorial

adsense

Pre-requisites for Firebase Cloud Messaging :

  1. Android Studio installed on your PC (Unix or Windows). For working with Firebase you should install Android Studio 1.5 or higher. You can learn how to install it here . 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, follow the instructions here Firebase Android Tutorial Part 1 – Getting Started

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.
  2. Firebase Tutorial -add google-services.json

  3. 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.
  4. AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    
  5. 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.
  6. <service
        android:name=".MyAndroidFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    
  7. 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.
  8. <service
        android:name=".MyAndroidFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    
  9. 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.
  10.  <activity android:name=".ResultActivity"/>
    

    On completion your AndroidManifest.xml should look like this.

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="https://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>
    
  11. Now open your project’s build.gradle from the project’s home directory and add the following dependency.
  12. build.gradle

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

    	apply plugin: 'com.google.gms.google-services'
    
  15. 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
  16.     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.
  2. MyAndroidFirebaseMsgService

    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.

    fcm11

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

  3. 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.
  4. MyAndroidFirebaseInstanceIdService

    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.

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

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:app="https://schemas.android.com/apk/res-auto"
        xmlns:tools="https://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>
    
  7. The content of the MainActivity will stay as the default.
  8. MainActivity.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);
        }
    }
    
  9. Create a new Activity ResultActivity.java and put the following code.
  10. ResultActivity.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.
    Firebase Notifications Console

    fcm9

    This will generate a new Notification message on your android device as shown below.
    Firebase Push Notification

    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.

    fcm10



    What’s Next ??

    After creating the Firebase Cloud Messaging app example, you can also work on setting up an HTTP or XMPP server to interact with the clients app, experiment with more engaging and complex notification messages.

    We hope you liked our Firebase Cloud Messaging example tutorial, please leave comments in the comment section below in case of any doubts.

    You can also learn how to use Firebase real time database with your android app.
    in the our Firebase Database Tutorial.

    Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

    To download the full code for theFirebase Cloud Messaging app, Click on the Download Now link below.

    Android Tutorial Point Download Now


Reader Interactions

Comments

  1. @Kapil Thanks for the tutorial , i have been searching for FCM Click_action tutorial, your’s helped me accomplished it. Please how can i change the notification icon or better still customize the notification View.

    Best Regards.

  2. App crash after send message. [Service com.android.email.service.EmailBroadcastProcessorService has leaked ServiceConnection…]. Please tell me, why?

  3. hello,i have implemented every part as shown in this tutorial but still i am not been able to get notifications.Please let me know why it is happening

  4. Hello friends.
    I was looking information about how to implement an FCM service and it has been a pleasure to find this tutorial
    It works perfectly!
    Thanks

  5. Android firebase cloud messaging is really great topic to discuss and you have written great information over here.

    I enjoyed it!

  6. Your every articles on firebase subject are interesting to read.

    I will surely share your blog on social media platforms.

  7. hello,
    thank you for this tutorial, I have do the same as you did but don’t work for me.
    i don’t know if my emulator is the problem or my gridll file configuration.
    Can you give me a help plz ?

  8. The tutorial is great, but I ran into a really weird problem. Maybe someone can help me out.

    When I use .setSmallIcon() and .setContentTitle() my emulator shows exactly the icon and title I have provided. But when I run the application on my own smartphone, it takes android:icon= android:label= as values for icon and title.

    Thanks

  9. suppose my application is already open then how i set the notification text in TextView. without clicking on notification.

  10. Hi,
    Thank you for this.This is a good example to start with FCM. I am facing once issue in this. I want to display the notification message in my main acitiviy when click on the notification that is send by FCM console. This works fine when the app is running in the foreground, but if the app is in the background and I am clicking on the notification, then activity is opening but the message is not dispalying in the main activity.

    Can you please help me in this?

    Thanks in Advance.

  11. This worked for me after a couple minor tweaks:
    a) Steps 3 and 4 of “Add Permissions and Dependencies”, the service names are not correct and don’t match the remainder of the tutorial.
    b) The namespaces in the XML files must replace “https” with “http”
    c) Not sure if this is the case for everybody, but I had to add MultiDex support.

Leave a Reply

Advertisment ad adsense adlogger