我正在使用 react-native-fcm 接收推送通知。当应用程序通知屏幕仅处于前台状态时它可以正常工作(不能在其他屏幕上工作)。但是我希望在应用程序被杀死或在后台时收到通知或我在我项目的任何其他屏幕上。这是我的代码:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import FCM,{FCMEvent,RemoteNotificationResult,WillPresentNotificationResult,NotificationType} from "react-native-fcm";
let data=[];
FCM.on(FCMEvent.Notification, async(notify)=>{
if(notify.local_notification){
//this is a local notification
console.log('===data =====on=='+JSON.stringify(notify))
}
if(notify.opened_from_tray){
console.log("====tray=======")
}
if(Platform.OS==='android'){
switch(notify.NotificationType){
case NotificationType.Remote:
notify.finish(
RemoteNotificationResult.NewData
)
break;
case NotificationType.NotificationResponse:
notify.finish();
break;
case NotificationType.WillPresent:
notify.finish(WillPresentNotificationResult.All)
break;
}
}
});
FCM.on(FCMEvent.RefreshToken,(token)=>{
console.log(token);
})
export default class HomePage extends Component {
constructor(props){
super(props);
this.state={
totalTarget: null,
targetAchieved:null,
message:null,
notificationsType:null,
extraMessage:null,
}
}
componentDidMount () {
const { navigate } = this.props.navigation;
FCM.requestPermissions().then(()=>console.log('granted')).catch(()=>console.log('notification permission'))
FCM.getFCMToken().then(token=>{
console.log(token)
});
this.notificationListener = FCM.on(FCMEvent.Notification, async(notify)=>{
console.log("===notification---listener===="+JSON.stringify(notify));
this.setState({
totalTarget:notify.totalTarget,
targetAchieved:notify.targetAchieved,
message:notify.message,
notificationsType:notify.notificationsType,
extraMessage:notify.extraMessage
})
navigate("TargetScreenPage",{message:this.state.message,extraMessage:this.state.extraMessage})
})
FCM.getInitialNotification().then(notify=>{
console.log("notification-----"+ JSON.stringify(notify))
})
}
componentWillUnmount(){
this.notificationListener.remove();
}
render() {
return (
<View style={styles.container}>
<Text style={styles.instructions}>
{this.state.totalTarget}
</Text>
<Text style={styles.instructions}>
{this.state.targetAchieved}
</Text>
<Text style={styles.instructions}>
{this.state.message}
</Text>
<Text style={styles.instructions}>
{this.state.notificationsType}
</Text>
<Text style={styles.instructions}>
{this.state.extraMessage}
</Text>
</View>
);
}
}