Firebase Cloud Messaging

Firebase Cloud Messaging Tutorial Android

firebase cloud messaging

What’s Firebase Cloud Messaging (FCM)?

Firebase Cloud Messaging (FCM) is a robust API that enables you to deliver emails/messages reliably and in addition to the program you are growing on. Using FCM, programmers can inform the users that new data is designed for sync and send notification text messages. These are incredibly useful for assessment, mailing marketing and proposal messages. It will come in with built-in targeting and analytics.

We are able to use Firebase Cloud Meaning (FCM) for instant messages of upto 4KB in proportions.

A typical execution of Firebase Cloud Messaging (FCM) system includes an software server that interacts with FCM either using HTTP or XMPP process, and a customer/client app. Text messages and notifications can be delivered to the client app using the software server or the Firebase notifications system/console. The bottom line is FCM makes android cloud messaging super easy even for newcomers in android development.

Firebase Cloud Messaging Pricing

Firebase Cloud Messaging which is generally known as FCM is a cross-platform messaging solution that enables you to reliably deliver messages free thus firebase cloud messaging has no cost at all. You are able to send notification information to drive customer reengagement and retention.Using FCM, you can inform a client app that new email or other data is open to sync.

In this Firebase cloud messanging (FCM) tutorial we will generate a simple android os firebase cloud messaging app that will an individual about firebase android login features. This post can help you get right up and running with integrating Firebase Cloud Messaging (FCM) to android. It will become an android notification article since it we will discussing NotificationCompat for mailing press notifications to your mobile phone.

Hello friends we’ve protected a some training with Google Cloud Messaging (GCM) however now google comes with an alternative which is simpler than gcm. In this article we use FCM (Firebase Cloud Messaging). So today in this Firebase Cloud Messaging (FCM) Guide I will educate you on how to send force notification to solitary android devices using Firebase Cloud Messaging (FCM). So let us begin.

Firebase Cloud Messaging Tutorial

Creating an Android os Studio Project

Even as we do always in previous tutorials. Create a fresh android studio task. Once the task is loaded duplicate the package deal name you can obtain it from the AndroidManifest.xml file.

  • Head to firebase console and create a fresh project.
  • Now put your app name and choose your country.

firebase cloud messaging

  • Now select Add Firebase for your Android App.

firebase cloud messaging

  • You now have to enter in your projects package name(mine com.androdevelopment.fcmdemo) and select ADD APP.

firebase cloud messaging

  • After visiting add application you’ll get google-services.json.

Adding Firebase Messaging to ASSEMBLING YOUR PROJECT

  • Now get back to your android job. Go to app folder and paste google-services.json.

firebase cloud messaging

go to your root level build.gradle record and add the next 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 data file make the next changes.
apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
 
    defaultConfig {
        applicationId "com.androdevelopment.firebasecloudmessaging"
        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'

 

  • Now sync assembling your project.

Implementing Firebase Cloud Messaging

Create a category called  MyFirebaseInstanceIDService.java and write the next code.

package com.androdevelopment.firebasecloudmessaging;
 
 
import android.util.Log;
 
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
 
/**
 * Created by Abdul Basit on 4/1/2017.
 */
 
 
//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 next code.
package com.androdevelopment.firebasecloudmessaging;
 
 
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 Abdul Basit on 4/1/2017.
 */
 
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());
    }
}

 

  • We now have to define the above mentioned services inside our AndroidManifest.xml data file. So go to manifest and modify the following.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androdevelopment.firebasecloudmessaging">
 
    <!-- 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>

 

Thats all. Now run your software (Ensure that your device is having google play service if not it will not work).

After running you will notice the token in the logcat. copy the token. as shown in following image

firebase cloud messaging

Sending Push Notification using Firebase Console

  • Head to firebase console and choose the app you created.
  • From the still left menu go for notification.
  • Select new message.
  • Enter message, choose one device and paste the token you copied and select send.

firebase cloud messaging

Read Full Tutorial Of Firebase Push Notification.

Yeah! It really is working absolutely fine.So thats all because of this Firebase Cloud Messaging (FCM) Article friends. In approaching posts I’ll make an effort to show some complicated applications using Firebase Cloud Messaging (FCM).

See Also:

Firebase Push Notification Android Tutorial

Firebase Loign And Registration Authentication

Firebase Github Authentication