skip to Main Content

I’m trying to implement push notifications with react native app with this plugin react-native-push-notifications. what I succeed is to get notification when app is running(in foreground), but what I’m looking to do is to get local notification when app is closed(background), not running and when I get notification to go into the app.

This is my Code –

  PushNotification.createChannel({
    channelId: "alarm-channel",
    channelName: "Alarm Channel",
    importance: 4,
    vibrate: true,
  });
};

const [selectedDate, setSelectedDate] = useState(new Date());
const handleDatePicker = (dateTime) => {
  const fireDate = dateTime;

  PushNotification.localNotificationSchedule({
    channelId: "alarm-channel",
    title: 'title',
    id: alarmNotifData.id,
    message: 'message',
    date: fireDate ,
    soundName: "Default",
    actions: ["Snooze", "Stop Reminder"],
    importance: Importance.HIGH,
    playSound: true,
    allowWhileIdle: true,
    invokeApp: false,
    priority: "high",
    timeoutAfter: 50000,
    autoCancel: false,
    vibrate: true,
    vibration: 500,
  });
};

handleDatePicker(selectedDate);

2

Answers


  1. Use background services to run your code when app is closed. For Android, react-native has Headless.js but to do that you need to write some native code. Unfortunately react-native has no documentation for IOS right now.

    For Android : https://reactnative.dev/docs/headless-js-android

    A library that does this for both IOS & Android : https://www.npmjs.com/package/react-native-background-actions

    Login or Signup to reply.
  2. If you’re looking to implement notifications in the background. I highly recommend adopting the @notifee/react-native package.

    Installation instructions

    You can use React Native AppState to check whether or not you’re currently in the foreground of the app or in the background.

    For iOS, I personally like to use AppState.current === "inactive" since its lifecycle is always active -> inactive -> background.

    For Android I use AppState.current === "background" since Android only has active -> background

    First import AppState and notifee

    import {AppState} from "react-native"
    import notifee from "@notifee/react-native";
    

    Within your app setup code create a state variable for appState and set up an AppState listener

    
      const [appState, setAppState] = useState(AppState.currentState);
    
      // This is used as a callback function whenever AppState changes
      const handleAppStateChange = useCallback(
        (newState: any) => {
          console.log(`AppState changed to ${newState}`);
          setAppState(newState);
        },
        []
      );
    
      // Initial useEffect to set things up
      useEffect(() => {
        let isActive = true;
        let appStateSubscriber: NativeEventSubscription;
        const loadNavSubscriber = async () => {
          if (isActive) {
            // Adding the listener for whether the user leaves the app
            console.log(`Adding AppState event listener`);
            appStateSubscriber = AppState.addEventListener("change", 
            handleAppStateChange);
          }
        };
        loadNavSubscriber();
        
        // It's always good practice to ask the user for notification permissions
        const getNotificationPermissions = async () => {
          if (isActive) {
            const settings = await notifee.requestPermission();
          }
        };
        getNotificationPermissions();
        return () => {
          isActive = false;
          if (appStateSubscriber) appStateSubscriber.remove();
        };
      }, []);
    

    Then, somewhere in your code you can say.

    if (appState === "active") {
      // no need to notify 
    } else if (Platform.OS === "ios" && appState === "inactive") {
      // notify when background logic occurs
    } else if (Platform.OS === "android" && appState === "background") {
      // notify when background logic occurs
    }
    

    In android if you’re experiencing that a new instance of your app is getting created when you open up a notification, make sure you check your AndroidManifest.xml. This took me hours to fix in the past.

    android:windowSoftInputMode="adjustPan"
            android:launchMode="singleTask"
            android:exported="true"
    
    

    the whole activity in question for AndroidManifest.xml

        <activity
          android:name=".MainActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
          android:windowSoftInputMode="adjustPan"
            android:launchMode="singleTask"
            android:exported="true">
         <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="YOUR_APP_NAME" />
        </intent-filter>
        </activity>
    

    Good luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search