当应用程序在后台时,React Native 处理套接字连接的事件?

React Native handle socket connection's events when app is in background?

我正在使用 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();

        })
    };

I did a research and I found that I need to run a silent background audio track at all times(some said this illegal way).

是的,这肯定会导致 Apple/Google 应用审核团队拒绝。

Is there a legal API to keep a connection alive in the background?

实际上你不需要那个(见下面的解决方案)

解决方案:

我假设您有一个服务器,您可以在其中管理所有 websocket 连接并将消息路由到预期的客户端。您可以使用 firebase cloud messaging to send the user an ios/android push notification, which informs him/her that there is a new message. Of course you need FCM on both your server and app side. For the app part you could use for example react-native-firebase. For the server there are several libraries 可用。现在有两种情况:

案例1)

如果应用程序已经在前台,您可以通过 FCM(react-native-firebase) 显示 LocalNotification,或者您只使用 websocket 连接来显示消息。

案例2)

您的应用程序在后台,您再次通过 FCM 从您的服务器发送推送通知。最大的优势是 FCM 与 Apple 推送通知服务和 Google 云消息服务进行通信(顺便说一句 google 很快就会使用 FCM)。这意味着您的用户会收到带有预览文本或完整消息(由您决定)的本机推送通知。然后用户点击通知,您的应用程序再次打开。此时您可以重新连接到您的 websocket,然后您可以继续正常的应用程序行为。

补充说明:

  1. 这可能是唯一合法的方式
  2. 使用 APNS/GMS/FCM 比让应用程序始终处于后台
  3. 更节能