- 写下react-native-push-notification的用法,这是用来本地或者websocket接收数据在手机上方通知栏进行提示的
- 按照官方文档的做即可
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));
}
- 把他的NotifService.js直接copy到我们的目录
- this.notif.localNotif()即可食用
- 说下好像websocket接受的e.data出来的是字符串,需要JSON.parse()解析成json,
我们可以修改下localNotify()给它传递参数,显示成我们需要的样子
-
- websocket使用,最好不要把websocket集中方法写成函数调用,那样子会接收不到数据,最好写到render()中
- 这个提示分成两种,一种是弹出提示,这没有显示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 }); } }