Lia*_*iam 8 android websocket ios react-native react-native-push-notification
我正在使用 React Native 开发聊天应用程序,并且WebSocket在活动模式下一切正常,但是当您按下主页按钮使应用程序处于后台模式时,WebSocket不会触发 onMessage 事件功能
好消息是WebSocket连接仍然连接但未触发事件功能。
我只想在后台模式下收到消息时推送通知。
我做了一项研究,发现我需要始终运行无声的背景音轨(有人说这是非法的方式)。
是否有合法的 API 可以在后台保持连接活跃?
后台模式需要重新连接socket连接吗
我的代码
events = (data) =>{
if(data[0].message){
if(this.state.appState !== 'active'){
console.log('check here') // not working when the app in background mode
PushNotification.localNotification({// not working when the app in background mode
message: data[0].message,
number: 1,
title: 'a new message from: '+data[0].username,
});
}else{
this.setState({messages: data[0]})
}
}
}
socketConnect = () =>{
AsyncStorage.getItem('token').then((token) => {
let connection = new wamp.Connection({ url: 'wss://*******/',
realm: 'realm',
authmethods: ['jwt'],
});
connection.onopen = (session, detalis) => {
session.subscribe('messages', this.events);
};
connection.open();
})
};
Run Code Online (Sandbox Code Playgroud)
我做了一项研究,发现我需要始终运行无声的背景音轨(有人说这是非法的方式)。
是的,这肯定会导致 Apple/Google 应用审核团队的拒绝。
是否有合法的 API 可以在后台保持连接活跃?
实际上你不需要那个(见下面的解决方案)
我假设您有一个服务器,您可以在其中管理所有 websocket 连接并将消息路由到预期的客户端。您可以使用firebase 云消息传递向用户发送 ios/android 推送通知,通知他/她有新消息。当然,您的服务器端和应用程序端都需要 FCM。对于应用程序部分,您可以使用例如react-native-firebase。对于服务器,有几个可用的库。现在有两种情况:
情况1)
如果应用程序已经在前台,您可以通过 FCM(react-native-firebase) 显示 LocalNotification,也可以仅使用 websocket 连接来显示消息。
情况 2)
您的应用程序在后台,您再次通过 FCM 从您的服务器发送推送通知。最大的优势是 FCM 与 Apple Push Notification Service 和 Google Cloud Messaging Service 进行通信(顺便说一句,Google 很快将只使用 FCM)。这意味着您的用户会收到带有预览文本或完整消息的本机推送通知(由您决定)。然后用户单击通知,您的应用程序将再次打开。此时您可以重新连接到您的 websocket,然后您可以继续您的正常应用程序行为。
补充说明:
| 归档时间: |
|
| 查看次数: |
5658 次 |
| 最近记录: |