How to send one to one message using Firebase Messaging

Solution for How to send one to one message using Firebase Messaging
is Given Below:

I have been trying to read the official docs and guides about how to send message from one device to another. I have saved registration token of both devices in the Real Time Database, thus I have the registration token of another device.
I have tried the following way to send the message

RemoteMessage message = new RemoteMessage.Builder(getRegistrationToken())
                    .addData("message", "Hello")

However this is not working. The other device doesn’t receive any message. I am not even sure, if I can use upstream message sending to conduct device to device communication.

PS: I just want to know if device-to-device messaging is possible using FCM? If yes, then is the code I used have some issue? If yes, then what is the correct way.

My question was to ask whether device to device messaging without using any separate server other than firebase could messaging is possible or not, if yes than how, since there’s no documentation about it. I do not understand what is left to explain here? Anyways I got the answer and will update it as an answer once the question gets reopened.

Firebase has two features to send messages to devices:

  • the Notifications panel in your Firebase Console allows you to send notifications to specific devices, groups of users, or topics that users subscribed to.
  • by calling Firebase Cloud Messaging API, you can send messages with whatever targeting strategy you prefer. Calling the FCM API requires access to your Server key, which you should never expose on client devices. That’s why you should always run such code on an app server.

The Firebase documentation shows this visually:

The two ways to send messages to device with Firebase

Sending messages from one device directly to another device is not supported through Firebase Cloud Messaging.

Update: I wrote a blog post detailing how to send notifications between Android devices using Firebase Database, Cloud Messaging and Node.js.

Update 2: You can now also use Cloud Functions for Firebase to send messages securely, without spinning up a server. See this sample use-case to get started. If you don’t want to use Cloud Functions, you can run the same logic on any trusted environment you already have, such as your development machine, or a server you control.

Warning There is a very important reason why we don’t mention this approach anywhere. This exposes your server key in the APK that
you put on every client device. It can (and thus will) be taken from
there and may lead to abuse of your project. I highly recommend
against taking this approach, except for apps that you only put on
your own devices. – Frank van Puffelen

Ok, so the answer by Frank was correct that Firebase does not natively support device to device messaging. However there’s one loophole in that. The Firebase server doesn’t identify whether you have send the request from an actual server or are you doing it from your device.

So all you have to do is send a Post Request to Firebase‘s messaging server along with the Server Key. Just keep this in mind that the server key is not supposed to be on the device, but there’s no other option if you want device-to-device messaging using Firebase Messaging.

I am using OkHTTP instead of default way of calling the Rest API. The code is something like this –

public static final String FCM_MESSAGE_URL = "";
OkHttpClient mClient = new OkHttpClient();
public void sendMessage(final JSONArray recipients, final String title, final String body, final String icon, final String message) {

        new AsyncTask<String, String, String>() {
            protected String doInBackground(String... params) {
                try {
                    JSONObject root = new JSONObject();
                    JSONObject notification = new JSONObject();
                    notification.put("body", body);
                    notification.put("title", title);
                    notification.put("icon", icon);

                    JSONObject data = new JSONObject();
                    data.put("message", message);
                    root.put("notification", notification);
                    root.put("data", data);
                    root.put("registration_ids", recipients);

                    String result = postToFCM(root.toString());
                    Log.d(TAG, "Result: " + result);
                    return result;
                } catch (Exception ex) {
                return null;

            protected void onPostExecute(String result) {
                try {
                    JSONObject resultJson = new JSONObject(result);
                    int success, failure;
                    success = resultJson.getInt("success");
                    failure = resultJson.getInt("failure");
                    Toast.makeText(getCurrentActivity(), "Message Success: " + success + "Message Failed: " + failure, Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    Toast.makeText(getCurrentActivity(), "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();

String postToFCM(String bodyString) throws IOException {
        RequestBody body = RequestBody.create(JSON, bodyString);
        Request request = new Request.Builder()
                .addHeader("Authorization", "key=" + SERVER_KEY)
        Response response = mClient.newCall(request).execute();
        return response.body().string();

I hope Firebase will come with a better solution in future. But till then, I think this is the only way. The other way would be to send topic message or group messaging. But that was not in the scope of the question.

The JSONArray is defined like this –

JSONArray regArray = new JSONArray(regIds);

regIds is a String array of registration ids, you want to send this message to. Keep in mind that the registration ids must always be in an array, even if you want it to send to a single recipient.

I have also been using direct device to device gcm messaging in my prototype. It has been working very well. We dont have any server. We exchange GCM reg id using sms/text and then communicate using GCM after that. I am putting here code related to GCM handling

**************Sending GCM Message*************

//Sends gcm message Asynchronously
public class GCM_Sender extends IntentService{
    final String API_KEY = "****************************************";

    //Empty constructor
    public GCM_Sender() {

    //Processes gcm send messages
    protected void onHandleIntent(Intent intent) {  

        Log.d("Action Service", "GCM_Sender Service Started");
        //Get message from intent
        String msg = intent.getStringExtra("msg");
        msg =  """ + msg + """;
            String ControllerRegistrationId = null;                 
            //Check registration id in db       
            if(RegistrationIdAdapter.getInstance(getApplicationContext()).getRegIds().size() > 0 ) {
                String controllerRegIdArray[] = RegistrationIdAdapter.getInstance(getApplicationContext()).getRegIds().get(1);
                    ControllerRegistrationId = controllerRegIdArray[controllerRegIdArray.length-1];

                    // 1. URL
                    URL url = new URL("");
                    // 2. Open connection
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    // 3. Specify POST method
                    // 4. Set the headers
                    urlConnection.setRequestProperty("Content-Type", "application/json");
                    urlConnection.setRequestProperty("Authorization", "key=" + API_KEY);
                    // 5. Add JSON data into POST request body
                    JSONObject obj = new JSONObject("{"time_to_live": 0,"delay_while_idle": true,"data":{"message":" + msg + "},"registration_ids":[" + ControllerRegistrationId + "]}");
                    // 6. Get connection output stream
                    OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                    // 6. Get the response
                    int responseCode = urlConnection.getResponseCode();

                    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null){
                    Log.d("GCM getResponseCode:", new Integer(responseCode).toString());
                    Log.d("GCM_Sender:","Field REGISTRATION_TABLE is null");
            }else {
                Log.d("GCM_Sender:","There is no Registration ID in DB ,please sync devices");
        } catch (Exception e) {
            //MessageSender.getInstance().sendMessage(msg, Commands.SMS_MESSAGE);

    //Called when service is no longer alive
    public void onDestroy() {
        //Do a log that GCM_Sender service has been destroyed
        Log.d("Action Service", "GCM_Sender Service Destroyed");

**************Receiving GCM Message*************

public class GCM_Receiver extends WakefulBroadcastReceiver {
    public static final String RETRY_ACTION ="";
    public static final String REGISTRATION ="";
    public SharedPreferences preferences;

    //Processes Gcm message .
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(),
        //Start GCMNotificationIntentService to handle gcm message asynchronously
        startWakefulService(context, (intent.setComponent(comp)));

        /*//Check if DatabaseService is running .
        if(!DatabaseService.isServiceRunning) {
            Intent dbService = new Intent(context,DatabaseService.class);
        //Check if action is RETRY_ACTION ,if it is then do gcm registration again .
        if(intent.getAction().equals(RETRY_ACTION)) {
            String registrationId = intent.getStringExtra("registration_id");

            }else {
                //Save registration id to prefs .
                preferences = PreferenceManager.getDefaultSharedPreferences(context);
                SharedPreferences.Editor editor = preferences.edit();
        } else if (intent.getAction().equals(REGISTRATION)) {


//Processes gcm messages asynchronously .
public class GCMNotificationIntentService extends IntentService{
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    String gcmData;
    private final String TAG = "GCMNotificationIntentService";

    //Constructor with super().
    public GCMNotificationIntentService() {

    //Called when startService() is called by its Client .
    //Processes gcm messages .
    protected void onHandleIntent(Intent intent) {

        Log.d("GCMNotificationIntentService", "GCMNotificationIntentService Started");
        Bundle extras = intent.getExtras();
        //Get instance of GoogleCloudMessaging .
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        //Get gcm message type .
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                sendNotification("Deleted messages on server: "
                        + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

                gcmData = extras.getString("message");
                Intent actionService = new Intent(getApplicationContext(),Action.class);    
                actionService.putExtra("data", gcmData);
                //start Action service .

                //Show push notification .
                sendNotification("Action: " + gcmData);
                //Process received gcmData.

                Log.d(TAG,"Received Gcm Message from Controller : " + extras.getString("message"));

    //Shows notification on device notification bar .
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent notificationIntent = new Intent(this, BlackboxStarter.class);
        //Clicking on GCM notification add new layer of app.
        notificationIntent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                .setContentTitle("Notification from Controller")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
        //Play default notification
        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        } catch (Exception e) {

    //Called when service is no longer be available .
    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.d("GCMNotificationIntentService", "GCMNotificationIntentService Destroyed");


According to the new documentation which was updated on October 2, 2018 you must send post request as below
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA //Server key

    "to": "sent device's registration token",
    "data": {
       "hello": "message from someone",

To get device’s registration token extend FirebaseMessagingService and override onNewToken(String token)
For more info refer to doc

I am late but above solutions has helped me to write down this simple answer, you can send your message directly to android devices from android application, here is the simple implementation I have done and it works great for me.

  1. compile android volley library

    compile ''
  2. Just copy paste this simple function 😉 and your life will become smooth just like knife in butter. 😀

    public static void sendPushToSingleInstance(final Context activity, final HashMap dataValue /*your data from the activity*/, final String instanceIdToken /*firebase instance token you will find in documentation that how to get this*/ ) {
    final String url = "";
    StringRequest myReq = new StringRequest(Request.Method.POST,url,
            new Response.Listener<String>() {
                public void onResponse(String response) {
                    Toast.makeText(activity, "Bingo Success", Toast.LENGTH_SHORT).show();
            new Response.ErrorListener() {
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(activity, "Oops error", Toast.LENGTH_SHORT).show();
            }) {
        public byte[] getBody() throws {
            Map<String, Object> rawParameters = new Hashtable();
            rawParameters.put("data", new JSONObject(dataValue));
            rawParameters.put("to", instanceIdToken);
            return new JSONObject(rawParameters).toString().getBytes();
        public String getBodyContentType()
            return "application/json; charset=utf-8";
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "key="+YOUR_LEGACY_SERVER_KEY_FROM_FIREBASE_CONSOLE);
            return headers;

If you want to send message to topics so you can change parameter instanceIdToken to something like /topics/topicName.
For groups implementation is the same but you just need to take care of parameters. checkout Firebase documentation and you can pass those parameters.
let me know if you face any issue.