Home Android Tutorial How to Use Firebase Cloud Messaging for Android App

How to Use Firebase Cloud Messaging for Android App

0
How to Use Firebase Cloud Messaging for Android App
Firebase Cloud Messaging for Android App

Push Notification also knows as Messaging service for android app is the best way for the app developer to be in contact with Application user. Firebase is recently launched by Google with a number of services, You can learn what is Google Firebase from link article. Firebase Cloud messaging service is alternative to old GCM and Firebase is far easy and simple to implement in Android App.

Firebase Cloud Messaging provide user dashboard to send the push notification with the different option like sending the notification to a single android device to the specific version of your deploy android app on Google Play store. In this Firebase Cloud Messaging Tutorial, you will learn how to implement Firebase Notification service in Android App developed in Android Studio and also how to send the push notification to single android devices using Firebase Cloud Messaging.  Here we start our tutorial, so fix your seat belts.

Firebase Cloud Messaging Tutorial

Firebase Cloud Messaging Tutorial

Creating Firebase Cloud Messaging account

Go to firebase console and create a new project.

Create Firebase Project For Android App

Add your Firebase App name and select your country.

Firebase Android Notification Project

Now click on Add Firebase to your Android App

Add Firebase to Android App

Create Android App for Firebase Cloud Notification

Start Android Studio and Configure Android App Project for Firebase cloud messaging service.

Create Android Firebase Cloud Messaging App

Now select the device for which you want to develop App and choose the lowest version for the supporting device. For Firebase cloud messaging service, there is no restriction of Android API, we can use any lowest version but it should support Google play services.

Copy package name of your android app project and now return to the Firebase Console and enter your package name as shown below. Note: you can leave Debug signing certificate SHA-1 as it is the optional option.

Add package name to Firebase Android App

After clicking add app you will get google-services.JSON file.

How to Add Firebase Messaging to Your Project

Adding Firebase Messaging to Your Project

As you are now in your android app project paste the file google-services.json to app folder of your project.

Now you have to make few changes in your root level build.gradle file by adding the following code.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

        //Add this line
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Inside app level build.gradle file makes the following changes.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "buzzmycode.com"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

    //Add this line 
    compile 'com.google.firebase:firebase-messaging:9.0.0'
}

//Add this line
apply plugin: 'com.google.gms.google-services'

Finally Sync Your Android Project.

Implementing Firebase Cloud Messaging

Create a class named MyFirebaseInstanceIDService.java and write the following code.

package buzzmycode.com;


import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


//Class extending FirebaseInstanceIdService
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {
        
        //Getting registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        
        //Displaying token on logcat 
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        
    }

    private void sendRegistrationToServer(String token) {
        //You can implement this method to store the token on your server 
        //Not required for current project 
    }
}

Now create MyFirebaseMessagingService.java and write the following code.

package buzzmycode.com;


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 MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional 
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        
        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody());
    }

    //This method is only generating push notification
    //It is same as we did in earlier posts 
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

Now we have to define the above services in our AndroidManifest.xml file. So go to manifest and modify as follows.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="buzzmycode.com">

    <!-- Adding Internet Permission -->
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <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>

        <!-- 
            Defining Services
        -->
        <service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>

</manifest>

Now sync your android project and start Emulator to check the project is working. If you use proper coding as I shown above then it will run without any error.

Sending Push Notification using Firebase Console

  • Go to firebase console and select the app you created.
  • From the left menu select notification.
  • Click on the new message.
  • Enter message, select single device and paste the token you copied and click on send. The same as I did on the video, and check your device

Hope you apply everything exactly as detailed in the tutorial, enjoy creating the new android app. If you have any suggestion or query then ping us.