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
              });
          }
      }
要实现在 React Native 中建立 WebSocket 连接并进行心跳检测,可以参考以下步骤: 1. 安装 `react-native-websocket` 库 ``` npm install --save react-native-websocket ``` 2. 在需要使用 WebSocket 的组件中导入并创建 WebSocket 实例,并添加心跳检测逻辑 ```javascript import React, { Component } from 'react'; import { View } from 'react-native'; import WebSocket from 'react-native-websocket'; class MyComponent extends Component { constructor(props) { super(props); this.state = { ws: null, }; } componentDidMount() { const ws = new WebSocket('ws://localhost:3000'); this.setState({ ws }); // 心跳检测 ws.onopen = () => { console.log('WebSocket connected'); this.pingInterval = setInterval(() => { if (ws.readyState === ws.OPEN) { ws.send(JSON.stringify({ type: 'ping' })); } }, 5000); }; // 接收服务端消息 ws.onmessage = (evt) => { console.log(`Received message: ${evt.data}`); }; // WebSocket 断开处理 ws.onclose = () => { console.log('WebSocket closed'); clearInterval(this.pingInterval); }; } componentWillUnmount() { const { ws } = this.state; if (ws) { ws.close(); clearInterval(this.pingInterval); } } render() { return <View />; } } export default MyComponent; ``` 在上述代码中,我们创建了一个 WebSocket 实例,并在 `componentDidMount` 生命周期钩子中添加了心跳检测逻辑。这里我们使用了 `setInterval` 定时发送 `ping` 消息,并在 `onmessage` 回调中处理服务端返回的消息。在 `onclose` 回调中清除定时器。 3. 注意事项 - 在组件卸载时,需要关闭 WebSocket 连接并清除心跳检测定时器,以免引起内存泄漏; - 心跳检测的时间间隔需要根据具体业务需求进行调整; - 需要注意处理 WebSocket 连接异常情况,例如网络异常或服务端关闭连接等;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值