Socket.io and background and foreground

Hi everyone :slight_smile:

I’m using Ionic 3.x with socket.io to receive real time data.
The issue is, if the user puts the app in the background and it stays there for more than one minute it looses it’s connection to the socket.
If the user then switches from background to foreground the connection does not get reestablished.
My question is? How can you detect if an app switches from background to foreground? I would like to reset the connection as soon as the app enters the foreground again.

The same ‘connection to socket lost issue’ arises, if the user loses his internet connection.
I solved this by calling this function:

  resetSocketConnection(token) {
    this.leaveSocketRoom(token);
    this.socket.connect();
    this.joinSocketRoom(token);
  }

 leaveSocketRoom(token) {
    this.socket.removeAllListeners(SERVER_SOCKET_CHANNEL_UPDATES);
    this.socket.emit(SERVER_SOCKET_LEAVE_ROOM, SERVER_SOCKET + token);
    this.socket.disconnect();
  }

everytime the user connects to the internet.
I did this using network and the onConnect() function. This works and I think I can do the same if the app enters foreground.

I know there is this plugin for background mode, but as far as I understand it, the plugin forces the app to always run in the background. I don’t want that, because that would stress the server and the users battery unnecessarily (I assume).

Any help would be much appreciated! :slight_smile:

basically you want to get events for focus and blur

see discussion here

and event handler sample here
https://ionicframework.com/docs/api/util/Events/

click ‘demo source’ link under image on the right

Thank you for your help!

I found a different solution though, which works perfectly!

this.platform.resume.subscribe(() => {
  this.soSeCoProv.resetSocketConnection(
    this.storageProv.restaurantToken
  );
});
1 Like

thank you… i need to look at the libraries a bit more… platform!..

1 Like