How to add Firebase in android app

Push Notification Using Firebase In Android

How to add Firebase in android app

Firebase is real-time, advance and powerful tool for android app development. Firebase is a google product which allows to store data on the cloud, crashlytics, analytics, user authentication, cloud messaging and much more. In this session I'll cover push notification of Firebase. Firebase allow to send real time messaging on the android phones. Using the Firebase messaging you can send three types of messages:

1. Notification Message - Notification messages are handled by Firebase itself.

2. Data Message - Data messages are handled by the Android app.

3. 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 its values.

Create your account with Firebase Click here

Foreground State – App receive a message object with both payloads in activity FirebaseMessagingService.

Background State – App receive the notification message  payload in the notification tray, and when user taps on the notification then handle the data payload.

 

Second thing is message targeting 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. I'll tell you how to get this token id.

 

Let's start with Firebase:

1.First of all login with your gmail account in firebase.

2.You'll see the Welcome page of Firebase like this

 

3. Add project in your account.

 

4. Now you'll see the this screen, here your can choose your platform and choose options of add your Fiarebase android app.

 

5. Now you can register your app with package name and your app name.

 

6. When you pressed Register App button, Firebase allow to download config file to your PC. And this file needs to add in your android project root folder.

 

7. Now, add Firebase SDK in your gradle file.

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'

 

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
}

 

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:

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

    <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>

</manifest>

 

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:

204 day ago

Thanks for sharing such an amazing article, these tips surely improve my skills. I will also share this article with my co-android workers so that they can also learn about this great concept.

Legend Blogs made a post.
412 day ago

@Sagar Singh: admob is only for google Ad not for cloud notification.

Amanda Chua made a post.
413 day ago

Really impressive information in regards to firebase and I am going to improve my skills for sure. Thanks for the valuable information.

Sagar Singh made a post.
536 day ago

can is use admob instead of .. compile 'com.google.firebase:firebase-messaging:11.2.0'

Top