react-native-push-notification icon indicating copy to clipboard operation
react-native-push-notification copied to clipboard

Disable foreground notifications?

Open 0hio-creator opened this issue 3 years ago • 10 comments

Is it possible to disable foreground receiving foreground notifications from my own app? (when the app is open). Specifically for Android?

I have this set but i still see remote notifications for my app while its in the foreground

<meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>

0hio-creator avatar Mar 03 '21 07:03 0hio-creator

Hi I'm also experiencing this issue My remote and local notifications have been setup successfully

But when my app is in foreground, i dont want the notification to pop up as alert

allindeveloper avatar Mar 13 '21 21:03 allindeveloper

Hi,

<!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>

This parameter is for remote notification, please use the following for local notifications:

ignoreInForeground: false, // (optional) if true, the notification will not be visible when the app is in the foreground (useful for parity with how iOS notifications appear). should be used in combine with `com.dieam.reactnativepushnotification.notification_foreground` setting

Without context / reproducible exemple, can't help more.

Regards,

Dallas62 avatar Mar 13 '21 21:03 Dallas62

Thank You. I'll try to explain.

I have checked other issues, but i haven't seen a solution. -- Location/Scheduled notification works well for me---

This issue is particular to Remote/Push Notifications on Android

onNotif function gets called automatically when the android app is in foreground as soon as remote notification comes in, I believe it supposed to show in the action center just like a location notification.

Expected behaviour The push notification should pop up from the action center just like a regular notification

Please what i'm i doing wrong, kindly advice I followed the example here https://github.com/zo0r/react-native-push-notification/tree/master/example

From App.js

  ...
  constructor(props) {
    super(props);
    this.notif = new NotifService(
      this.onRegister.bind(this),
      this.onNotif.bind(this),
    );
  }

    onRegister(token) {
    this.setState({registerToken: token.token, fcmRegistered: true});
  }
    onNotif(notif) {
    Alert.alert(notif.title, notif.message); 
    <--- For push notification This function gets called automatically when the app is in foreground --->
    console.log("onNotif,",notif)
    // if(notif){
    // this.navigate("CurrentNotification",{notif})
    // }else{
    //   console.log("notif from onNotif is undefined",notif)
    // }
  }

Notification Handler

import PushNotification from 'react-native-push-notification';

class NotificationHandler {

 onNotification(notification) {
   console.log('NotificationHandler-- onNotifcation:', notification);

   if (typeof this._onNotification === 'function') {
     this._onNotification(notification);
   }
 }

 onRegister(token) {
   console.log('NotificationHandler--- onRegister:', token);

   if (typeof this._onRegister === 'function') {
     this._onRegister(token);
   }
 }

 onAction(notification) {
   console.log ('Notification action received:');
   console.log(notification.action);
   console.log(notification);

   if(notification.action === 'Yes') {
     PushNotification.invokeApp(notification);
   }
 }

 // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
 onRegistrationError(err) {
   console.log(err);
 }
 
 attachRegister(handler) {
   this._onRegister = handler;
 }

 attachNotification(handler) {
   this._onNotification = handler;
 }
}

const handler = new NotificationHandler();

PushNotification.configure({
 // (optional) Called when Token is generated (iOS and Android)
 onRegister: handler.onRegister.bind(handler),

 // (required) Called when a remote or local notification is opened or received
 onNotification: handler.onNotification.bind(handler),

 // (optional) Called when Action is pressed (Android)
 onAction: handler.onAction.bind(handler),

 // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
 onRegistrationError: handler.onRegistrationError.bind(handler),

 // 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: false,
});

export default handler;

NotifService


import PushNotification from 'react-native-push-notification';
import NotificationHandler from './NotificationHandler';

export default class NotifService {
  constructor(onRegister, onNotification) {
    this.lastId = 0;
    this.lastChannelCounter = 0;

    this.createDefaultChannels();

    NotificationHandler.attachRegister(onRegister);
    NotificationHandler.attachNotification(onNotification);

    // Clear badge number at start
    PushNotification.getApplicationIconBadgeNumber(function (number) {
      if (number > 0) {
        PushNotification.setApplicationIconBadgeNumber(0);
      }
    });
    
    PushNotification.getChannels(function(channels) {
      console.log(channels);
    });
    PushNotification.subscribeToTopic("MyNews")
  }

  createDefaultChannels() {
    PushNotification.createChannel(
      {
        channelId: "default-channel-id", // (required)
        channelName: `Default channel`, // (required)
        channelDescription: "A default channel", // (optional) default: undefined.
        soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
        importance: 4, // (optional) default: 4. Int value of the Android notification importance
        vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
      },
      (created) => console.log(`createChannel 'default-channel-id' returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
    );
    PushNotification.createChannel(
      {
        channelId: "sound-channel-id", // (required)
        channelName: `Sound channel`, // (required)
        channelDescription: "A sound channel", // (optional) default: undefined.
        soundName: "sample.mp3", // (optional) See `soundName` parameter of `localNotification` function
        importance: 4, // (optional) default: 4. Int value of the Android notification importance
        vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
      },
      (created) => console.log(`createChannel 'sound-channel-id' returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
    );
  }

  createOrUpdateChannel() {
    this.lastChannelCounter++;
    PushNotification.createChannel(
      {
        channelId: "custom-channel-id", // (required)
        channelName: `Custom channel - Counter: ${this.lastChannelCounter}`, // (required)
        channelDescription: `A custom channel to categorise your custom notifications. Updated at: ${Date.now()}`, // (optional) default: undefined.
        soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
        importance: 4, // (optional) default: 4. Int value of the Android notification importance
        vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
      },
      (created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
    );
  }

  popInitialNotification() {
    PushNotification.popInitialNotification((notification) => console.log('InitialNotication:', notification));
  }

  localNotif(soundName) {
    this.lastId++;
    PushNotification.localNotification({
      /* Android Only Properties */
      channelId: soundName ? 'sound-channel-id' : 'default-channel-id',
      ticker: 'My Notification Ticker', // (optional)
      autoCancel: true, // (optional) default: true
      largeIcon: 'ic_launcher', // (optional) default: "ic_launcher"
      smallIcon: 'ic_notification', // (optional) default: "ic_notification" with fallback for "ic_launcher"
      bigText: 'My big text that will be shown when notification is expanded', // (optional) default: "message" prop
      subText: 'This is a subText', // (optional) default: none
      color: 'red', // (optional) default: system default
      vibrate: true, // (optional) default: true
      vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
      tag: 'some_tag', // (optional) add tag to message
      group: 'group', // (optional) add group to message
      groupSummary: false, // (optional) set this notification to be the group summary for a group of notifications, default: false
      ongoing: false, // (optional) set whether this is an "ongoing" notification
      actions: ['Yes', 'No'], // (Android only) See the doc for notification actions to know more
      invokeApp: true, // (optional) This enable click on actions to bring back the application to foreground or stay in background, default: true
      
      when: null, // (optionnal) Add a timestamp pertaining to the notification (usually the time the event occurred). For apps targeting Build.VERSION_CODES.N and above, this time is not shown anymore by default and must be opted into by using `showWhen`, default: null.
      usesChronometer: false, // (optional) Show the `when` field as a stopwatch. Instead of presenting `when` as a timestamp, the notification will show an automatically updating display of the minutes and seconds since when. Useful when showing an elapsed time (like an ongoing phone call), default: false.
      timeoutAfter: null, // (optional) Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled, default: null

      /* iOS only properties */
      category: '', // (optional) default: empty string
      
      /* iOS and Android properties */
      id: this.lastId, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
      title: 'Local Notification', // (optional)
      message: 'My Notification Message', // (required)
      userInfo: { screen: 'home' }, // (optional) default: {} (using null throws a JSON value '<null>' error)
      playSound: !!soundName, // (optional) default: true
      soundName: soundName ? soundName : 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
      number: 10, // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
    });
  }

  scheduleNotif(soundName) {
    this.lastId++;
    PushNotification.localNotificationSchedule({
      date: new Date(Date.now() + 30 * 1000), // in 30 secs

      /* Android Only Properties */
      channelId: soundName ? 'sound-channel-id' : 'default-channel-id',
      ticker: 'My Notification Ticker', // (optional)
      autoCancel: true, // (optional) default: true
      largeIcon: 'ic_launcher', // (optional) default: "ic_launcher"
      smallIcon: 'ic_notification', // (optional) default: "ic_notification" with fallback for "ic_launcher"
      bigText: 'My big text that will be shown when notification is expanded', // (optional) default: "message" prop
      subText: 'This is a subText', // (optional) default: none
      color: 'blue', // (optional) default: system default
      vibrate: true, // (optional) default: true
      vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
      tag: 'some_tag', // (optional) add tag to message
      group: 'group', // (optional) add group to message
      groupSummary: false, // (optional) set this notification to be the group summary for a group of notifications, default: false
      ongoing: false, // (optional) set whether this is an "ongoing" notification
      actions: ['Yes', 'No'], // (Android only) See the doc for notification actions to know more
      invokeApp: false, // (optional) This enable click on actions to bring back the application to foreground or stay in background, default: true

      when: null, // (optionnal) Add a timestamp pertaining to the notification (usually the time the event occurred). For apps targeting Build.VERSION_CODES.N and above, this time is not shown anymore by default and must be opted into by using `showWhen`, default: null.
      usesChronometer: false, // (optional) Show the `when` field as a stopwatch. Instead of presenting `when` as a timestamp, the notification will show an automatically updating display of the minutes and seconds since when. Useful when showing an elapsed time (like an ongoing phone call), default: false.
      timeoutAfter: null, // (optional) Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled, default: null
    
      /* iOS only properties */
      category: '', // (optional) default: empty string
      
      /* iOS and Android properties */
      id: this.lastId, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
      title: 'Scheduled Notification', // (optional)
      message: 'My Notification Message', // (required)
      userInfo: { sceen: "home" }, // (optional) default: {} (using null throws a JSON value '<null>' error)
      playSound: !!soundName, // (optional) default: true
      soundName: soundName ? soundName : 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
      number: 10, // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
    });
  }

  checkPermission(cbk) {
    return PushNotification.checkPermissions(cbk);
  }

  requestPermissions() {
    return PushNotification.requestPermissions();
  }

  cancelNotif() {
    PushNotification.cancelLocalNotifications({id: '' + this.lastId});
  }

  cancelAll() {
    PushNotification.cancelAllLocalNotifications();
  }

  abandonPermissions() {
    PushNotification.abandonPermissions();
  }

  getScheduledLocalNotifications(callback) {
    PushNotification.getScheduledLocalNotifications(callback);
  }

  getDeliveredNotifications(callback) {
    PushNotification.getDeliveredNotifications(callback);
  }
}

allindeveloper avatar Mar 14 '21 10:03 allindeveloper

How i send the message from my node api

router.post("/Notify", async function (req, res, next) {
  
  const message = {
    topic: "MyNews",
    notification: {
      title: "Presh Notification",
      body: "Here is the Notification Description",
    },
    data: {
      name: "AboutReact",
      url: "https://google.com",
      writter: "@allindeveloper",
    },
    android: {
      notification: {
        image:
          "https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png",
        defaultSound:true,
        priority:"low"
      },
      ttl: 4500,
      priority: "normal",
    },
    apns: {
      headers: {
        "apns-priority": "5",
        "apns-expiration": "1604750400",
      },
      "payload":{
        "aps":{
           "sound":"default"
        }
     }
    },
  };

  admin
    .messaging()
    .send(message)
    .then((response) => {
      res.send(`Successfully sent message: ${response}`);
    })
    .catch((error) => {
      res.send(`Error sending message: ${error}`);
    });
});

allindeveloper avatar Mar 14 '21 10:03 allindeveloper

Hi https://github.com/zo0r/react-native-push-notification/issues/1632#issuecomment-690265077 This has solved my issue, it gave me some insight

    onNotif(notification) {
    // Alert.alert(notif.title, notif.message);
    if(!notification.userInteraction) {
      PushNotification.localNotification(notification.data);
    }
    console.log("onnNotif noww,",notification)
    // if(notif){
    // this.navigate("Login",{notif})
    // }else{
    //   console.log("notif from onNotif is undefined",notif)
    // }
  }

and updated my message object like so

const message = {
    topic: "MyNews",
     data: {
      // this works when the app is not killed and in background
      name: "AboutReact",
      url: "https://aboutreact.com",
      writter: "@allindeveloper",
      title: "Presh Notification",
      message: "Here is the Notification Description",
    },
    android: {
      // this works when the app is killed, and you can still get the above data object from
      ///PushNotification.popInitialNotification ()
      
      notification: {
        image:
          "https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png",
          title: "Presh Notification",
          body: "Here is the Notification Description",
        defaultSound:true,
        priority:"low",
        channelId:"clenv-driver-channel",
        
      },
      
      ttl: 4500,
      priority: "normal",
    },
    apns: {
      headers: {
        "apns-priority": "5",
        "apns-expiration": "1604750400",
      },
      "payload":{
        "aps":{
           "sound":"default"
        }
     }
    },
  };

allindeveloper avatar Mar 14 '21 11:03 allindeveloper

This is working for us-

Android

<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground" android:value="false"/>

iOS

// Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    completionHandler(UNNotificationPresentationOptionNone);
}

In this way, when the app is in the foreground, no notification shown while in the background, notification is showing. Hence, this solution is working for us.

classiebit avatar Jun 04 '21 08:06 classiebit

This is working for us-

Android

<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground" android:value="false"/>

iOS

// Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    completionHandler(UNNotificationPresentationOptionNone);
}

In this way, when the app is in the foreground, no notification shown while in the background, notification is showing. Hence, this solution is working for us.

Thank's, that worked for me!

akinncar avatar Sep 22 '21 17:09 akinncar

This is working for us-

Android

<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground" android:value="false"/>

iOS

// Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    completionHandler(UNNotificationPresentationOptionNone);
}

In this way, when the app is in the foreground, no notification shown while in the background, notification is showing.

Found the same but with more details in other tickets but for amplify push. It worked for me developer.apple.com

LYevhen avatar Dec 03 '21 19:12 LYevhen

This is working for us-

Android

<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground" android:value="false"/>

iOS

// Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    completionHandler(UNNotificationPresentationOptionNone);
}

In this way, when the app is in the foreground, no notification shown while in the background, notification is showing. Hence, this solution is working for us.

all you have to do is clear cache and delete your existing app and try build new cd android && ./gradlew clean && cd .. then react-native run-android

and yeah do the above changes as well this will fix your issue.

coder-dev-phoenix avatar Dec 30 '21 12:12 coder-dev-phoenix

On iOS need notification but without popup when you are in foreground, android is working fine.

rajkhata avatar May 20 '22 09:05 rajkhata