• Android Push notification using FCM (Firebase Cloud Messaging)

    What is FCM (Firebase Cloud Messaging) ?

    Simply we can say FCM (Firebase Cloud Messaging) is a new version of GCM (Google Cloud Messaging).
    It is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Using FCM, you can send notification messages to drive user re-engagement and retention.

    FCM (Firebase Cloud Messaging) Project setup on Firebase Console

    Go to Firebase Console and create a new project
    One popup will appear. Provide your app name (Project name) and country and click on CREATE PROJECT button
    To implement Firebase to your Android app, click on Add Firebase to your Android app
    Now enter your project package name and click on ADD APP to register your app
    Download google-services.json file and click on CONTINUE button
    Now click on FINISH button and complete your project setup on Firebase Console

    Add FCM (Firebase Cloud Messaging) to Android app

    Copy google-services.json file, go to your Android Project and paste it in appfolder.
    Go to project level (root level) build.gradle file and add the following code into dependencies
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    
        // Add this line
        classpath 'com.google.gms:google-services:3.0.0'}
    Now go to app level build.gradle file and add the following lines
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:25.3.0'
        testCompile 'junit:junit:4.12'
        implementation 'com.google.android.gms:play-services:9.0.0'
        // Add this line
        implementation 'com.google.firebase:firebase-messaging:17.0.0'
        implementation 'com.google.firebase:firebase-core:15.0.0'}
    
    // Add this lineapply plugin: 'com.google.gms.google-services'
    Sync your project
    Now create MyFirebaseInstanceIDService.java class
    package com.mypackage.fcmdemo;
    
    import android.util.Log;
    
    import com.google.firebase.iid.FirebaseInstanceId;
    import com.google.firebase.iid.FirebaseInstanceIdService;
    
    
    public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    
    
        @Override
        public void onTokenRefresh() {
    
            //For registration of token
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    
            //To displaying token on logcat
            Log.d("TOKEN: ", refreshedToken);
    
        }
    
    }
    Now create MyFirebaseMessagingService.java class
    package com.mypackage.fcmdemo;
    
    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 com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;
    
    
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    
        @Override
        public void onMessageReceived(RemoteMessage message) {
            sendMyNotification(message.getNotification().getBody());
        }
    
        
        private void sendMyNotification(String message) {
          
            //On click of notification it redirect to this Activity
            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 soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Firebase Push notification")
                    .setContentText(message)
                    .setAutoCancel(true)
                    .setSound(soundUri)
                    .setContentIntent(pendingIntent);
    
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            notificationManager.notify(0, notificationBuilder.build());
        }
    }
    Give the INTERNET permission and define both above services into AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.mypackage.fcmdemo">
        <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=".MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
                </intent-filter>
            </service>
        </application>
    </manifest>
    Now run your application and check your logcat and you can find TOKEN

    Send your first notification message

    Go to Firebase Console and click on your project (e.g. FCMDemo) Now click on Notifications
    Now click on SEND YOUR FIRST MESSAGE button
    Type your message, select your app and click on SEND MESSAGE button and you will get your first notification on your device.
  • 1 comment:

    1. That's amazing informative post, I want to add one more thing, If you want to make your web visitor to your subscriber then you should definitely check gravitec lifetime deal Best push notification for website ever.

      ReplyDelete

    FAVOURITE LINE

    To steal ideas from one is plagiarism. To steal from many is Research.

    ADDRESS

    Mumbai , Maharashtra

    EMAIL

    shikha.pathak6@gmail.com
    shikha.the.swt.pari@gmail.com

    Skype

    shikha_pari