Android


How to add firebase push notification in android

Firebase push notification in android

Firebase is a real-time, advanced and powerful tool for android app development. Firebase is a Google product. This is used for firebase push notification in android and storing data on the cloud, crashlytics, analytics, user authentication, cloud messaging and much more.

In this session, I’ll cover push notification of Firebase. Firebase allows sending real-time messaging on Android phones.

Types of Firebase messaging

  • Notification Message
  • Data Message
  • Notification and Data Message

Using the Firebase messaging you can send Above all types of messages. Let’s see some more information about these three types:

Notification Message:

You need to to set your message only. In other words, Notification messages are handled by Firebase itself.

Data Message Firebase push notification:

Data messages are handled by the Android app.

Notification and Data Message:

In this situation, it will be handled in two scenarios depending upon app state (foreground/background). For these messages, we can use both notification and data keys and their values.

Create your account link for firebase push notification in android

Your can create your account with this Firebase Click here.

Firebase push notification states

  • Foreground State
  • Background State

Foreground State:

App receives a message object with both payloads in activity FirebaseMessagingService.

Background State:

App receives the notification message payload in the notification tray, and when a user taps on the notification then handle the data payload.

After that, The second thing is a message targeting the audience. You can send notification messages either to a single user or to all users using a topic name. But for targeting the audience you need a registered token id. Therefore, I’m going to tell you how to get this token id.

Let’s start with Firebase Sample Project

After that, I’ll tell you how you should use them. Above all steps follow carefully and create your Firebase Project.

Firstly: First of all login with your gmail account in Firebase.

Secondly: You’ll see the Welcome page of Firebase like this

Thirdly: Add project in your account.

Fourthly: Now you’ll see this screen, here you can choose your platform and choose options to add your Firebase android app.

Six: Now you can register your app with package name and your app name.

Seven: When you pressed Register App button, Firebase allows downloading config file to your PC. And this file needs to add in your android project root folder.

Finally: Now, add Firebase SDK in your Gradle file.

Now come to your Project and do some important changes. Add this link to your project level Gradle:

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

Add this to your add level Gradle:

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

And bottom of the same file add this line:

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

Sample file for your Project level Gradle is:

// 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'
        classpath 'com.google.gms:google-services:3.2.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
}

And Your app level Gradle is:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"

    defaultConfig {
        applicationId "com.legendblogs.firebase"
        minSdkVersion 21
        targetSdkVersion 26
        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:26.0.0-alpha1'
    compile 'com.google.firebase:firebase-messaging:11.8.0'
}

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

Now create your FirebaseCloudMessagingService file, FirebaseCloudMessagingService.java

package com.legendblogs.firebase;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FirebaseCloudMessagingService extends FirebaseMessagingService {

    private static final String TAG = FirebaseCloudMessagingService.class.getSimpleName();

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage == null)
            return;

        Log.d(TAG, "token "+ FirebaseInstanceId.getInstance().getToken());
        storeRegIdInPref(FirebaseInstanceId.getInstance().getToken());
        // check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification body: " + remoteMessage.getNotification().getBody());
            createNotification(remoteMessage.getNotification());
        }

        // check if message contains a data payload
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }
    }

    private void createNotification (RemoteMessage.Notification notification) {

        Intent notificationIntent = new Intent(this.getApplicationContext(), FirebaseCloudMessagingService.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, 0);

        Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(notification.getTitle())
                .setContentText(notification.getBody())
                .setAutoCancel( true )
                .setSound(notificationSoundURI)
                .setContentIntent(contentIntent);

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

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

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("legendblogs_firebase", 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("fcmRegId", token);
        editor.commit();
    }
}

MainActivity.java

package com.legendblogs.firebase;

import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView fcmtoken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fcmtoken = (TextView) findViewById(R.id.fcmtoken);
        Button getToken = (Button) findViewById(R.id.getToken);

        getToken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fcmtoken.setText(displayFirebaseRegId());
            }
        });

    }

    private String displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("legendblogs_firebase", 0);
        String regId = pref.getString("fcmRegId", null);
        return regId;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.legendblogs.firebase.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="FCM Registration Token"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="97dp"
        android:textSize="30dp"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/fcmtoken"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Token"
        android:id="@+id/getToken"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Add sevices of Filebase in your android manifest:

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

manifest.xml:

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

</application>

Now, go to your google Firebase account and select Notification section to send a notification message.

After this you’ll see this screen to send your first Notification:

Create your first notification like this and press send:

Now you’ll get notification on your phone like this:

When you tap on the notification your app will open:

And for Register Token Id press on GET TOKEN button:

firebase push notification

Published by Tirthraj Pandey

Professional Android app Developer, Full Stack Web Developer, Blogger, Entrepreneur And Founder of Coding Issue. I am always trying to learn new things or new possible ways to do things.

Did you find this page helpful?

X

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

*