How to create Firebase Cloud Messaging Client App on Android

Firebase cloud messaging can be used by Android Developers who wish to send  push notifications with one click to each and every user who has installed their application. You can also control the complete push notification it self by setting up push notification title, push notification message body. The developer can also schedule our push notification timing from the Firebase panel.

 

1.Open your project’s AndroidManifest.xml file and copy the below permission inside it.

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

 

2. Add service into AndroidManifest.xml file

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

 

3. MainActivity Java File

package com.androidjson.firebasecloudmessage_androidjsoncom;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

 

4. activity_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidjson.firebasecloudmessage_androidjsoncom.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

 

5. Code for MyFirebaseInstanceIDService.java file

 

package com.androidjson.firebasecloudmessage_androidjsoncom;



import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import android.util.Log;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String Firebase_Tag = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {

        //Getting token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        //Show token on logcat
        Log.d(Firebase_Tag, "Refreshed token: " + refreshedToken);

    }

    private void sendRegistrationToServer(String token) {
        // Write down your code here to do anything with toke like sending on server or save locally.
    }
}

 

6. MyFirebaseMessagingService.java file source code

package com.androidjson.firebasecloudmessage_androidjsoncom;


import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.content.Intent;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        //Method To Generate Notification.
        FirebaseCloudMessageFunction(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
    }

    // Function to Generate Push Notification After Receiving Response from Server.
    private void FirebaseCloudMessageFunction(String messageTitle, String messageBody) {

        // Creating Intent.
        Intent intent = new Intent(this, MainActivity.class);

        // Device vibrate pattern.
        long[] pattern = {500,500,500,500,500};

        // Adding FLAG_ACTIVITY_CLEAR_TOP to intent.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Creating Pending Intent object.
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 , intent,PendingIntent.FLAG_UPDATE_CURRENT);


        // Creating URI to access the default Notification Ringtone.
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // Converting drawable icon to bitmap for default notification ICON.
        Bitmap DefaultIconBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        // Building Notfication.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)

                // Adding Default Icon to Notification bar.
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

                // Setting up Title.
                .setContentTitle(messageTitle)

                // Setting the default msg coming from server into Notification.
                .setContentText(messageBody)

                .setAutoCancel(true)

                .setVibrate(pattern)

                .setSound(defaultSoundUri)

                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

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

 

 

7. Complete AndroidManifest.xml file  source code

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

 

How to send push notification from Firebase Panel ?

  1. Open Firebase .
  2. Select your application.
  3. Goto Notifications.
  4. Click on SEND YOUR FIRST MESSAGE .
  5. Enter Message body and title, Hit the Send Message button.

Recent Articles

OnePlus 7T vs iPhone 11 | Specs Comparison

The OnePlus 7T and iPhone 11 are the two best phones if you looking for a price of less than $1000. Both the phone...

Elon Musk unveils Tesla’s Cybertruck

Are you into gaming or love watching sci-fi movies?  What about those back to the future movies which gave us a glimpse of the...

7 Best Hiking Apps you Must Try in 2020

Having the best hiking apps always gives you an advantage if you are going for adventurous trips. These apps can track your workout and activities...

[UPDATED] 9 Best Android Launcher Apps of 2019

Android launcher is best to customize the overall experience of Android for a user in terms of look and act. In apps store, there are...

Stadia Pro members will get two more games in December

If you are a member of Google Stadia Pro then there is good news for you, you will be getting two more games for free...

Related Stories

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay on Top - Get the daily news in your inbox