如何在应用程序被杀或后台反应原生时显示FCM推送通知?

时间:2018-03-23 09:57:51

标签: android ios react-native react-native-fcm react-native-push-notification

我正在使用react-native-FCM并尝试显示来自其他客户端的通知,当应用程序位于前台时它正常工作并触发我要显示通知数据的屏幕但是当应用程序位于背景或杀死它不会触发通知屏幕。所以,我想知道当应用程序被杀或在后台时如何触发应用程序通知屏幕。提前谢谢。任何帮助将不胜感激。这是我的代码:

homepage.js

    import React, { Component } from 'react';
    import {
      Platform,
      StyleSheet,
      Text,
      View
    } from 'react-native';

    import FCM,{FCMEvent,RemoteNotificationResult,WillPresentNotificationResult,NotificationType,NotificationActionType,NotificationActionOption,NotificationCategoryOption} from "react-native-fcm";

    let data=[];
    FCM.on(FCMEvent.Notification, async(notify)=>{
      if(notify.local_notification){
        //this is a local notification
      }
      if(notify.opened_from_tray){

            navigation.navigate('TargetScreenPage')


      }
      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,
          token: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.setState({token:token})
        });

        this.notificationListener = FCM.on(FCMEvent.Notification, async(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.token}
            </Text> */}
             <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>                                                       
        );
      }
    }
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 40,
        textAlign: 'center',
        margin: 10,
      },
      instructions: {
        fontSize:40,
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
        flexDirection:'row'
      },              
    });

和TargetScreen.js

import React, { Component } from 'react';
import {ImageBackground,
  Platform,StyleSheet,BackHandler,Image,TouchableOpacity,Text,StatusBar,View} from 'react-native';
import { Header,Right} from 'native-base';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class TargetScreen extends Component {

    handleCrossButtonClick() {
        this.props.navigation.goBack(null);
        return true;
    }                      

  render() {
    const { params } = this.props.navigation.state;
    return (
    <View style={{flex:1,backgroundColor: '#fff'}}>
    <StatusBar hidden = {true} />
    <Header style={{ backgroundColor: "#fff" ,justifyContent:'center',alignItems:'center'}}>
        <Image style={{height:45,width:90,resizeMode: "stretch",marginLeft:95}} source={require('./images/salesLineLogo.jpg')} />
        <Right>      
        <TouchableOpacity onPress={()=>this.handleCrossButtonClick()}>
        <Image style={{height:25,width:25,resizeMode: "stretch"}} source={require('./images/cross.png')}/>      
        </TouchableOpacity></Right>               
     </Header>        
     <View style={{flex:0.5,justifyContent:'center',alignItems: 'center'}}>
    <ImageBackground source={require('./images/up-arrow.png')} style={{ resizeMode: "stretch",height: 95, width: 95,justifyContent:'center',alignItems:'center' }} >
    <Text style={{fontSize:20}}>8</Text></ImageBackground>
    <Text style={{fontSize:20,marginTop:25}}>{params.message}</Text>
    </View>
    <View style={{flex:0.5,justifyContent:'center',alignItems:'center'}}>
    <ImageBackground source={require('./images/up-arrow.png')} style={{ resizeMode: "stretch",height: 95, width: 95,justifyContent:'center',alignItems:'center'}} >
    <Text style={{fontSize:20}}>8</Text></ImageBackground> 
    <Text style={{fontSize:20,marginTop:25}}>{params.extraMessage}</Text>
    </View></View>               
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

0 个答案:

没有答案