Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android: onForegroundEvent not listening to onPress Event #621

Closed
quicksilverr opened this issue Dec 20, 2022 · 42 comments · Fixed by #720
Closed

Android: onForegroundEvent not listening to onPress Event #621

quicksilverr opened this issue Dec 20, 2022 · 42 comments · Fixed by #720
Labels
needs-feedback Waiting on response to questions

Comments

@quicksilverr
Copy link

Hey, thanks for building such a cool package for handling notifications in RN.

The current issue that I'm facing is that, if the app is in the foreground state and I click on the notification. The onForegroundEvent is not listening to that action, and I'm unable to receive the notification payload or any event type, rather it gives the warning that the onBackgroundEvent is not setup.

The strange thing is that, when the notification is delivered. I'm able to get a log from the onForegroundEvent, for the Event type delivered, but on clicking the notification, nothing happens.

Info

"@notifee/react-native": "^7.2.0",
"react-native": "0.70.5",
"react": "18.2.0",

buildToolsVersion = "31.0.0"
minSdkVersion = 21
compileSdkVersion = 33
targetSdkVersion = 33
kotlinVersion = '1.7.10'

The current workaround, that I'm using is, which was suggested by @mikehardy .

Being, we store the notification in the onBackgroundEvent, in a global state management storage and then retrieve it, wherever in the app we require.

@quicksilverr
Copy link
Author

@helenaford As requested by you, created this issue

@qroac
Copy link

qroac commented Dec 20, 2022

Thanks for posting this.
Yesterday I started to migrate our expo project from expo-notifications to notifee.
I really love the notifications with notifee but I am facing the very same problem.

What I did:

  • added notifee to the project
  • added expo plugin to config, executed expo prebuild and built an expo dev-client that includes notifee
  • added event listeners for foreground, background and initialNotificaton as described in documentation in the main component just before calling registerRootComponent
  • display a dummy notification from somewhere in my code and add a dummy trigger notification as well

What I get:

  • event 7 when trigger notification is scheduled
  • event 3 when one of the notifications is displayed
  • event 0 when user dismisses notification

What I dont get:

  • event 1 after pressing the notification

Opening the app if not in foreground works, I just dont get notified about the event.

"@notifee/react-native@npm:^7.3.0":
  version: 7.3.0
  resolution: "@notifee/react-native@npm:7.3.0"
"react-native@npm:0.69.6":
  version: 0.69.6
  resolution: "react-native@npm:0.69.6"
"expo@npm:^46.0.0, expo@npm:~46.0.17":
  version: 46.0.17
  resolution: "expo@npm:46.0.17"

expo config

plugins: [
      [
        'expo-build-properties',
        {
          android: {
            compileSdkVersion: 33,
            buildToolsVersion: '33.0.0',
          },
        },
      ],
      '@notifee/react-native',
      'sentry-expo',
    ],
   android: {
      package: ...,
      permissions: ['SCHEDULE_EXACT_ALARM'],
      useNextNotificationsApi: true,
      versionCode: 37,
    },

@quicksilverr
Copy link
Author

Hey @qroac, while this is getting fixed, I've just done a temporary workaround.

Assuming that, you are using redux-toolkit and react navigation.

Here are the steps, that I took..

  • First, setup the onBackgroundEvent listener, in your index.js file and dispatch the notification data in it.
  • Then, retrieve it in the component, where you want to do some UI changes.

Here are the code snippets

import { AppRegistry } from 'react-native';
import App from './app/App';
import 'react-native-gesture-handler';
import 'react-native-get-random-values';
import messaging from '@react-native-firebase/messaging';
import notifee from '@notifee/react-native';
import _ from 'lodash';
import { displayNotifications } from 'just_a_wrapper_file';
import { dispatch, storeNotification } from 'your_store';

messaging().setBackgroundMessageHandler(displayNotifications);

notifee.onBackgroundEvent(async ({ type, detail }) => {
  const { notification, pressAction } = detail;
  dispatch(
    storeNotification({
      notification: notification,
      eventType: type,
    })
  );
});

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


imports...

const notificationData = useAppSelector(getNotificationData);

React.useEffect(() => {
    if (navigationRef.isReady()) {
      if (!_.isUndefined(notificationData.notification)) {
        onNotificationEvent(
          notificationData?.notification?.data,
          notificationData.eventType
        );
      }
    }
  }, [notificationData]);

  return (
    <NavigationContainer
      ref={navigationRef}
      fallback={<Text>Loading ...</Text>}
      onReady={() => {
        RNBootSplash.hide({ fade: true });
      }}
    >
<Routes/>
</NavigationContainer>

@AnisDerbel
Copy link

I'm also facing the same problem, onForegroundEvent not getting fired when pressing on the notification on Android

@patissier-boulanger
Copy link

patissier-boulanger commented Jan 6, 2023

Me too. Having same problem. Can't receive foreground event

I'm also facing the same problem, onForegroundEvent not getting fired when pressing on the notification on Android

@helenaford
Copy link
Member

helenaford commented Jan 9, 2023

can you post a step-by-step of how to recreate this bug? it's not clear to me as you mention both the background and foreground event handlers.
I just tested this myself and received a press_event on API Level 33/Android 13 with the app open, pull down the notification drawer and press it.

This is the payload from our test app:

{
   key: 'Basic',
   notification: {
     id: 'basic',
     title: '<p style="color: #4caf50;"><b>Styled HTMLTitle</span></p></b></p> &#128576;',
     android: {
       channelId: 'high',
       pressAction: {
         id: 'default',
       },
     },
     ios: {},
   },
 },
 
 Edit: press event was received but via background handler. For the foreground handler to be triggered, the notification needs to be in a heads-up notification. 

@helenaford helenaford added the needs-feedback Waiting on response to questions label Jan 9, 2023
@helenaford
Copy link
Member

helenaford commented Jan 9, 2023

ohhh, isn't this the same issue #529? I think I understand now what you are saying the problem is... that you're receiving a background event but you think it should be a foreground event instead 🤔

@izakfilmalter
Copy link

izakfilmalter commented Jan 15, 2023

This is a huge problem for us.

It seems to me that there is not a thorough testing process for releases. I have the following testing process for both iOS and Android which would be good to mirror at some level. I get the desire for automated testing, but every release I run into an issue with FCM + Notifee.

  1. App Quit Test
    1. Quit Open Test
      1. Quit the app.
      2. Trigger test notification.
      3. Tap on notification.
      4. App should open to the screen for the notification.
    2. Background Open Test
      1. Quit the app.
      2. Trigger test notification.
      3. Open the app, and dismiss it. The app must still be open in the background.
      4. Tap on notification.
      5. App should open to the screen for the notification.
    3. Foreground Open Test
      1. Quit the app.
      2. Trigger test notification.
      3. Open the app. The app must still be open in the foreground.
      4. Tap on notification.
      5. App should open to the screen for the notification.
  2. App Background Test
    1. Quit Open Test
      1. Open the app, and dismiss it. The app must still be open in the background.
      2. Trigger test notification.
      3. Quit the app after the notification has displayed.
      4. Tap on notification.
      5. App should open to the screen for the notification.
    2. Background Open Test
      1. Open the app, and dismiss it. The app must still be open in the background.
      2. Trigger test notification.
      3. Tap on notification.
      4. App should open to the screen for the notification.
    3. Foreground Open Test
      1. Open the app, and dismiss it. The app must still be open in the background.
      2. Trigger test notification.
      3. Quit the app after the notification has displayed.
      4. Open the app. The app must still be open in the foreground.
      5. Tap on notification.
      6. App should open to the screen for the notification.
  3. App Foreground Test
    1. Quit Open Test
      1. Open the app. The app must still be open in the foreground.
      2. Trigger test notification.
      3. Quit the app after the notification has displayed.
      4. Tap on notification.
      5. App should open to the screen for the notification.
    2. Background Open Test
      1. Open the app. The app must still be open in the foreground.
      2. Trigger test notification.
      3. Dismiss the app. The app must still be open in the background.
      4. Tap on notification.
      5. App should open to the screen for the notification.
    3. Foreground Open Test
      1. Open the app. The app must still be open in the foreground.
      2. Trigger test notification.
      3. Quit the app after the notification has displayed.
      4. Open the app. The app must still be open in the foreground.
      5. Tap on notification.
      6. App should open to the screen for the notification.

@github-actions
Copy link

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

@Ahmedhamed77
Copy link

Hey @qroac, while this is getting fixed, I've just done a temporary workaround.

Assuming that, you are using redux-toolkit and react navigation.

Here are the steps, that I took..

  • First, setup the onBackgroundEvent listener, in your index.js file and dispatch the notification data in it.
  • Then, retrieve it in the component, where you want to do some UI changes.

Here are the code snippets

import { AppRegistry } from 'react-native';
import App from './app/App';
import 'react-native-gesture-handler';
import 'react-native-get-random-values';
import messaging from '@react-native-firebase/messaging';
import notifee from '@notifee/react-native';
import _ from 'lodash';
import { displayNotifications } from 'just_a_wrapper_file';
import { dispatch, storeNotification } from 'your_store';

messaging().setBackgroundMessageHandler(displayNotifications);

notifee.onBackgroundEvent(async ({ type, detail }) => {
  const { notification, pressAction } = detail;
  dispatch(
    storeNotification({
      notification: notification,
      eventType: type,
    })
  );
});

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

imports...

const notificationData = useAppSelector(getNotificationData);

React.useEffect(() => {
    if (navigationRef.isReady()) {
      if (!_.isUndefined(notificationData.notification)) {
        onNotificationEvent(
          notificationData?.notification?.data,
          notificationData.eventType
        );
      }
    }
  }, [notificationData]);

  return (
    <NavigationContainer
      ref={navigationRef}
      fallback={<Text>Loading ...</Text>}
      onReady={() => {
        RNBootSplash.hide({ fade: true });
      }}
    >
<Routes/>
</NavigationContainer>

if you use messaging().setBackgroundMessageHandler(displayNotifications); this wouldn't duplicate notifications for you on android ? if so how did you solve it ?
because whenever I use messaging().setBackgroundMessageHandler(displayNotifications); I get two notifications
one from FCM and the other is from notifee
how did you manage to get one notification from notifee only ?

@artus9033
Copy link

The issue is still present in 7.4.0

@lmalvasia
Copy link

notificationData

Still having this issue in 7.5.0

I could make a workaround using redux and redux persist, following the example posted by quicksilverr. Thanks

@criss02-cs
Copy link

still having this issue, i can listen DELIVERED event, but when i press the notification it does nothing

@joel611
Copy link

joel611 commented Mar 10, 2023

Having the same problem, only receive delivered events onForegroundEvent but no press events.

@k0502s
Copy link

k0502s commented Mar 20, 2023

I also checked that it was not working. Event 1 is not displayed after clicking Alert. on Android

@fgagneten
Copy link

fgagneten commented Mar 20, 2023

Same issue here! Android 12. Only "delivered" event works. Issue still present in 7.6.1

@helenaford
Copy link
Member

does anyone know when this stopped working? I'm looking into this now, can see the issue you describe. definitely hasn't always been like this.

i wonder if it's todo with android 12 +.

@izakfilmalter
Copy link

It's been an issue for at least the last 5 months. Didn't seem to be an issue in October last year but by December I've been fighting it.

@k0502s
Copy link

k0502s commented Mar 22, 2023

@helenaford

In my case, there was a problem with Android 12 version.

@helenaford
Copy link
Member

helenaford commented Mar 23, 2023

Hey All, I've pushed a solution and a pre-release of v7.7.0-0.

npm i @notifee/react-native@7.7.0-0

I've left some notes on the p/r with a screen recording showing the final result. #720

I will not actually publish this as a final version until Monday which gives time for feedback.

Reopened issue for now until it's in a final release.

@helenaford helenaford reopened this Mar 23, 2023
@Sandeep145XamRN
Copy link

Hey @helenaford I am currently facing with triggering the onPress event of notification click when a notification is received in the background.

As when a notification is received in the foreground, the onPress event is triggered without any issues. However, when the notification is received in the background, the onPress event is not triggered (notifee.onBackgroundEvent).
with version v7.7.0-0.

I have added my index.js class code

/**
 * @format
 */

import { AppRegistry } from 'react-native'
import AppCover from './src/App'
import { name as appName } from './app.json'
import { startNetworkLogging } from 'react-native-network-logger';
import notifee, { EventType } from '@notifee/react-native';
import { gestureHandlerRootHOC } from 'react-native-gesture-handler';


notifee.onBackgroundEvent(async ({ type, detail }) => {
    console.warn('notification background handler',type,detail)
    const { notification, pressAction } = detail;
    // Check if the user pressed 
    if (type === EventType.ACTION_PRESS) {
        console.warn('notification read')
        // Remove the notification
        await notifee.cancelNotification(notification.id);
    }
});

AppRegistry.registerComponent(appName, () => gestureHandlerRootHOC(AppCover))

@k0502s
Copy link

k0502s commented Mar 31, 2023

me too. @Sandeep145XamRN

"react-native": "0.66.3", "@notifee/react-native": "7.7.0-0"

I tested it with v7.7.0-0.
For the foreground, Press event started working well, but now Press event doesn't seem to work in the background.

The devices tested are Galaxy s20 and Android 12 versions.

@helenaford Thank you for your efforts to solve this problem.

@MandeepKaur-1
Copy link

I'm facing the same issue @Sandeep145XamRN @k0502s have you found any solution?

"react-native": "0.70.6", "@notifee/react-native": "7.7.0-0"

@helenaford thanks for a great library. I understand that you are dealing with a lot of issues, but I wanted to bring your attention to a particular issue, which is crucial, I'm unable to work on notification re-direction. Any guidance will be appreciated.

@helenaford
Copy link
Member

helenaford commented Apr 2, 2023

@k0502s @MandeepKaur-1 please can you provide a screen recording?

Sometimes it may be still classed as "foreground" if the app is running but may visually be in the background. If you have just pushed it into the background without opening another app for example.

Have you checked out my video on the p/r #720. This shows when the background event is fired

What is the re-direction issue you are facing? Are you receiving a foreground event instead?

@helenaford
Copy link
Member

helenaford commented Apr 3, 2023

I tested this with the example app we have packages/react-native/example on Samsung S21 an it's working on Android 13 and I believe it will be the same for Android 12 too. The app is on the latest react-native version... not sure if that makes a difference.

If it is not crashing your app when it's firing the foreground event when the app is active (even if visually it's in the background), then I think that is fine. If you need to know if the app is in focus for a specific foreground event, you can use the AppState

I really don't like that it's called onForegroundEvent as it is misleading. I think it should be called something like onEventListener which means if the app is "running" or "already launched", the listener is still active.

And, then the onBackgroundEvent should be when the app is truly closed and the app's activity is not running.

But this latest fix is to get the same original behaviour where background event can mean quit or in the background, and foreground event is when the app is in focus on the screen.

As I mentioned above, if you could provide a video or more details of how this negatively effects your app, that would be helpful.

@helenaford helenaford pinned this issue Apr 3, 2023
@k0502s
Copy link

k0502s commented Apr 3, 2023

@helenaford You always work hard. Thank you.

What I learned from watching this video(#720) is that you get a push notification from the foreground of the video, then switch to the background and click on the push notification.

The flow I tested had a problem when I switched to the background before receiving a push notification and then got a push notification in the background state and then clicked on the push notification.

I'm sorry, but I can't upload the video right now. I'll try v7.7.0-0 as soon as I have time.

Thank you.

@Sandeep145XamRN
Copy link

#720

Hi @helenaford Thank you so much for your guidance!!, I'm attaching a detailed screen recording of whole notification flow testing, In my case background event not working in any of case even app is in kill state. Please check attached video.

Untitled.2.mp4

Environment

"react-native": "0.70.1"
notifee:[v7.7.0-0](https://www.npmjs.com/package/@notifee/react-native/v/7.7.0-0:).
Android version 13

let me know in case you require further information regarding same.

@k0502s
Copy link

k0502s commented Apr 3, 2023

#720

안녕@helenaford안내해 주셔서 감사합니다!! 전체 알림 흐름 테스트에 대한 자세한 화면 녹화를 첨부하고 있습니다. 제 경우에는 백그라운드 이벤트가 작동하지 않고 앱이 종료 상태인 경우도 있습니다. 첨부된 영상을 확인해주세요.

환경

"react-native": "0.70.1" notifee:[v7.7.0-0](https://www.npmjs.com/package/@notifee/react-native/v/7.7.0-0:). 안드로이드 버전 13

이와 관련하여 추가 정보가 필요한 경우 알려주세요.

Same here when I get push notifications in background like this video and click push notifications, there is no response.

@samjuyal
Copy link

samjuyal commented Apr 4, 2023

@Sandeep145XamRN have you found any solution? I am facing same issue in background notification.
React-native version--0.70.1

@edritech93
Copy link

same issue for me, I use "@notifee/react-native": "^7.6.1",

@helenaford
Copy link
Member

helenaford commented Apr 7, 2023

@Sandeep145XamRN that's expected for remote notifications. You need to use the RNFB messaging background handler because your notification has a title and body.

@k0502s , I believe this could the same issue are you describe above too

@helenaford
Copy link
Member

@samjuyal @edritech93 please can you specify which issue you are experiencing? There's alot of various sub issues in this thread, so the more specific you can be, the better

@Sandeep145XamRN
Copy link

Hey @helenaford Thank you for your attention to this matter!! Yeah, I have also used the same approach. However, the Firebase handler is not working with the latest version https://www.npmjs.com/package/@notifee/react-native/v/7.7.0-0: on iOS platform. To resolve this issue, I had to downgrade the version of Notifee to https://www.npmjs.com/package/@notifee/react-native/v/5.7.0. But there are some issues with this version too, as the notification permission popup does not appear on the Android platform.

I think downgrading the version is not a good solution, whereas the latest versions should have Firebase events listening capabilities for iOS too(working seamlessly on Android). If we do that, we will not be able to use the latest features of the library.

I am adding some code snippets, hoping that it will be helpful for push notification handling.

If you are using a native splash screen for android, then its code should be as given below. ignore if you are using react-native-splash-screen

SplashActivity.java

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
  //  block of code to try
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, MainActivity.class);
        // Pass along FCM messages/notifications etc.
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
        finish();
}
catch(Exception e) {
  //  block of code to handle errors
  System.out.println(e.getMessage());
}
    }
}

App.js

 import messaging from '@react-native-firebase/messaging'
//RNFB messaging
useEffect(() => {
    (async () => await messaging().registerDeviceForRemoteMessages())();
    //foreground state
    const unsubscribe = messaging().onMessage(async message => {
      if(message){
        console.log('Notification received in foreground state:', message);
      }
      notifee.displayNotification({
        title: message?.notification?.title,
        body: message?.notification?.body,
        android: {
          channelId: 'default',
          backgroundEvent: 'handleNotification',
        },
      })
    });
    //backgroud state click
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('Notification caused app to open from background state:', remoteMessage);
      navigateToScreenWhenNotificationTapped(remoteMessage)
    });
    //kill state click
    messaging().getInitialNotification().then(remoteMessage => {
      if (remoteMessage) {
        console.log('Notification caused app to open from quit state:', remoteMessage);
        navigateToScreenWhenNotificationTapped(remoteMessage)
      }
    });
    return unsubscribe;
  }, [])

@FrSenpai
Copy link

FrSenpai commented Apr 8, 2023

Same issue for me, on expo SDK 48, notifee ^7.6.1 and react native 0.71.6

@helenaford
Copy link
Member

for iOS, please use the notifee methods.

@helenaford
Copy link
Member

Closing issue as original issue is now fixed with pre-release v7.7.0-0. Will be released later today.

@k0502s
Copy link

k0502s commented Apr 12, 2023

@helenaford

The onBackgroundEvent method is not functioning in the background state even though v7.7.0-0 is using the setBackgroundMessageHandler.

스크린샷 2023-04-12 오후 1 08 49

@helenaford
Copy link
Member

@k0502s please can you be more detailed? which platform and which type of notification? local (via notifee) or remote (via RNFB)?

@k0502s
Copy link

k0502s commented Apr 15, 2023

@helenaford

  • v7.7.0-1
  • RN version "react-native": "0.66.3"
  • The device is Android (Galaxy s20 SM-G980F)
  • The software version is Android 12
  • I used remote (via RNFB "@react-native-firebase/messaging": "^14.2.4"). Push notifications from RNFB are displayed as notifee.

스크린샷 2023-04-15 오후 9 53 45

You always work hard. Thank you!

@vasylnahuliak
Copy link

vasylnahuliak commented Apr 18, 2024

The issue is still present in 7.8.2 on Android

@react-native-firebase/messaging 19.2.2
react-native 0.72.4
Android 14 (Emulator/Device)

Test case:

  1. Open the app. The app must still be open in the foreground.
  2. Trigger test remote notification.
  3. Dismiss the app. The app must still be open in the background.
  4. Tap on notification.
  5. App should open to the screen for the notification.

@mezalejandro
Copy link

Any update on this?
the same thing keeps happening

@ucheNkadiCode
Copy link

When using remote notifications on React Native, I've had the most luck with these docs. It directly states that onForegroundEvent will fire when it's a remote notification.

I'm able to send notifications via the Firebase Messaging Console. The way I've handled it is to place the notifee.onForegroundEvent subscriber onto my home screen and then handle any navigation logic from there. That way I have access to a navigation object and can navigate or pass params. Surprisingly, this onForegroundEvent code even runs from the kill state. I am only able to get onBackgroundEvent to fire from local notifications while the app is running, not remote notifications

Using
"@notifee/react-native": "^7.7.1",
"react-native": "^0.72.4",
"@react-native-firebase/app": "^14.12.0",
"@react-native-firebase/messaging": "^14.12.0",

// One Time USE EFFECT function to set things up!!
  useEffect(() => {
    const unsubscribeNotifee = notifee.onForegroundEvent(
      async ({ type, detail }) => {
        console.log(
          `The type is`,
          type,
          "the detail is",
          detail
        );
        switch (type) {
          case EventType.PRESS:
            if (detail.notification?.remote) {
               console.log("It was a remote notification")
              // Do some navigation logic
            }
            break;
          case EventType.ACTION_PRESS:
            console.log(`It was an ACTION PRESS THO`)
            break;
        }
      }
    );
    return () => {
      unsubscribeNotifee();
    };
  }, []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-feedback Waiting on response to questions
Projects
None yet
Development

Successfully merging a pull request may close this issue.