/firebase-tutorials

How to send push notifications with Firebase?

Learn how to set up Firebase push notifications for Android, iOS, and Web with our easy, step-by-step guide to configure FCM and implement notification code.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to send push notifications with Firebase?

 

Step 1: Set Up Your Firebase Project

 

  1. Go to the Firebase Console.
  2. Click on "Add project" to create a new Firebase project.
  3. Enter your project name and choose your settings, then click "Continue."
  4. Set up Google Analytics for your project if you prefer, or skip this step.
  5. Click "Create project," then "Continue" once the project is set up.

 

Step 2: Add Firebase to Your App

 

  1. In the Firebase Console, select your project.

  2. Click on the platform icon (iOS, Android, or Web) to add Firebase to your app. Follow the provided instructions based on your platform:

    For Android:

  • Enter your package name and optional app nickname.

  • Download the google-services.json file and add it to your app directory.

  • Add Firebase SDK to your app by updating your build.gradle files:

// In your root-level (project-level) Gradle file (build.gradle), add:
buildscript {
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.10' // Check for the latest version
}
}

// In your app-level Gradle file (usually app/build.gradle), add:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
// Add the Firebase SDK for Google Analytics
implementation 'com.google.firebase:firebase-analytics:19.0.0'

// Add the Firebase Cloud Messaging dependency
implementation 'com.google.firebase:firebase-messaging:23.0.0' // Check for the latest version

}

For iOS:

  • Download the GoogleService-Info.plist file and add it to your Xcode project.

  • Use CocoaPods to add the Firebase SDK. In your Podfile, include:

pod 'Firebase/Messaging'

  • Run pod install in your project directory.

    For Web:

  • Add the Firebase SDK to your project by including the scripts in your HTML file:

 </pre></code>
  • Initialize Firebase with your configuration settings.

 

Step 3: Set Up Firebase Cloud Messaging (FCM)

 

  1. In the Firebase Console, navigate to your project and click on "Cloud Messaging."
  2. Follow any instructions to set up FCM for your specific platform.

 

Step 4: Implement Push Notification Code in Your App

 

For Android:

  1. Extend FirebaseMessagingService to handle incoming FCM messages:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Handle FCM messages here.
    // Not getting messages here? See why this may be: https://firebase.google.com/docs/cloud-messaging/android/receive

    if (remoteMessage.getNotification() != null) {
        // Get the message and handle it
        String messageBody = remoteMessage.getNotification().getBody();
        sendNotification(messageBody);
    }
}

private void sendNotification(String messageBody) {
    // Create and display the notification
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "default\_channel")
            .setSmallIcon(R.drawable.ic\_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION\_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("default_channel", "Default Channel", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

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

}

  1. Don't forget to declare MyFirebaseMessagingService in your AndroidManifest.xml:






For iOS:

  1. Implement the messaging delegate methods in your App Delegate or any other initial view controller:

import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

func application(\_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Configure Firebase
    FirebaseApp.configure()

    // Set UNUserNotificationCenterDelegate
    UNUserNotificationCenter.current().delegate = self

    // Request notification permissions
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        // Handle the authorization request response
    }

    application.registerForRemoteNotifications()

    // Set the Messaging delegate
    Messaging.messaging().delegate = self

    return true
}

// Receive and handle FCM messages
func application(\_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // Handle the message
}

// Handle notification settings
func userNotificationCenter(\_ center: UNUserNotificationCenter,
                            openSettingsFor notification: UNNotification?) {
    // Handle the settings
}

// Handle FCM token refresh
func messaging(\_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    print("Firebase registration token: (String(describing: fcmToken))")
}

}

For Web:

  1. Register a service worker and handle messages:

// Initialize Firebase
const firebaseConfig = {
// Your Firebase config here
};
firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.getToken({ vapidKey: 'YOUR_PUBLIC_VAPID_KEY' }).then((currentToken) => {
if (currentToken) {
// Send token to server and display notification UI
console.log('Token:', currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.error('An error occurred while retrieving token. ', err);
});

// Handle incoming messages
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});

 

Step 5: Testing Push Notifications

 

  1. In the Firebase Console, go to the "Cloud Messaging" tab.
  2. Click "Send your first message."
  3. Enter the message details and select your target (app instance, topic, etc.).
  4. Click "Review" then "Publish" to send the message.

 

This comprehensive guide should help you set up and implement Firebase push notifications for your Android, iOS, or Web app.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022