我是React Native开发的新手,我正在使用WebSocket开发聊天应用程序。
我可以发送和接收消息,但是当消息来自频道时,我需要显示本地通知。
我收到消息,并且可以在打开应用程序时显示通知,但是,如果它在后台运行,则不会收到通知。
仅供参考:我没有关闭该应用程序,打开了另一个应用程序,如WhatsApp或其他应用程序,如果收到消息,则通知也不会显示。
对于本地推送通知,正在使用:
https://www.npmjs.com/package/react-native-push-notification
“ react-native-push-notification”:“ 3.1.1”
“反应本机”:“ 0.59.8”
我不想使用FCM之类的任何第三方服务
下面是获取和显示通知的代码
import React, {Component} from 'react';
import {Socket} from 'phoenix-socket';
import AsyncStorage from "@react-native-community/async-storage";
import PushNotification from 'react-native-push-notification';
class SocketConnection extends React.Component {
constructor(props) {
console.log('Socket constructor');
super(props);
this.state = {
user_id: '',
company_id: '',
msg: {}
};
PushNotification.configure({
onNotification: function (notification) {
console.log('NOTIFICATION: ', notification);
},
popInitialNotification: true,
requestPermissions: true,
});
}
componentDidMount() {
this.getMessage();
};
getMessage = async () => {
var thatclass = this;
let user = await AsyncStorage.getItem('currentUser');
user = JSON.parse(user);
this.setState({user_id: user.user.id});
this.setState({company_id: user.user.company_id});
console.log('Socket constructor');
this.socket = new Socket('ws://localhost:4000/socket/websocket');
this.socket.connect();
const that = this;
this.socket.onError(function (er) {
console.log('Error');
console.log(er);
that.socket.close();
});
this.socket.onOpen(function (res) {
console.log('Open');
console.log(res)
});
this.channel = this.socket.channel("channel:" + user.user.company_id, {});
this.channel.join()
.receive("ok", resp => {
console.log(resp)
})
.receive("error", resp => {
console.log(resp)
});
if (this.channel) {
this.channel.on('users:' + user.user.id, function (payload) {
console.log(payload);
this.setState = ({
msg: payload,
});
thatclass.sendNotification(payload);
});
}
}
sendNotification(payload) {
console.log(payload);
PushNotification.localNotification({
foreground: true, // BOOLEAN: If the notification was received in foreground or not
userInteraction: false,
ticker: "My Notification Ticker", // (optional)
bigText: payload.message, // (optional) default: "message" prop
color: "red", // (optional) default: system default
priority: "high", // (optional) set notification priority, default: high
visibility: "private", // (optional) set notification visibility, default: private
/* iOS and Android properties */
title: payload.subject, // (optional)
message: "My Notification Message", // (required)
playSound: true, // (optional) default: true
actions: '["archive", "reply"]',
});
};
openIndex(id) {
console.log(id);
}
render() {
return (null);
}
}
export default SocketConnection;