Instant Messaging Implementation with Firebase Cloud Messaging
<p>I have set up an android app that works with Firebase Cloud Messaging (FCM) in the following way:</p>

<ol>
<li>When my apps starts, it sends sends the FCM token to my app server which stores the token in a database</li>
<li>When a user sends a message, it sends the message to my app server. My app server then retrieves other users' FCM tokens from the database, and sends a request to Google to push the message to those devices</li>
</ol>

<p>This works, but the problem I am facing is determining which FCM tokens to send the message to. Firebase Cloud Messaging works in a way that messages are delivered when the app is running in the background. I do not want this because it's unnecessary and wastes bandwidth for the user and my app server.</p>

<p>So how can I only send FCM messages to devices that have my app open? I cannot simply look at the response from Google when sending FCM messages and then remove all those FCM tokens that failed to send because the response will say the message was successfully sent even if the app is in the background or if the app has been forced stopped.</p>

<p>So, I can think of a few possible solutions, but I am unsure of which is the best. None of them seem like good options.</p>

<ol>
<li>Have my app poll my server every few minutes to tell it that the app is open. (I want to avoid polling because isn't that what FCM is supposed to eliminate?)</li>
<li>Force Firebase Cloud Messaging to delete the token every time the app is paused or destroyed. This will make messages fail to send to the old FCM tokens and then I can delete the failed ones.</li>
<li>Abandon FCM and implement my solution with a TCP connection</li>
</ol>

<p>I'm leaning towards option #2 for now. But it still means my app server has to attempt and fail to send messages to offline devices. Is there a better way that I'm missing?</p>

<p>Thanks.</p>