DEV Community

Cover image for Hiding Notifications in Foreground and Triggering Them in Background or Killed States using notifee
Amit Kumar
Amit Kumar

Posted on

Hiding Notifications in Foreground and Triggering Them in Background or Killed States using notifee

Push notifications are an essential feature for engaging users, but there are cases where you might want to control when notifications are delivered. In this article, we will implement a notification system in React Native using notifee that:

  • Hides notifications when the app is in the foreground.
  • Triggers notifications when the app is in the background or killed state.

I will walk through setting up the necessary permissions, creating notifications, and managing notifications.

Prerequisites

You will need the following:

  • A React Native project.
  • The Notifee library is installed. You can install it by running:
npm install @notifee/react-native
Enter fullscreen mode Exit fullscreen mode

Ensure you have properly configured your Android and iOS projects as per Notifee's setup guide.

1. Requesting Notification Permissions

To start, you need to request notification permissions for both Android and iOS. Here’s how to set it up:

import {useEffect} from 'react';
import notifee, {AndroidImportance} from '@notifee/react-native';

const getPermission = async () => {
  // Request permissions (required for iOS)
  await notifee.requestPermission();

  // Create a notification channel (required for Android)
  const channelId = await notifee.createChannel({
    id: 'default',
    name: 'Default Channel',
    importance: AndroidImportance.HIGH, // Ensure notifications appear
  });
};

Enter fullscreen mode Exit fullscreen mode

You should call this getPermission function when your app starts, so users are prompted for permission.

2. Managing Foreground Notifications (iOS and Android)

iOS:
iOS allows granular control over notifications in the foreground using foregroundPresentationOptions. Here’s how you can suppress notifications in the foreground:

ios: {
  foregroundPresentationOptions: {
    alert: false,  // Disable alert in foreground
    badge: false,
    sound: false,
    banner: false,
    list: false,
  },
},

Enter fullscreen mode Exit fullscreen mode

This configuration will prevent notifications from showing when the app is in the foreground, but they will still trigger in the background or killed states.

Android:
For Android, you need to handle foreground notifications through event listeners. We can use Notifee's onForegroundEvent to detect when notifications are delivered and cancel them in the foreground:

useEffect(() => {
  return notifee.onForegroundEvent(({type, detail}) => {
    switch (type) {
      case EventType.DELIVERED:
        console.log('Notification delivered in foreground');
        notifee.cancelNotification(detail.notification.id);  // Hide the notification id is -> notification_id
        break;
      case EventType.DISMISSED:
        console.log('Notification dismissed');
        break;
      case EventType.PRESS:
        console.log('Notification pressed');
        break;
    }
  });
}, []);

Enter fullscreen mode Exit fullscreen mode

In the example above, when a notification is delivered while the app is in the foreground, it is immediately canceled. This prevents the user from seeing it.

3. Handling Notifications in the Background or Killed State

To trigger notifications when the app is in the background or killed state, you can schedule notifications using a timestamp trigger. Here's an example of how to set up a trigger notification:

const onCreateTriggerNotification = () => {
  const trigger = {
    timestamp: Date.now() + 3000,  // Trigger after 3 seconds
    type: TriggerType.TIMESTAMP,
    alarmManager: { allowWhileIdle: true },  // Ensure it triggers even in idle state
  };

  return notifee.createTriggerNotification(
    {
      id: 'notification_id',
      title: 'Test Notification',
      body: 'This notification is triggered in the background or killed state',
      android: {
        smallIcon: 'ic_launcher',  // Ensure you have a valid icon
        channelId: 'default',
      },
      ios: {
        foregroundPresentationOptions: {
          alert: false,
          badge: false,
          sound: false,
          banner: false,
          list: false,
        },
      },
    },
    trigger,
  );
};

Enter fullscreen mode Exit fullscreen mode

You can trigger this function with a button press or programmatically based on app logic.

4. Required Permissions for Android

For Android, it’s important to request alarm permissions, especially for notifications in idle states. You can open the necessary permissions settings using Notifee:

useLayoutEffect(() => {
  notifee.openAlarmPermissionSettings();
}, []);

Enter fullscreen mode Exit fullscreen mode

Without this permission, notifications might not trigger correctly.

Full Code Example

Here is the full implementation:

import {Button, StyleSheet, View} from 'react-native';
import React, {useEffect, useLayoutEffect} from 'react';
import notifee, {AndroidImportance, EventType, TriggerType} from '@notifee/react-native';

const App = () => {
  useEffect(() => {
    getPermission();
  }, []);

  useEffect(() => {
    return notifee.onForegroundEvent(({type, detail}) => {
      switch (type) {
        case EventType.DELIVERED:
          notifee.cancelNotification(detail.notification.id);
          break;
      }
    });
  }, []);

  useLayoutEffect(() => {
    notifee.openAlarmPermissionSettings();
  }, []);

  const getPermission = async () => {
    await notifee.requestPermission();
    await notifee.createChannel({
      id: 'default',
      name: 'Default Channel',
      importance: AndroidImportance.HIGH,
    });
  };

  const onCreateTriggerNotification = () => {
    const trigger = {
      timestamp: Date.now() + 3000,
      type: TriggerType.TIMESTAMP,
      alarmManager: { allowWhileIdle: true },
    };

    return notifee.createTriggerNotification(
      {
        id: 'notification_id',
        title: 'Test Notification',
        body: 'This notification is triggered in the background or killed state',
        android: {
          smallIcon: 'ic_launcher',
          channelId: 'default',
        },
        ios: {
          foregroundPresentationOptions: {
            alert: false,
            badge: false,
            sound: false,
            banner: false,
            list: false,
          },
        },
      },
      trigger,
    );
  };

  return (
    <View style={styles.container}>
      <Button title="Display Notification" onPress={onCreateTriggerNotification} />
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

Enter fullscreen mode Exit fullscreen mode

Conclusion

By following this approach, you can effectively manage when notifications are shown to the user based on the app's state. Notifications are hidden when the app is in the foreground and triggered when the app is in the background or killed state.

Top comments (0)