Popular Searches
Popular Course Categories
Popular Courses

Introduction to Mobile Push Notifications

Introduction to Mobile Push Notifications

Push Notifications and Background Tasks

Introduction to Mobile Push Notifications in React Native

Course: React Native Training

Topic: Introduction to Mobile Push Notifications

Course Link: React Native Training at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Mobile Push Notifications

Mobile push notifications are messages delivered to mobile devices to inform users about new activities, important updates, reminders, offers, and events. They can appear on the lock screen, notification center, or as banners, depending on device settings and operating system behavior.

In React Native, push notifications help developers build applications that communicate with users even when the application is not currently open. Typical examples include chat messages, order updates, appointment reminders, news alerts, and account notifications.

1.1 Importance of Push Notifications

  • Improve communication between applications and users.
  • Provide timely updates about important activities.
  • Encourage users to return to the application.
  • Deliver reminders for scheduled events and tasks.
  • Support personalized content and user engagement.
  • Provide transactional updates such as payment and delivery status.

1.2 Real-World Examples

Application Example Notification
Messaging You have received a new message.
Shopping Your order has been shipped.
Education Your online class starts in 15 minutes.
Travel Your flight schedule has changed.
Banking A transaction has been completed.
News A new article is available.

2. Learning Objectives

After studying this topic, learners will be able to:

  • Understand the purpose and architecture of mobile push notifications.
  • Differentiate push notifications, local notifications, and in-app messages.
  • Understand Firebase Cloud Messaging and Apple Push Notification service.
  • Configure the basic requirements for notifications in React Native.
  • Understand notification permissions and device registration tokens.
  • Receive and handle messages in different application states.
  • Handle notification taps and navigate to relevant screens.
  • Understand notification security, testing, and troubleshooting.

3. Types of Mobile Notifications

3.1 Remote Push Notifications

Remote push notifications originate from a backend server and are delivered through a push messaging service. They are useful for real-time updates, messages, promotions, and order status notifications.

3.2 Local Notifications

Local notifications are scheduled or triggered on the device by the application. They are commonly used for reminders, alarms, calendar events, and scheduled tasks.

3.3 In-App Messages

In-app messages appear inside an application while the user is interacting with it. Examples include promotional banners, announcement cards, and informational dialogs.

3.4 Comparison

Feature Remote Push Local Notification In-App Message
Origin Backend server Device application Application interface or service
Internet needed at display time Usually required for new remote delivery Not necessarily Depends on the content source
Can appear outside the application Yes, subject to permissions and platform rules Yes, subject to permissions and platform rules Generally no
Example New message alert Scheduled reminder Welcome banner

4. Understanding Push Notification Architecture

Push notifications involve communication between a mobile application, a backend service, and the platform's messaging infrastructure.

4.1 Main Components

  • React Native application: The mobile app that receives and handles messages.
  • Backend server: Determines when notifications should be sent and selects recipients.
  • Firebase Cloud Messaging (FCM): A messaging service for supported mobile platforms.
  • Apple Push Notification service (APNs): Apple's infrastructure for delivering notifications to Apple devices.
  • Registration token: Identifies a registered application installation or messaging endpoint.
  • Operating system: Controls notification permissions, presentation, and background execution.

4.2 How Push Notifications Work

  1. The user installs and opens the application.
  2. The application completes the necessary messaging configuration and registration.
  3. The application requests notification permission when appropriate.
  4. The messaging SDK provides a registration token when registration succeeds.
  5. The application sends the token securely to its backend.
  6. The backend associates the token with the appropriate account or installation.
  7. An event occurs, such as a new message or an order being shipped.
  8. The backend sends a message through the appropriate push service.
  9. The service attempts to deliver the message to the device.
  10. The operating system or application handles presentation and user interaction according to the message type and application state.

4.3 Architecture Diagram

React Native Mobile App
          |
          | Registration Token
          v
      Backend API
          |
          v
   Token Database
          |
          | Business Event
          v
Notification Service
          |
          v
      FCM / APNs
          |
          v
    Mobile Device
          |
          v
 Notification Handler
          |
          v
 Relevant App Screen

5. Firebase Cloud Messaging and APNs

5.1 Firebase Cloud Messaging

Firebase Cloud Messaging is a messaging service that allows a trusted server to send messages to supported client applications. It is commonly used in React Native applications to implement remote push notifications.

FCM supports notification messages and data messages. Notification messages provide user-visible content, while data messages contain custom information for application logic. Actual delivery and handling depend on platform rules and application state.

5.2 Apple Push Notification Service

Apple Push Notification service is Apple's remote notification delivery infrastructure. An iOS application requires appropriate Apple Developer configuration, signing, capabilities, and push credentials for successful remote notification delivery.

5.3 Comparison

Aspect FCM APNs
Provider Google Firebase Apple
Purpose Messaging infrastructure for supported platforms Remote push delivery to Apple devices
Android support Yes No
iOS support Yes, using Apple's push infrastructure for delivery Yes
Configuration Firebase project and platform setup Apple Developer configuration and capabilities

6. Prerequisites for React Native Push Notifications

Before integrating notifications, prepare the following:

  • A working React Native project.
  • A compatible notification library.
  • A Firebase project if using FCM.
  • Correct Android application ID and Firebase configuration.
  • An Apple Developer account and suitable iOS signing configuration when required.
  • A backend service for sending remote notifications.
  • A secure mechanism for storing and updating device registration tokens.
  • A physical device or supported testing environment.

6.1 Choosing a Library

React Native Firebase Messaging provides an interface to Firebase Cloud Messaging. A separate notification library may be needed for advanced local notification scheduling and presentation. The correct choice depends on the React Native version, project workflow, and notification requirements.

Follow the current official installation instructions for your chosen library because native setup and API details can vary by version.

7. Installing React Native Firebase Messaging

For a compatible React Native project using React Native Firebase, install the core Firebase package and messaging module.

npm install @react-native-firebase/app
npm install @react-native-firebase/messaging

For iOS projects, install CocoaPods dependencies when required:

cd ios
pod install
cd ..

7.1 Configure Firebase

  1. Open the Firebase Console.
  2. Create a Firebase project.
  3. Register the Android application using its correct application ID.
  4. Register the iOS application using its bundle identifier when supporting iOS.
  5. Download and configure the platform-specific Firebase files.
  6. Complete the native configuration and build requirements.
  7. Verify that the application initializes Firebase successfully.

Installing the packages alone does not enable push notifications. Firebase setup, native configuration, platform permissions, and appropriate messaging registration must also be completed.

8. Requesting Notification Permission

Mobile operating systems control whether applications can display notifications. Developers should request permission at an appropriate point and explain the value of enabling notifications.

8.1 Request Permission on iOS

import messaging from '@react-native-firebase/messaging';

export async function requestIOSNotificationPermission() {
  const status = await messaging().requestPermission();

  const enabled =
    status === messaging.AuthorizationStatus.AUTHORIZED ||
    status === messaging.AuthorizationStatus.PROVISIONAL;

  return enabled;
}

This example uses the permission API provided by React Native Firebase Messaging. Check the current library guidance for permission APIs and supported versions.

8.2 Request Permission on Android 13 and Later

import {
  PermissionsAndroid,
  Platform,
} from 'react-native';

export async function requestAndroidNotificationPermission() {
  if (
    Platform.OS === 'android' &&
    Number(Platform.Version) >= 33
  ) {
    const result = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
    );

    return result === PermissionsAndroid.RESULTS.GRANTED;
  }

  return true;
}

Android 13 and later generally require the runtime notification permission for standard notifications. Earlier versions follow different permission rules. Ensure that the Android manifest and target SDK settings are configured correctly.

8.3 Permission Best Practices

  • Explain why notifications are useful before requesting permission.
  • Handle permission denial without crashing or blocking unrelated functionality.
  • Avoid repeatedly prompting the user.
  • Respect the user's system notification settings.
  • Provide instructions for enabling notifications in settings when appropriate.

9. Retrieving the FCM Registration Token

An FCM registration token identifies a registered application installation or messaging endpoint. The backend uses it to target messages to that installation.

9.1 Get the Token

import messaging from '@react-native-firebase/messaging';

export async function getFCMToken() {
  const token = await messaging().getToken();
  return token;
}

9.2 Send the Token to the Backend

export async function registerDeviceToken(token, authToken) {
  const response = await fetch(
    'https://example.com/api/device-tokens',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`,
      },
      body: JSON.stringify({ token }),
    }
  );

  if (!response.ok) {
    throw new Error('Device token registration failed');
  }

  return response.json();
}

The endpoint and authentication token in this example are placeholders. Replace them with your actual backend URL and secure authentication implementation.

9.3 Handle Token Refresh

import messaging from '@react-native-firebase/messaging';

export function subscribeToTokenRefresh(authToken) {
  return messaging().onTokenRefresh(async token => {
    try {
      await registerDeviceToken(token, authToken);
    } catch (error) {
      console.error('Token update failed:', error);
    }
  });
}

Register the listener in an appropriate application lifecycle location and unsubscribe when needed. Also consider synchronizing the current token during authenticated startup, since a token refresh listener alone does not cover every registration scenario.

10. Receiving Foreground Notifications

The foreground state means that the application is currently open and visible. React Native Firebase Messaging provides onMessage() to process incoming FCM messages while the application is active.

10.1 Example Foreground Handler

import React, { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';

export default function App() {
  useEffect(() => {
    const unsubscribe = messaging().onMessage(
      async remoteMessage => {
        const title =
          remoteMessage.notification?.title || 'New Message';

        const body =
          remoteMessage.notification?.body ||
          'You have received an update.';

        Alert.alert(title, body);
      }
    );

    return unsubscribe;
  }, []);

  return null;
}

This is a simplified example of the listener. In a real application, integrate the listener into the existing root component rather than replacing the application UI with this component.

10.2 Important Foreground Behavior

  • The listener can process messages while the application is active.
  • A visible system notification may not automatically appear in the foreground.
  • The application can update its UI or show an appropriate in-app notification.
  • Foreground presentation behavior may require additional native configuration.

11. Handling Background Messages

A background message handler processes eligible messages when the application is not visible. In React Native Firebase, register setBackgroundMessageHandler() outside the normal React component lifecycle, usually in the entry file.

11.1 Background Handler Example

// index.js

import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import App from './App';
import { name as appName } from './app.json';

messaging().setBackgroundMessageHandler(
  async remoteMessage => {
    // Process the message or update suitable stored data.
    console.log('Background message received');
  }
);

AppRegistry.registerComponent(appName, () => App);

Keep background processing short and return a promise for the work that needs to finish. Background execution is subject to operating system restrictions, payload type, device state, and notification configuration.

12. Handling Notification Taps

Users often tap a notification to open a relevant screen. For example, tapping an order notification can open the order details page.

12.1 Handle a Notification Tap from the Background

import messaging from '@react-native-firebase/messaging';

export function listenForNotificationTaps(navigate) {
  return messaging().onNotificationOpenedApp(
    remoteMessage => {
      const data = remoteMessage.data || {};

      if (data.type === 'order_update' && data.orderId) {
        navigate('OrderDetails', {
          orderId: data.orderId,
        });
      }
    }
  );
}

12.2 Handle a Notification That Launches the App

import messaging from '@react-native-firebase/messaging';

export async function handleInitialNotification(navigate) {
  const remoteMessage =
    await messaging().getInitialNotification();

  if (!remoteMessage) {
    return;
  }

  const data = remoteMessage.data || {};

  if (data.type === 'order_update' && data.orderId) {
    navigate('OrderDetails', {
      orderId: data.orderId,
    });
  }
}

The navigate function represents your navigation logic. Call these handlers where the navigation system can safely process the action. If navigation is not ready, queue the destination until initialization completes.

12.3 Safe Navigation Practices

  • Validate notification payload data before using it.
  • Verify that the destination record exists.
  • Check that the signed-in user has permission to view the destination.
  • Handle missing or invalid identifiers gracefully.
  • Wait for authentication and navigation initialization when necessary.

13. Notification Payloads

A notification payload contains information sent by the backend. Its structure depends on the push service and message type.

13.1 Example Payload

{
  "notification": {
    "title": "Order Update",
    "body": "Your order has been shipped."
  },
  "data": {
    "type": "order_update",
    "orderId": "ORD-1001"
  }
}

13.2 Notification Payload vs Data Payload

Feature Notification Payload Data Payload
Purpose Provides user-visible content Provides custom application data
Typical fields Title and body Type, record ID, routing information
Display behavior Can be displayed by the platform when eligible Does not inherently display a visible notification
Handling Depends on application state and platform Processed by application code when delivered and execution is permitted

Message delivery and processing behavior differs between Android and iOS. Do not assume that every data message will execute JavaScript immediately when the application is in the background or terminated.

14. Foreground, Background, and Terminated States

State Description Considerations
Foreground The application is open and visible. Use foreground listeners and configure presentation as needed.
Background The application is not visible but may still be running. Notification display and background processing depend on the payload and platform.
Terminated The application process is not active. A notification may be displayed by the operating system and can launch the application when tapped.
Force-stopped or force-quit The user or operating system has stopped the application. Delivery and background execution may be restricted until the application is reopened.

15. Android Notification Channels

Android 8.0 and later use notification channels to group notifications by category. Users can manage channel settings, such as sound and importance, through system settings.

15.1 Examples of Channels

  • Messages: New conversations and chat alerts.
  • Orders: Shipping and delivery updates.
  • Reminders: Scheduled activities and deadlines.
  • Promotions: Optional marketing notifications.

15.2 Best Practices

  • Use meaningful channel names and descriptions.
  • Group notifications according to user expectations.
  • Avoid creating unnecessary channels.
  • Respect the importance and sound settings chosen by users.
  • Test channel behavior on different Android versions.

16. Sending Notifications from a Backend

In production applications, privileged messages should be sent from a trusted backend or server environment. The backend can validate events, authenticate requests, identify recipients, and send messages using the appropriate messaging API.

16.1 Example Workflow

  1. An event occurs, such as an order being shipped.
  2. The backend validates the event and recipient.
  3. The backend retrieves the appropriate device-token registrations.
  4. The server creates a notification payload.
  5. The trusted server submits the message through the messaging service.
  6. The backend records the outcome and handles invalid tokens or delivery errors.

16.2 Security Requirements

  • Never store privileged FCM server credentials in the React Native application.
  • Protect service-account keys and backend secrets.
  • Use secure connections and appropriate authentication.
  • Validate user access before displaying sensitive destination content.
  • Remove obsolete device-token registrations.
  • Do not include passwords, authentication tokens, or sensitive personal information in notification text.

17. Testing Push Notifications

Testing should cover device registration, permissions, message delivery, presentation, notification taps, and application lifecycle behavior.

Test Case Expected Result
Open the application. Firebase initializes and messaging registration can complete.
Grant notification permission. The permission result is handled correctly.
Deny permission. The application continues working without crashing.
Retrieve the FCM token. A token is obtained when registration succeeds.
Send a test message. The device receives the message when delivery conditions are satisfied.
Receive a foreground message. The foreground listener processes the message.
Receive a background notification. Behavior matches the payload and platform configuration.
Tap a notification. The correct screen opens when applicable.
Refresh the registration token. The backend registration is updated.
Disable notifications in system settings. The application handles the changed permission or channel state.

17.1 Useful Testing Tools

  • Firebase Console for project setup and supported test messaging workflows.
  • Android Studio for Android logs and native configuration.
  • Xcode for iOS builds, signing, and device testing.
  • React Native DevTools for application debugging.
  • Backend logs for investigating messaging API errors.

Use physical devices for end-to-end testing where required. Some simulator environments do not support every push notification scenario.

18. Common Problems and Troubleshooting

Problem Possible Cause Solution
Notifications do not arrive. Incorrect setup, invalid token, permissions, or delivery restrictions. Verify registration, server responses, and platform configuration.
Token retrieval fails. Firebase initialization or native configuration is incomplete. Review installation and platform setup.
No visible foreground notification. Foreground presentation is not configured. Implement the appropriate in-app or native presentation behavior.
Background handler does not run. Incorrect registration or platform restrictions. Check the entry-point registration and payload type.
Wrong screen opens after a tap. Invalid payload data or navigation timing. Validate data and wait for navigation readiness.
Android notification has no sound. Channel or device settings disable sound. Check notification channel and system settings.
iOS notifications fail. APNs credentials, capabilities, or permission setup is incorrect. Verify Apple Developer and Firebase configuration.
Duplicate notifications appear. Both platform handling and custom code display the same event. Review payload type and notification presentation logic.
Old notifications target unavailable records. The record was removed or access has changed. Validate the destination and provide a fallback screen.

19. Best Practices for Mobile Push Notifications

  • Send useful and relevant notifications.
  • Keep titles and message content concise.
  • Request permission at an appropriate moment.
  • Respect user preferences and system settings.
  • Use notification channels appropriately on Android.
  • Handle foreground, background, and terminated states.
  • Validate payload data before navigation.
  • Manage registration tokens securely.
  • Send privileged messages from a trusted backend.
  • Provide clear handling for failures and invalid tokens.
  • Avoid excessive notifications and unnecessary interruptions.
  • Test on supported Android and iOS devices.

20. Mini Project: Order Update Notification System

Create a React Native application that notifies users when an order is placed, shipped, or delivered.

20.1 Project Requirements

  • Create a basic order screen.
  • Configure Firebase Cloud Messaging.
  • Request notification permission where required.
  • Retrieve and register the device token with a backend.
  • Send an order-update notification from a trusted server.
  • Handle messages in the foreground.
  • Register a background message handler.
  • Handle notification taps from background and terminated states.
  • Navigate to the appropriate order details screen.
  • Handle errors, permission denial, and token changes.

20.2 Suggested Project Structure

OrderNotificationApp/
├── src/
│   ├── screens/
│   │   ├── HomeScreen.js
│   │   └── OrderDetailsScreen.js
│   ├── services/
│   │   ├── notificationService.js
│   │   └── apiService.js
│   ├── navigation/
│   │   └── AppNavigator.js
│   └── components/
│       └── OrderCard.js
├── App.js
└── index.js

20.3 Development Steps

  1. Create the React Native project.
  2. Configure Firebase and native platform requirements.
  3. Install the required packages.
  4. Implement permission handling.
  5. Retrieve and register the device token.
  6. Implement foreground and background message handlers.
  7. Implement notification-tap navigation.
  8. Send test notifications from a trusted backend.
  9. Test error handling, token refresh, and lifecycle behavior.

21. Practice Exercises

  1. Explain the difference between push notifications and local notifications.
  2. Create a Firebase project and register a React Native application.
  3. Implement notification permission handling.
  4. Retrieve an FCM registration token.
  5. Register the device token with a backend endpoint.
  6. Handle foreground messages using onMessage().
  7. Register a background handler in the entry file.
  8. Handle notification taps from the background.
  9. Handle the initial notification when a notification launches the application.
  10. Create a sample order-update notification payload.
  11. Test notification permission denial and token changes.
  12. Document common Android and iOS notification issues.

22. Interview Questions and Answers

Q1. What is a mobile push notification?

Answer: A message delivered to a mobile device through a push notification service to communicate updates, reminders, or events.

Q2. What is Firebase Cloud Messaging?

Answer: FCM is a messaging service used by trusted servers to send messages to supported client applications.

Q3. What is APNs?

Answer: Apple Push Notification service is Apple's infrastructure for delivering remote notifications to Apple devices.

Q4. What is an FCM registration token?

Answer: It identifies a registered application installation or messaging endpoint and can be used to target messages.

Q5. What is the difference between notification and data payloads?

Answer: Notification payloads contain user-visible content, while data payloads contain custom key-value information for application logic.

Q6. How are foreground messages handled?

Answer: React Native Firebase's onMessage() listener processes eligible incoming FCM messages while the application is active.

Q7. How are background messages handled?

Answer: The setBackgroundMessageHandler() API handles eligible background processing when correctly registered, subject to operating system restrictions.

Q8. Why is notification permission important?

Answer: It determines whether the application can present notifications according to operating system rules and the user's preferences.

Q9. What is an Android notification channel?

Answer: A category that groups notifications and lets users control their behavior through system settings.

Q10. How can a notification open a specific screen?

Answer: Include appropriate routing data, handle notification-open events, validate the data, and navigate when the application is ready.

Q11. Why should server credentials not be stored in a mobile app?

Answer: Mobile application code can be inspected. Exposing privileged credentials could allow unauthorized access to messaging services.

Q12. What should happen when an FCM token changes?

Answer: The application should update the backend registration and associate the new token with the correct account or installation.

23. Quick Revision Checklist

  • Push notifications deliver remote messages to mobile devices.
  • FCM provides messaging infrastructure for supported platforms.
  • APNs provides Apple's remote notification delivery infrastructure.
  • Remote push, local notifications, and in-app messages are different.
  • Notification permissions and native configuration must be handled correctly.
  • Registration tokens need secure backend management.
  • onMessage() handles eligible foreground messages.
  • setBackgroundMessageHandler() handles eligible background processing.
  • onNotificationOpenedApp() handles notification taps from the background.
  • getInitialNotification() can identify a notification that launched the application.
  • Notification behavior differs by platform and application state.
  • Privileged messaging credentials must remain on the trusted backend.
  • Test notification delivery, navigation, permissions, and failure scenarios.

24. Official Learning Resources

25. Conclusion

Mobile push notifications are an important part of modern React Native applications. They enable timely communication, user engagement, reminders, and updates even when the application is not currently visible.

Developers should understand Firebase Cloud Messaging, APNs, notification permissions, registration tokens, foreground and background handling, and notification-tap navigation. Secure backend integration, careful payload design, token lifecycle management, and thorough device testing are essential for reliable notification behavior.

Explore the Course: React Native Training at JustAcademy

Register for a Demo: Register for a JustAcademy Course Demo

Visit the Website: JustAcademy Official Website

whatsapp