App.js 7.83 KB
Newer Older
Libin Lu's avatar
Libin Lu committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

import { StackNavigator } from 'react-navigation';

import firebase from 'react-native-firebase';

Libin Lu's avatar
Libin Lu committed
22
import {registerAppListener} from "./Listeners";
Libin Lu's avatar
Libin Lu committed
23 24 25 26 27 28 29 30 31 32 33 34 35
import firebaseClient from  "./FirebaseClient";

class MainPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      token: "",
      tokenCopyFeedback: ""
    }
  }

  async componentDidMount(){
Libin Lu's avatar
Libin Lu committed
36 37 38 39 40 41 42
    // Build a channel
    const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
    .setDescription('My apps test channel');

    // Create the channel
    firebase.notifications().android.createChannel(channel);

Libin Lu's avatar
Libin Lu committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    registerAppListener(this.props.navigation);
    firebase.notifications().getInitialNotification()
      .then((notificationOpen: NotificationOpen) => {
        if (notificationOpen) {
          // Get information about the notification that was opened
          const notif: Notification = notificationOpen.notification;
          this.setState({
            initNotif: notif
          })
          if(notif && notif.targetScreen === 'detail'){
            setTimeout(()=>{
              this.props.navigation.navigate('Detail')
            }, 500)
          }
        }
      });

    if (!await firebase.messaging().hasPermission()) {
      try {
        await firebase.messaging().requestPermission();
Libin Lu's avatar
Libin Lu committed
63
      } catch(e) {
Libin Lu's avatar
Libin Lu committed
64 65 66 67 68 69 70 71 72 73 74 75
        alert("Failed to grant permission")
      }
    }

    firebase.messaging().getToken().then(token => {
      console.log("TOKEN (getFCMToken)", token);
      this.setState({token: token || ""})
    });

    // topic example
    firebase.messaging().subscribeToTopic('sometopic');
    firebase.messaging().unsubscribeFromTopic('sometopic');
Libin Lu's avatar
Libin Lu committed
76 77 78 79 80 81 82 83 84 85

    AsyncStorage.getItem('lastNotification').then(data=>{
      if(data){
        // if notification arrives when app is killed, it should still be logged here
        this.setState({
          offlineNotif: JSON.parse(data)
        });
        AsyncStorage.removeItem('lastNotification');
      }
    })
Libin Lu's avatar
Libin Lu committed
86 87
  }

Libin Lu's avatar
Libin Lu committed
88
  componentWillUnmount(){
Libin Lu's avatar
Libin Lu committed
89 90 91 92 93 94
    this.onTokenRefreshListener();
    this.notificationOpenedListener();
    this.messageListener();
  }

  showLocalNotification() {
Libin Lu's avatar
Libin Lu committed
95 96 97 98 99 100 101 102
    let notification = new firebase.notifications.Notification();
    notification = notification.setNotificationId(new Date().valueOf().toString())
    .setTitle( "Test Notification with action")
    .setBody("Force touch to reply")
    .setSound("bell.mp3")
    .setData({
      key1: 'value1',
      key2: 'value2'
Libin Lu's avatar
Libin Lu committed
103
    });
Libin Lu's avatar
Libin Lu committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    notification.ios.badge = 10
    notification.android.setAutoCancel(true);

    notification.android.setBigPicture("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png", "https://image.freepik.com/free-icon/small-boy-cartoon_318-38077.jpg", "content title", "summary text")
    notification.android.setColor("red")
    notification.android.setColorized(true)
    notification.android.setOngoing(true)
    notification.android.setPriority(firebase.notifications.Android.Priority.High)
    notification.android.setSmallIcon("ic_launcher")
    notification.android.setVibrate([300])
    notification.android.addAction(new firebase.notifications.Android.Action("view", "ic_launcher", "VIEW"))
    notification.android.addAction(new firebase.notifications.Android.Action("dismiss", "ic_launcher", "DISMISS"))
    notification.android.setChannelId("test-channel")

    firebase.notifications().displayNotification(notification)
Libin Lu's avatar
Libin Lu committed
119 120 121
  }

  scheduleLocalNotification() {
Libin Lu's avatar
Libin Lu committed
122 123 124 125 126 127 128 129
    let notification = new firebase.notifications.Notification();
    notification = notification.setNotificationId(new Date().valueOf().toString())
    .setTitle( "Test Notification with action")
    .setBody("Force touch to reply")
    .setSound("bell.mp3")
    .setData({
      key1: 'value1',
      key2: 'value2'
Libin Lu's avatar
Libin Lu committed
130
    });
Libin Lu's avatar
Libin Lu committed
131 132 133 134 135
    notification.android.setChannelId("test-channel")
    notification.android.setPriority(firebase.notifications.Android.Priority.High)
    notification.android.setSmallIcon("ic_launcher")

    firebase.notifications().scheduleNotification(notification, { fireDate: new Date().getTime() + 5000 })
Libin Lu's avatar
Libin Lu committed
136 137 138 139 140 141 142 143 144 145 146 147
  }

  sendRemoteNotification(token) {
    let body;

    if(Platform.OS === 'android'){
      body = {
        "to": token,
      	"data":{
					"custom_notification": {
						"title": "Simple FCM Client",
						"body": "Click me to go to detail",
Libin Lu's avatar
Libin Lu committed
148
            data: {targetScreen: 'detail'}
Libin Lu's avatar
Libin Lu committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        	}
    		},
    		"priority": 10
      }
    } else {
			body = {
				"to": token,
				"notification":{
					"title": "Simple FCM Client",
					"body": "Click me to go to detail",
					"sound": "default"
        },
        data: {
          targetScreen: 'detail'
        },
				"priority": 10
			}
		}

    firebaseClient.send(JSON.stringify(body), "notification");
  }

  render() {
    let { token, tokenCopyFeedback } = this.state;

    return (
      <View style={styles.container}>
      <ScrollView style={{paddingHorizontal: 20}}>
        <Text style={styles.welcome}>
          Welcome to Simple Fcm Client!
        </Text>

        <Text style={styles.feedback}>
          {this.state.tokenCopyFeedback}
        </Text>

        <Text style={styles.feedback}>
          Remote notif won't be available to iOS emulators
        </Text>

        <TouchableOpacity onPress={() => this.sendRemoteNotification(token)} style={styles.button}>
          <Text style={styles.buttonText}>Send Remote Notification</Text>
        </TouchableOpacity>

        <TouchableOpacity onPress={() => this.showLocalNotification()} style={styles.button}>
          <Text style={styles.buttonText}>Show Local Notification</Text>
        </TouchableOpacity>

        <TouchableOpacity onPress={() => this.scheduleLocalNotification()} style={styles.button}>
          <Text style={styles.buttonText}>Schedule Notification in 5s</Text>
        </TouchableOpacity>

        <Text style={styles.instructions}>
          Init notif:
        </Text>
        <Text>
Libin Lu's avatar
Libin Lu committed
205 206 207 208 209 210 211 212
          {JSON.stringify(this.state.initNotif)}
        </Text>

        <Text style={styles.instructions}>
          Notif when app was closed:
        </Text>
        <Text>
          {JSON.stringify(this.state.offlineNotif)}
Libin Lu's avatar
Libin Lu committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        </Text>

        <Text style={styles.instructions}>
          Token:
        </Text>
        <Text selectable={true} onPress={() => this.setClipboardContent(this.state.token)}>
          {this.state.token}
        </Text>
        </ScrollView>
      </View>
    );
  }

  setClipboardContent(text) {
    Clipboard.setString(text);
    this.setState({tokenCopyFeedback: "Token copied to clipboard."});
    setTimeout(() => {this.clearTokenCopyFeedback()}, 2000);
  }

  clearTokenCopyFeedback() {
    this.setState({tokenCopyFeedback: ""});
  }
}

class DetailPage extends Component {
  render(){
    return <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Detail page</Text>
    </View>
  }
}

export default StackNavigator({
  Main: {
    screen: MainPage,
  },
  Detail: {
    screen: DetailPage
  }
}, {
  initialRouteName: 'Main',
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 2,
  },
  feedback: {
    textAlign: 'center',
    color: '#996633',
    marginBottom: 3,
  },
  button: {
    backgroundColor: "teal",
    paddingHorizontal: 20,
    paddingVertical: 15,
    marginVertical: 10,
    borderRadius: 10
  },
  buttonText: {
    color: "white",
    backgroundColor: "transparent"
  },
});