After searching the docs I could not find any info on how to send device to device messages using FCM without the use of an external server.
For example, if I was creating a chat application I would need to send push notifications to users about unread messages since they won't be online all the time and I can't have a persistent service in the background that would always be connected to the real time database because that would be too resource heavy.
So how would I send a push notification to a user "A" when a certain user "B" sends him/her a chat message? Do I need an external server for this or can it be done with just Firebase servers?
1) subscribe an identical topic name, for example:
2) send messages inside the application
GoogleFirebase : How-to send topic messages
Yes, it's possible to do it without any server. You can create a device group client side and then you exchange messages in the group. However there are limitations:
Reference: Firebase doc See the section "Managing device groups on Android client apps"
If you have fcm(gcm) token of the device to whom you want to send notification. It's just a post request to send the notification.
https://github.com/prashanthd/google-services/blob/master/android/gcm/gcmsender/src/main/java/gcm/play/android/samples/com/gcmsender/GcmSender.java
You can use Retrofit. Subscribe devices to topic news. Send notification from one device to other.
POJOs
and
and FirebaseAPI
UPDATE: It is now possible to use firebase cloud functions as the server for handling push notifications. Check out their documentation here
============
According to the docs you must implement a server for handling push notifications in device to device communication.
If you only need to send basic notifications to your users from the server. You can use their serverless solution, Firebase Notifications.
See a comparison here between FCM and Firebase Notifications: https://firebase.google.com/support/faq/#messaging-difference
I figured out like this:-
Making a HTTP POST request with the link "https://fcm.googleapis.com/fcm/send" with required header and data referenced HERE.
Constants.LEGACY_SERVER_KEY is a local class variable, you can find this at your Firebase Project Settings-->CLOUD MESSAGING-->Legacy Server key. You need to pass device registration token(reg_token) in below code snippet referenced HERE.
However you need okhttp library dependency in order to get this snippet work.
further if you want to send message to a particular topic, replace 'regToken' in json like this
and at last don't forget to add INTERNET permission in your AndroidManifest.xml.
IMPORTANT : - Using above code means your server key resides in the client application. That is dangerous as someone can dig into your application and get the server key to send malicious notifications to your users.