Search code examples
androidreact-nativereact-native-push-notification

How to know if the app is open from the android notification tray?


How to know if the app is open from the android notification tray? For instance, I have closed the app (cleared from recent app list). but I receive notification from the backend websocket, i pressed it, it opens the app. So my question is, is there way to check if this is open from notification?


Solution

  • Its simple, you receive notifications payload in your push notification listener

    import PushNotification from 'react-native-push-notification'
    configurePushNotifications = () => {
    
        PushNotification.configure({
          // (optional) Called when Token is generated (iOS and Android)
          onRegister: function(token) {
            console.log('PushNotification token', token)
          },
    

    onNotification is where you would receive you local or remote notification and it will be called when the user clicks on notification tray

          onNotification: function(notification) {
            console.log('notification received', notification)
          },
    
          // IOS ONLY (optional): default: all - Permissions to register.
          permissions: {
            alert: true,
            badge: true,
            sound: true,
          },
    
          // Should the initial notification be popped automatically
          // default: true
          popInitialNotification: true,
    
          /**
           * (optional) default: true
           * - Specified if permissions (ios) and token (android and ios) will requested or not,
           * - if not, you must call PushNotificationsHandler.requestPermissions() later
           */
          requestPermissions: true,
        })
      }
    

    this is how the notificaion object would look like

    {
        foreground: false, // BOOLEAN: If the notification was received in foreground or not
        userInteraction: false, // BOOLEAN: If the notification was opened by the user from the notification area or not
        message: 'My Notification Message', // STRING: The notification message
        data: {}, // OBJECT: The push data
    }