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

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Clipboard,
  Platform,
Libin Lu's avatar
Libin Lu committed
15 16
  ScrollView,
  AsyncStorage
Libin Lu's avatar
Libin Lu committed
17 18 19 20 21 22
} from 'react-native';

import { StackNavigator } from 'react-navigation';

import firebase from 'react-native-firebase';

Libin Lu's avatar
Libin Lu committed
23
import {registerAppListener} from "./Listeners";
Libin Lu's avatar
Libin Lu committed
24 25 26 27 28 29 30 31 32 33 34 35 36
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
37 38 39 40 41 42 43
    // 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
44 45 46 47 48 49 50
    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({
Libin Lu's avatar
Libin Lu committed
51
            initNotif: notif.data
Libin Lu's avatar
Libin Lu committed
52 53 54 55 56 57 58 59 60 61 62 63
          })
          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
64
      } catch(e) {
Libin Lu's avatar
Libin Lu committed
65 66 67 68 69 70 71 72 73 74 75 76
        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
77

Libin Lu's avatar
Libin Lu committed
78 79 80 81 82 83 84
    var offline = await AsyncStorage.getItem('headless')
    if(offline){
      this.setState({
        offlineNotif: offline
      });
      AsyncStorage.removeItem('headless');
    }
Libin Lu's avatar
Libin Lu committed
85 86
  }

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

  showLocalNotification() {
Libin Lu's avatar
Libin Lu committed
94 95 96 97 98 99
    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({
Libin Lu's avatar
Libin Lu committed
100
      now: new Date().toISOString()
Libin Lu's avatar
Libin Lu committed
101
    });
Libin Lu's avatar
Libin Lu committed
102 103 104 105 106 107 108 109 110 111 112
    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"))
Libin Lu's avatar
Libin Lu committed
113
    notification.android.addAction(new firebase.notifications.Android.Action("reply", "ic_launcher", "REPLY").addRemoteInput(new firebase.notifications.Android.RemoteInput("input")) )
Libin Lu's avatar
Libin Lu committed
114 115 116
    notification.android.setChannelId("test-channel")

    firebase.notifications().displayNotification(notification)
Libin Lu's avatar
Libin Lu committed
117 118 119
  }

  scheduleLocalNotification() {
Libin Lu's avatar
Libin Lu committed
120 121 122 123 124 125
    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({
Libin Lu's avatar
Libin Lu committed
126
      now: new Date().toISOString()
Libin Lu's avatar
Libin Lu committed
127
    });
Libin Lu's avatar
Libin Lu committed
128 129 130 131 132
    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
133 134 135 136 137 138 139 140 141
  }

  sendRemoteNotification(token) {
    let body;

    if(Platform.OS === 'android'){
      body = {
        "to": token,
      	"data":{
Libin Lu's avatar
Libin Lu committed
142 143 144 145
					"title": "Simple FCM Client",
          "body": "Click me to go to detail",
          targetScreen: 'detail',
          now: new Date().toISOString()
Libin Lu's avatar
Libin Lu committed
146 147 148 149 150 151 152 153 154 155 156 157
    		},
    		"priority": 10
      }
    } else {
			body = {
				"to": token,
				"notification":{
					"title": "Simple FCM Client",
					"body": "Click me to go to detail",
					"sound": "default"
        },
        data: {
Libin Lu's avatar
Libin Lu committed
158 159
          targetScreen: 'detail',
          now: new Date().toISOString()
Libin Lu's avatar
Libin Lu committed
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
        },
				"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
202 203 204 205 206 207 208
          {JSON.stringify(this.state.initNotif)}
        </Text>

        <Text style={styles.instructions}>
          Notif when app was closed:
        </Text>
        <Text>
Libin Lu's avatar
Libin Lu committed
209
          {this.state.offlineNotif}
Libin Lu's avatar
Libin Lu committed
210 211 212 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
        </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"
  },
});