BastianW
BastianW

Reputation: 270

Cordova / Phonegap receive push data even if app is in background

I build an app which receives data from a server. To receive data in realtime, I use socketIO, which works well when the app is currently opened.

Now I want to receive data from the server, even if the app is in background or device is restarted.

So:

  1. Server has new data (object) to send to specific users
  2. Server sends data to specific users
  3. Users get data in background and saves it locally
  4. Notify if data is relevant

I read about this plugin https://github.com/phonegap-build/PushPlugin but I want to save the data first and let the app decide then when data ist relevant to notify the user.

Thanks for help!

Upvotes: 1

Views: 1862

Answers (2)

Jay
Jay

Reputation: 1478

To receive data from socket.io server when the app is in background, I suggest you develop a Background Native Service which can keep running even when user is not using the app in foreground. You can use Socket.IO java client library like https://github.com/nkzawa/socket.io-client.java as your starting point.

Upvotes: 0

Jesper We
Jesper We

Reputation: 6087

Push notifications (PN) are handled by the phone OS (It works kind of similar in both Android and iOS). After the app has registered itself as a receiver of PNs, the actual notification is sent by the GCM or APNS server to the device, where it is received by the OS. The OS checks if the target app of the PN is running in the foreground, and in this case it delivers the PN as an event to the app. In your case you can now choose to just keep the data, or also display an alert.

But if the app is not running, or if it is paused, and the PN contains a message ("alert" property on iOS, "message" on Android) the OS displays a notification to the user, without involving the app at all. It is only if and when user klicks or slides the notification that the event is propagated to the app. So a PN with a message will not work for you, because the user sees the notification before your app can process and filter the data.

To make your scenario work you need to send the PN without message/alert. This way you should get it delivered straight to your app even if it is in the background. You will then need to implement your own local notification, but there is a plugin for that too.

It is more complex to get this to work on iOS, since it restricts what an app can do while it is not in the foreground. Read here, also the section titled "Fetching Small Amounts of Content Opportunistically" which give an alternative approach for iOS.

Upvotes: 2

Related Questions