不显示特定通知React Native

0qx6xfy6  于 2023-01-14  发布在  React
关注(0)|答案(3)|浏览(170)

我不想在特定屏幕中显示“新消息”推送通知类型。我编写了下面的代码,但当我测试它时,我总是得到一个通知。我该如何修复它?

useEffect(() => {
    notificationListener.current = Notifications.addNotificationReceivedListener(
      (notification) => {
        const {
          room_id,
          message_text,
          type,
        } = notification.request.content.data;
      
        
        // I do not want to show NEW_MSG,
         if (type == "NEW_MSG") {
           console.log(notification);
           return;
         }

      }
    );

    return () => {
      // Unsubscribe when component unmmounts
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
    };
  }, []);

注意:我使用Expo通知

z2acfund

z2acfund1#

我相信您需要做的是设置一个自定义通知处理程序,该处理程序引用一个状态变量,您可以使用上面演示的useEffect样式(即componentDidMount函数useEffect样式)在专用屏幕上设置/取消设置该状态变量。
抱歉,我没有先试着自己写,所以可能需要语法上的帮助。但是它应该是这样的...

为您的应用程序设置处理程序函数并使用它来处理您的通知

// The function must refer to a state variable that reacts to whether you're on the screen
let notificationHandlerFn = (notification: Notification) => {
  {
    shouldShowAlert: !onMySuperDuperScreen,   // special state variable
    shouldPlaySound: false,
    shouldSetBadge: false,
  }};

// Register the handler to use the function
Notifications.setNotificationHandler({
  handleNotification: notificationHandlerFn
});

稍后,在你的特别屏幕上

// Use useEffect to control the state variable
useEffect(() => {
    onMySuperDuperScreen = true;

    return () => {
      onMySuperDuperScreen = false;
    };
  }, []);

详细信息请看这里的世博会文档。阅读标题为“当应用程序处于前台时处理传入通知”的部分。

polhcujo

polhcujo2#

有了这个类(Android),你可以覆盖博览会通知服务,并决定是否显示推送通知。

import expo.modules.notifications.notifications.JSONNotificationContentBuilder;
import expo.modules.notifications.notifications.interfaces.NotificationsScoper;
import expo.modules.notifications.notifications.model.Notification;
import expo.modules.notifications.notifications.model.NotificationContent;
import expo.modules.notifications.notifications.model.NotificationRequest;
import expo.modules.notifications.notifications.model.triggers.FirebaseNotificationTrigger;
import expo.modules.notifications.notifications.service.NotificationsHelper;
import expo.modules.notifications.tokens.interfaces.FirebaseTokenListener;

public class FirebaseMessageService extends FirebaseMessagingService {

@Override
  public void onCreate() {
    super.onCreate();
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    
    try {
        
        JSONObject json = new JSONObject(remoteMessage.getData());
        JSONObject body = new JSONObject(json.getString("body"));
        
        if (body...) {  //HERE YOUR CONDITIONS
            
            //NOT SHOW RETURN:
            return;
            
        }else{
            
            //SHOW EXPO NOTIFICATION
            createNotificationsHelper().notificationReceived(createNotification(remoteMessage));

        }
    }
    catch (Exception e){
        
    }   
}

public void sendRegistrationToServer(String token) {
}

protected NotificationsHelper createNotificationsHelper() {
  return new NotificationsHelper(this, NotificationsScoper.create(this).createReconstructor());
}

protected Notification createNotification(RemoteMessage remoteMessage) {
  String identifier = remoteMessage.getMessageId();
  if (identifier == null) {
    identifier = UUID.randomUUID().toString();
  }
  JSONObject payload = new JSONObject(remoteMessage.getData());
  NotificationContent content = new JSONNotificationContentBuilder(this).setPayload(payload).build();
  NotificationRequest request = createNotificationRequest(identifier, content, new FirebaseNotificationTrigger(remoteMessage));
  return new Notification(request, new Date(remoteMessage.getSentTime()));
}

protected NotificationRequest createNotificationRequest(String identifier, NotificationContent content, FirebaseNotificationTrigger notificationTrigger) {
  return new NotificationRequest(identifier, content, notificationTrigger);
}

}
在您清单中:

<service
    android:name=".FirebaseMessageService"
    android:exported="false">
    <intent-filter android:priority="-1">
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
  </service>
e4eetjau

e4eetjau3#

这是我的解决方案-你可以检查通知数据,并确定是否要显示它的警报和播放警报声。

// https://docs.expo.dev/versions/latest/sdk/notifications/#handling-incoming-notifications-when-the-app-is-in-foreground
    Notifications.setNotificationHandler({
      handleNotification: async (notification) => {
        let shouldShow;

        // will not show alert and sound if we already in this chat
        const chatId = notification?.request?.content?.data?.chatId;
        const currentRouteNameIsChat = navigationRef.getCurrentRoute().name === "Chat";
        const currentRouteChatIdIsSame = navigationRef.getCurrentRoute().params?.chatId == chatId;

        if (chatId && currentRouteNameIsChat && currentRouteChatIdIsSame) {
          shouldShow = false;
        } else {
          shouldShow = true;
        }

        return {
          shouldShowAlert: shouldShow,
          shouldPlaySound: shouldShow,
          shouldSetBadge: false,
        };
      },
    });

setNotificationHandler文件:https://docs.expo.dev/versions/latest/sdk/notifications/#setnotificationhandlerhandler-notificationhandler--null-void

相关问题