Chat App for Android using a XMPP Server and Google Cloud Messaging (or the newer Firebase Cloud Messaging) for Push Notifications

Santiago Fermín picture Santiago Fermín · Jul 3, 2016 · Viewed 12.5k times · Source

I'm developing a Chat App for Android. I have been reading for weeks about XMPP and Google Cloud Messaging (and Firebase Cloud Messaging) and I am still very confused.

Currently, I already setup an XMPP server locally (Ejabberd) and successfully connected my Android App to it using the Smack library.

To my understanding, I need to use GCM or the newer FCM for Push Notifications, so I already created a project in Google Cloud Platform. My Android App can connect to it using the Smack library too (instead of connecting to my XMPP server directly). In my server I have an small Java app that connects to GCM using the Smack library too.

Everything is fine until here. My big confusion is: How can I use my XMPP server with GCM for Push Notifications? Every documentation, examples, guides, tutorials I found for server-side implementations just tell me how to connect to GCM but none tell me how to use my XMPP server in conjunction with GCM. What I'm missing? My Java app just connects to GCM, receive and send messages from and to GCM, but my XMPP server is just sitting there doing nothing. Actually my Android App and server Java App use GCM exclusively, not my XMPP server.

I hope someone can help me to understand this as a whole, I am obviously missing some key elements to achieve this implementation.

Answer

Nimrod Dayan picture Nimrod Dayan · Aug 4, 2016

You need to mix both Ejabberd and FCM together, that's how all the big chat apps do it out there. For the very basics, there are 3 components: App Server connected via XMPP to FCM, Ejabberd and your client app.

  1. When the app is in the foreground, you use Smack library to connect directly to your Ejabberd server, send messages, change user's presence, etc. The connection to your Ejabberd is kept during that time. You don't send upstream messages during this time!
  2. Once the user navigates away from your app, you close the connection. The user is now considered "Away" or "Offline".
  3. From this point and on, your App Server communicates with FCM to send downstream messages to the device using Smack library as well.
  4. On the client device: You handle the incoming message and show a notification. With Android N, users can reply directly from the notification. I assume that in this case, you would use FCM to send an upstream message to your app server since during that time, there's no active connection to your Ejabberd server.
  5. Once the user taps on the notification, the app comes back to foreground and you re-connect to Ejabberd and back to step 1.

This is the very basic description of the architecture you should have to achieve what you want.