Firebase Cloud Messaging Android Studio Tutorial

firebase cloud messaging android

You will need to work with Firebase Cloud Messaging Android example(FCM) for adding push notifications in android app.

Firebase Cloud Messaging Android Studio Tutorial guide you to integrate firebase push notification(FCM) in android studio.

In this Firebase Cloud Messaging Android Studio Tutorial, we will send notification from firebase console.

If you want to send notification from server(PHP-MySQL), then check Firebase push notification Android tutorial. 

If you want to send notification to multiple Android devices then check Android Firebase Push notification to multiple devices.

First, check output then we will develop Firebase Cloud Messaging Android Studio example(FCM).

Step 1: Create a new project in Android Studio.

If you select default activity as an empty activity while creating new project in android studio, it will be great choice.

Step 2: Creating app in Firebase Console

I have developed a video about how to make an app in the firebase console.

Quick steps of above video

  1. Go to https://firebase.google.com/ and sign in to your google account.
  2. Click on Add Project and give project name and country.
  3. Click on CREATE PROJECT button.
  4. After project is created, click on Add firebase to your Android app button.
  5. Give your Android package name and click on Register App button.
  6. Click on Download google-services.json button.
  7. Move your downloaded JSON file into app folder of your android project as shown in the video.

Step 3: Updating build.gradle(Project: project_name) file:

we need to add following in dependencies{} structure

classpath 'com.google.gms:google-services:3.1.0'

So final code for build.gradle(Project: project_name)  will look like this:

// 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:1.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

Step 4: Updating build.gradle(Module:app) file

Add following code into dependencies{}

compile 'com.google.firebase:firebase-messaging:9.0.2'

Add following at the end of the file

apply plugin: 'com.google.gms.google-services'

Final code for build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.exampledemo.parsaniahardik.simplefcm"
        minSdkVersion 16
        targetSdkVersion 22
        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.1.1'

    compile 'com.google.firebase:firebase-messaging:9.0.2'
}
apply plugin: 'com.google.gms.google-services'

Step 5: Creating Service Classes

Creating GettingDeviceTokenService

Create a new JAVA class named GettingDeviceTokenService”  and add below source code

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

/**
 * Created by Parsania Hardik on 09-Jun-17.
 */
public class GettingDeviceTokenService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String DeviceToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("DeviceToken ==> ",  DeviceToken);
    }

}
  • In this service, we will get device token.

Creating NotificationService

Create a new JAVA class named NotificationService” and add below source code

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;

/**
 * Created by Parsania Hardik on 09-Jun-17.
 */
public class NotificationService extends FirebaseMessagingService {

    public static  int NOTIFICATION_ID = 1;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        //Call method to generate notification
        generateNotification(remoteMessage.getNotification().getBody());
    }

    private void generateNotification(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 mNotifyBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Cloud or Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        if (NOTIFICATION_ID > 1073741824) {
            NOTIFICATION_ID = 0;
        }
        notificationManager.notify(NOTIFICATION_ID++ , mNotifyBuilder.build());
    }
}
  • We will receive message in this service.
  • You can also control title,icon, vibration, message tone etc. in this service.

Step 6: Updating AndroidManifest.xml

Add internet permission in AndroidManifest.xml 

<uses-permission android:name="android.permission.INTERNET"/>

Add services into <application> … </application> tags

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

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

Final code for AndroidManifest.xml 

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

    <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=".NotificationService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

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

    </application>

</manifest>

Step 7: Time to getting Notification

  • As you have seen in output video at the starting of the tutorial, get device token from logcat.
  • Now go to the firebase console and select your project.
  • Click on Notification from left menu bar.
  • Now type your message and select single device in Target.
  • Put device token into the FCM registration token field and click on Send Message -> Send
  • and…. ya you have push notification same as getting in WhatsApp or other app.

Feel free ask your questions and queries in comment section.

So all for firebase cloud messaging Android Studio programmatically example tutorial. Thank you.

Download Source Code For Firebase Cloud Messaging Android

[sociallocker]SimpleFCM [/sociallocker]