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

标签 android ios react-native websocket react-native-push-notification

我正在使用 React native 和 WebSocket 开发聊天应用程序,在 Activity 模式下一切正常,但是当您按下主页按钮使应用程序处于后台模式时,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向用户发送 ios/android 推送通知,通知他/她有一条新消息。当然,您的服务器端和应用程序端都需要 FCM。对于应用程序部分,您可以使用例如 react-native-firebase .对于服务器,有几个 libraries可用的。现在有两种情况:

案例一)

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

案例2)

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

补充说明:

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

关于android - 当应用程序在后台时,React Native 处理套接字连接的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55900662/

相关文章:

react-native - 将 Ignite 与 create-react-native-app 结合使用

android - eclipse 中没有 std::find() 的匹配函数。在 XCode 中运行良好

Android 与多显示器

android - 焦点在 ListView 中无法正常工作

android - Api 21 循环显示动画不起作用

ios - 为什么这种随机颜色方法不起作用?

ios - 当iphone到达某个位置时如何触发警报?

ios - iOS和watchOS(Objective-C)具有不同方法的相同类对象

javascript - React Native - 授予权限后切换到其他屏幕

javascript - react native : how to use require(path) with dynamic urls?