1. 程式人生 > >websocket react-native-push-notification用法

websocket react-native-push-notification用法

  1. 寫下react-native-push-notification的用法,這是用來本地或者websocket接收資料在手機上方通知欄進行提示的
  2. 按照官方文件的做即可

2.1)npm install –save react-native-push-notification

2.2)react-native link react-native-push-notification

2.3)不用修改android/build.gradle這個檔案的ext,現在0.57之後自動會有

2.4)按照官方修改AndroidManifest.xml即可

2.5)不用修改android/settings.gradle這個檔案,安裝react-native-push-notification後,會自動增加上去

2.6)按官方文件增加/app/src/res/values/colors.xml這個檔案

2.7)我們增加了link,所以不需要public class MainApplication extends Application implements ReactApplication這個

2.8)按照他的例子,修改constructor

constructor(props){

        super(props);

        this.state = {

            senderId: 'websocketid'

        };

        this.notif = new NotifService(this.onRegister.bind(this), this.onNotif.bind(this));

    }

  1. 把他的NotifService.js直接copy到我們的目錄
    1. this.notif.localNotif()即可食用
    2. 說下好像websocket接受的e.data出來的是字串,需要JSON.parse()解析成json,

我們可以修改下localNotify()給它傳遞引數,顯示成我們需要的樣子

    1. websocket使用,最好不要把websocket集中方法寫成函式呼叫,那樣子會接收不到資料,最好寫到render()中
    2. 這個提示分成兩種,一種是彈出提示,這沒有顯示bigText,另一種是我們下拉顯示,這個顯示bigText
      demo
      /**
       * Sample React Native App
       * https://github.com/facebook/react-native
       *
       * @format
       * @flow
       */
      
      import React, {Component} from 'react';
      import {
          Platform,
          StyleSheet,
          Text,
          View,
          DeviceEventEmitter,
          TouchableOpacity } from 'react-native';
      import appConfig from "../app";
      import NotifService from "./MyNotifService";
      
      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',
      });
      
      const ws = new WebSocket('ws://192.168.1.31:8080/event');
      
      type Props = {};
      export default class TestWebSocket extends Component<Props> {
      
          constructor(props){
              super(props);
              this.state = {
                  senderId: 'websocketid'
              };
              this.notif = new NotifService(this.onRegister.bind(this), this.onNotif.bind(this));
          }
      
          render() {
              ws.onopen =() =>{
                  console.log("ws.open222");
              }
      
              ws.onmessage =(e) =>{
                  console.log("ws. onMessage22");
                  console.log(e.data);
                  this.showNotify2(e.data);
      
              }
      
              ws.onerror =(e) =>{
                  console.log("ws onerror22");
                  console.log(e);
              }
      
              return (
                  <View style={styles.container}>
                      <TouchableOpacity onPress={() => this.myClose() }>
                          <Text style={styles.welcome}>Welcome to TestWebSocket!</Text>
                      </TouchableOpacity>
      
                      <TouchableOpacity onPress={ () =>this.showNotify2(null)}>
                          <Text style={styles.instructions}>To get started, edit App.js</Text>
                      </TouchableOpacity>
      
                      <Text style={styles.instructions}>{instructions}</Text>
                  </View>
              );
          }
      
          openWebSocket(){//恐怕只有這個呼叫成功了
              ws.onopen =() =>{
                  console.log("ws.open111");
              }
          }
      
          onMsgWebSocket(){//呼叫後接收不到資料
              ws.onmessage =(e) =>{
                  console.log("ws. onMessage");
                  this.showNotify2(e.data);
                  console.log(e.data);
              }
          }
      
          onErrorWebSocket(){//呼叫後接收不到資料
              ws.onerror =(e) =>{
                  console.log("ws onerror");
                  console.log(e);
              }
          }
      
          onCloseWebSocket(){
              ws.onclose = () =>{
                  console.log("ws close");
              }
          }
      
          myClose(){
              console.log("this is close");
              // this.onCloseWebSocket();
              ws.onclose = (e) =>{//為什麼關閉不了
                  console.log("ws close");
              }
          }
      
          onRegister(token) {
              // Alert.alert("Registered !", JSON.stringify(token));
              // console.log(token);
              // this.setState({ registerToken: token.token, gcmRegistered: true });
          }
      
          onNotif(notif) {
              // console.log(notif);
              // Alert.alert(notif.title, notif.message);
          }
      
          handlePerm(perms) {
              // Alert.alert("Permissions", JSON.stringify(perms));
          }
      
          showNotify(){
              this.notif.localNotifTitle('webSocketTest');
          }
      
          showNotify2(data){
              // let a = "{\"type\":\"alarm-raised\",\"alarm\":{\"id\":3386950381,\"wellName\":\"testdjr\",\"wellType\":\"電加熱\",\"type\":\"超限報警\",\"level\":3,\"cause\":\"管線溫度電加熱超限, <38.0 {資料時間-18:6 管線溫度[當前值:23.9] }\",\"timestamp\":1542190025380,\"checkedBy\":-1,\"checkedOn\":null,\"confirmedBy\":-1,\"confirmedOn\":null,\"confirmation\":null,\"secConfirmedBy\":0,\"secConfirmedOn\":null,\"secConfirmation\":null,\"alarmStatus\":0}}";
              // data = JSON.parse(a);
              data = JSON.parse(data);
              this.notif.localNotifTitle(data );
          }
      }
      
      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',
              fontSize:25,
              marginBottom: 5,
          },
      });
      
      
      import PushNotification from 'react-native-push-notification';
      
      export default class NotifService {
      
          constructor(onRegister, onNotification) {
              this.configure(onRegister, onNotification);
      
              this.lastId = 0;
          }
      
          configure(onRegister, onNotification, gcm = "") {
              PushNotification.configure({
                  // (optional) Called when Token is generated (iOS and Android)
                  onRegister: onRegister, //this._onRegister.bind(this),
      
                  // (required) Called when a remote or local notification is opened or received
                  onNotification: onNotification, //this._onNotification,
      
                  // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
                  senderID: gcm,
      
                  // IOS ONLY (optional): default: all - Permissions to register.
                  permissions: {
                      alert: true,
                      badge: true,
                      sound: true
                  },
      
                  // Should the initial notification be popped automatically
                  // default: true
                  popInitialNotification: true,
      
                  /**
                   * (optional) default: true
                   * - Specified if permissions (ios) and token (android and ios) will requested or not,
                   * - if not, you must call PushNotificationsHandler.requestPermissions() later
                   */
                  requestPermissions: true,
              });
          }
      
          checkPermission(cbk) {
              return PushNotification.checkPermissions(cbk);
          }
      
          cancelNotif() {
              PushNotification.cancelLocalNotifications({id: ''+this.lastId});
          }
      
          cancelAll() {
              PushNotification.cancelAllLocalNotifications();
          }
      
      
          localNotifTitle(data) {
              this.lastId++;
              PushNotification.localNotification({
                  /* Android Only Properties */
                  id: ''+this.lastId, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
                  ticker: data.alarm.type, // (optional)
                  autoCancel: true, // (optional) default: true
                  largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
                  smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
                  bigText: data.alarm.cause+"", // (optional) default: "message" prop
                  subText: "subText", // (optional) default: none
                  color: "red", // (optional) default: system default
                  vibrate: true, // (optional) default: true
                  vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
                  tag: 'some_tag', // (optional) add tag to message
                  group: "group", // (optional) add group to message
                  ongoing: false, // (optional) set whether this is an "ongoing" notification
      
                  /* iOS only properties */
                  alertAction: 'view', // (optional) default: view
                  category: null, // (optional) default: null
                  userInfo: null, // (optional) default: null (object containing additional notification data)
      
                  /* iOS and Android properties */
                  title: data.alarm.id+"", // (optional)
                  message: data.alarm.wellName, // (required)
                  playSound: false, // (optional) default: true
                  soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
                  number: '10', // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
                  //actions: '["Yes", "No"]',  // (Android only) See the doc for notification actions to know more
              });
          }
      }