我正在与Expo一起开发本机消息应用程序。每当用户收到新消息时,我都会从服务器发送通知。
如果应用当前处于打开状态,有什么方法不显示通知?
现在,我会在收到通知后立即使用它:
Notifications.dismissNotificationAsync(notification.notificationId);
但是有0.5秒的延迟,通知有时间出现在托盘中并在被取消之前触发声音。我根本不想显示它。
答案 0 :(得分:1)
您的问题的答案是是
<块引用>有没有办法不显示通知,如果应用程序是 目前开放?
Notification in Expo 的默认行为是在应用程序处于前台时不显示通知。您必须实现了类似于以下代码的 Notifications.setNotificationHandler
-
// *** DON'T USE THE FOLLOWING CODE IF YOU DON'T WANT NOTIFICATION TO BE DISPLAYED
// WHILE THE APP IS IN FOREGROUND! ***
// --------------------------------------------------
// Sets the handler function responsible for deciding
// what to do with a notification that is received when the app is in foreground
/*
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
*/
如果您不使用 setNotificaitonHandler,当应用处于前台时将不会显示新通知。
答案 1 :(得分:0)
我假设您设置了一个简单的FCM-Firebase cloud messaging 并使用该消息将消息推送到客户端? The official Expo guide has a sample code手动处理通知,除非您的代码,否则避免显示任何内容。
import React from 'react';
import {
Notifications,
} from 'expo';
import {
Text,
View,
} from 'react-native';
// This refers to the function defined earlier in this guide
import registerForPushNotificationsAsync from './registerForPushNotificationsAsync';
export default class AppContainer extends React.Component {
state = {
notification: {},
};
componentDidMount() {
registerForPushNotificationsAsync();
// Handle notifications that are received or selected while the app
// is open. If the app was closed and then opened by tapping the
// notification (rather than just tapping the app icon to open it),
// this function will fire on the next tick after the app starts
// with the notification data.
this._notificationSubscription = Notifications.addListener(this._handleNotification);
}
_handleNotification = (notification) => {
this.setState({notification: notification});
};
render() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Origin: {this.state.notification.origin}</Text>
<Text>Data: {JSON.stringify(this.state.notification.data)}</Text>
</View>
);
}
}
答案 2 :(得分:0)
这是FCM的实际工作流程(很奇怪,可以称为常见问题),当应用程序处于前台时,它将自行处理通知。
我为我的项目所做的解决方案是创建一个自定义通知JSON,而不是使用FCM无法解析的默认模板。
{
"hello":" custom key and value",
"message":{
"SampleKey":"Sample data",
"data":{
"SampleKey" : "Sampledata",
"SampleKey2" : "great match!"},
}}
在控制台中,您可以添加自己的自定义JSON对象,当您收到通知时,可以使用这些对象解析通知,然后就可以覆盖该问题。
您还可以为请求添加一个通道,以对通知进行分类
this.createNotificationListeners = firebase.notifications()
.onNotification((notification) => {
let{ hello,data,message} = notification;
});
答案 3 :(得分:0)
使用以下代码段。它适用于新闻通知。
_handleNotification = async (notification) => {
const {origin} = notification;
if (origin === ‘selected’) {
this.setState({notification: notification});
}
//OR
if (AppState.currentState !== 'active') {
this.setState({notification: notification});
}
}