Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm working on Chat app using React native and WebSocket everything works fine in active mode but when you push the home button to make the app in background mode, the WebSocket onMessage events function is not triggered

The good thing is that WebSocket connection is still connected but the events function not triggered.

I just want to push the notification when receiving a message in the background mode.

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).

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

Do I need to re-connect the socket connection in the background mode

My code

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();

        })
    };
like image 209
Liam Avatar asked Apr 29 '19 09:04

Liam


People also ask

Can React Native apps run in background?

In React Native, performing a task in the background might seem daunting at first. It is not as simple as writing a function in JavaScript, where the function is executed even after the activity is killed. Instead, React Native uses Headless JS to execute JavaScript code in the background.

Can we use WebSocket in React Native?

React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.

What is background thread in React Native?

The renderer uses three different threads: UI thread (often called main): The only thread that can manipulate host views. JavaScript thread: This is where React's render phase is executed. Background thread: Thread dedicated to layout.

How to integrate socket Io in React Native?

Please follow all the steps carefully for integrating socket.io in react native, let’s start – We are going to us socket.io-client plugin. Now you can import the plugin in which file you want to integrate the socket. Now we are going to initialise the server connection in componentDid Mount.

How to detect app is in background or foreground using appstate in React Native?

The AppState component in react native is used to notify the user whether the app is in background or foreground and returns a string. So in this tutorial we would Detect App is in Background or Foreground using AppState in react native android iOS application. 1. Import StyleSheet, Text, View & AppState component in your project’s App.js file. 2.

What is 2nd mode in React Native?

Second mode is Background mode in which the app is in background and user is accessing other apps on that time. The AppState component in react native is used to notify the user whether the app is in background or foreground and returns a string.

What is usecontext and usecallback in react?

What is useContext ? Context values are states. React notices their change and triggers re-render. What is useCallback? Why did you put every handlers inside useCallback ? You may forget (or don't bother) to use useCallback. But you may face serious performance issues if there are many states and components in your project


Video Answer


1 Answers

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).

Yes, that would definitely result in a rejection by the Apple/Google app review team.

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

Actually you don't need that (see solution below)

Solution:

I assume you have a server, where you manage all the websocket connections and route the message to the expected client. You can use 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 available. Now there are two cases:

case 1)

If the app is already in the foreground, you can either show a LocalNotification via FCM(react-native-firebase) or you just use your websocket connection to display the message.

case 2)

Your app is in background, again you send a push notification via FCM from your server. The big advantage is that FCM communicates with the Apple Push Notification Service and the Google Cloud Messaging Service (btw google will soon just use FCM). That means your user gets a native push notification with a preview text or a full message (that's up to you). Then the user clicks on the notification and your app opens again. At this point you can reconnect to your websocket and then you can continue with your normal app behavior.

Additional remarks:

  1. This is probably the only legal way
  2. It's much more energy efficient to use APNS/GMS/FCM than keeping the app always in background
like image 156
Tim Avatar answered Sep 20 '22 16:09

Tim