Simple Android Push Notification Example Using Firebase ( FCM ) in Android Studio

Please follow and like us:

Android Push Notification Tutorial Using Firebase

In Android Push Notification Example Using Firebase Tutorial, with the help of latest Firebase Cloud Messaging (FCM) we can easily send push notification without any cost. FCM is totally free and cross-platform push messages sending solution.

Step-by-step Example of sending Android push notification messages via FCM

Firebase Cloud Messaging Work Flow

Android Push Notification Tutorial Using Firebase

Firebase Cloud Messaging (FCM) implementation contains an app server that communicate with FCM using HTTP or XMPP protocol and client app. we can easily send messages using the Notifications Console GUI.

1. Create New Project in Firebase

 

  • First Open Google Firebase Developer Console.
  • Now click on “CREATE NEW PROJECT” button.
  • Add your preferred project name and country/region. 

 

Android Push Notification Tutorial Using Firebase

2. Add new firebase app

Now click on the “Add Firebase to your Android app“. Here you need to add your application package name then click on “ADD APP” button.

A file google-services.json is downloaded. Then click continue and then finish button.

Android Push Notification Tutorial Using Firebase

3. Add google-services.json file

Now open Android Studio and switch to the project view. Then add downloaded google-services.json file in your android app directory like bellow image.

Android Push Notification Tutorial Using Firebase

4. Add classpath to top level build.gradle

// 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.2'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

5. Add following plugin and dependencies in app’s build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.nkdroid.firebase.push"
        minSdkVersion 11
        targetSdkVersion 24
        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:24.0.0'
    compile 'com.google.firebase:firebase-core:9.4.0'                  // this line must be included to use FCM
    compile 'com.google.firebase:firebase-messaging:9.4.0'
}

6. Add following Firebase services in your java files

package com.nkdroid.firebase.push;

import android.util.Log;

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

public class FirebaseIDService extends FirebaseInstanceIdService {
    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}
package com.nkdroid.firebase.push;


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 = "FCM Service";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    }
}

7. Add following things in your AndroidMainifest.xml file

</pre>
<pre><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nkdroid.firebase.push">
    <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>

        <service android:name=".MyFirebaseMEssagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>


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

    </application>

</manifest></pre>
<pre>

Now you can send push notification to single devices, to groups of devices, or to devices subscribed to topics like bellow image.

Android Push Notification Tutorial Using Firebase

Note: When your application is in background then push message will occur in notification bar and when app is in foreground you will see push message in app’s logcat like bellow image.

Android Push Notification Tutorial Using Firebase

 

Final Words

Hope you liked our simple tutorial for implementing Android Push Notification using Firebase Cloud Messaging solution. Stay connected for new and simple Android tutorials…

nirav kalola