Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


According to the docs you must implement a server for handling push notifications in device to device communication.

Before you can write client apps that use Firebase Cloud Messaging, you must have an app server that meets the following criteria:

Could you help me to understand please. As far as i understand if i need sent direct message from one uset to another i have to use HTTP and sent this message to my server and next server will use FCM to sent Notification to recipent and thus recipent retrive data with id of sender . Next step recipent connect to FCM and with help of ID retrive all data from FCM DB? Such way?

If you only need to send basic notifications to your users from the server. You can use their serverless solution, Firebase Notifications.

Perfect answer, I had researched ab this 2 days. Very full informations ab FCM and sever need or not. Thank you !.

UPDATE: It is now possible to use firebase cloud functions as the server for handling push notifications. Check out their documentation here

You'll need to decide which FCM connection server protocol(s) you want to use to enable your app server to interact with FCM connection servers. Note that if you want to use upstream messaging from your client applications, you must use XMPP. For a more detailed discussion of this, see Choosing an FCM Connection Server Protocol.

good answer. Do you know any tutorials or videos that can explain how to do this? thank you

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


Developers can use Cloud Functions to keep users engaged and up to date with relevant information about an app. Consider, for example, an app that allows users to follow one another's activities in the app. In such an app, a function triggered by Realtime Database writes to store new followers could create Firebase Cloud Messaging (FCM) notifications to let the appropriate users know that they have gained new followers.

Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


I am able to send Firebase messages between devices and notifications using Smack Library. I don't implement any external server in My android code. Smack manages the connection and the incoming/outgoing of message stanzas using the XMPP protocol.

The user won't be using the app all the time and we can't use firebase realtime database in the background since it keeps a persistent socket connection to the server which is too heavy on the battery of the device.

You can use firebase realtime database to do so. You can create data structure for storing chats and add observers for the conversation threads for both users. It still does device - server - device architecture, but in this case there is no additional server on the developers' part. This uses the firebase servers. You can check out a tutorial here (ignore the UI part, although, that is also a good starting point for chat UI frameworks).

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


public class Message {
String to;
NotifyData data;

public Message(String to, NotifyData data) {
    this.to = to;
    this.data = data;
}
}
public class Notification {
String title;
String message;
enter code here`enter code here`
public Notification(String title, String message) {
    this.title = title;
    this.message = message;
}
}
void sendFCMPush(String msg,String token) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", "key="+Const.FIREBASE_LEGACY_SERVER_KEY); // <-- this is the important line
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    httpClient.addInterceptor(logging);
    OkHttpClient client = httpClient.build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://fcm.googleapis.com/")//url of FCM message server
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
            .build();

    // prepare call in Retrofit 2.0
    FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);

    //for messaging server
    NotifyData notifydata = new NotifyData("Chatting", msg);

    Call<Message> call2 = firebaseAPI.sendMessage(new Message(token, notifydata));

    call2.enqueue(new Callback<Message>() {
        @Override
        public void onResponse(Call<Message> call, retrofit2.Response<Message> response) {
            Log.e("#@ SUCCES #E$#", response.body().toString());
        }

        @Override
        public void onFailure(Call<Message> call, Throwable t) {

            Log.e("E$ FAILURE E$#", t.getMessage());
        }
    });
}

The Const.FIREBASE_LEGACY_SERVER_KEY is not safe to be used in client side code. Please at least read the other replies and comments before posting.

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


json.put("to","/topics/foo-bar")
public static final MediaType JSON
        = MediaType.parse("application/json; charset=utf-8");
private void sendNotification(final String reg_token) {
    new AsyncTask<Void,Void,Void>(){
        @Override
        protected Void doInBackground(Void... params) {
            try {
                OkHttpClient client = new OkHttpClient();
                JSONObject json=new JSONObject();
                JSONObject dataJson=new JSONObject();
                dataJson.put("body","Hi this is sent from device to device");
                dataJson.put("title","dummy title");
                json.put("notification",dataJson);
                json.put("to",regToken);
                RequestBody body = RequestBody.create(JSON, json.toString());
                Request request = new Request.Builder()
                        .header("Authorization","key="+Constants.LEGACY_SERVER_KEY)
                        .url("https://fcm.googleapis.com/fcm/send")
                        .post(body)
                        .build();
                Response response = client.newCall(request).execute();
                String finalResponse = response.body().string();
            }catch (Exception e){
                //Log.d(TAG,e+"");
            }
            return null;
        }
    }.execute();

}

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.

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.

The downside is 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. That's why you should never do this.

further if you want to send message to a particular topic, replace 'regToken' in json like this

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


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.

Yes, but this still requires our own external server right? Cause we shouldn't embed the API_KEY directly in our clients. My question was whether this is possible without an external server, which currently isn't as suggested by the other replies.

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


public class Message {
String to;
NotifyData notification;

public Message(String to, NotifyData notification) {
    this.to = to;
    this.notification = notification;
}

}
public class NotifyData {
String title;
String body;

public NotifyData(String title, String body ) {

    this.title = title;
    this.body = body;
}

}
public interface FirebaseAPI {

@POST("/fcm/send")
Call<Message> sendMessage(@Body Message message);

}
public void onClick(View view) {

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", "key=legacy server key from FB console"); // <-- this is the important line
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    httpClient.addInterceptor(logging);
    OkHttpClient client = httpClient.build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://fcm.googleapis.com")//url of FCM message server
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
            .build();

    // prepare call in Retrofit 2.0
    FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);

    //for messaging server
    NotifyData notifydata = new NotifyData("Notification title","Notification body");

Call<Message> call2 = firebaseAPI.sendMessage(new Message("topic or deviceID", notifydata));

    call2.enqueue(new Callback<Message>() {
        @Override
        public void onResponse(Call<Message> call, Response<Message> response) {

            Log.d("Response ", "onResponse");
            t1.setText("Notification sent");

        }

        @Override
        public void onFailure(Call<Message> call, Throwable t) {
            Log.d("Response ", "onFailure");
            t1.setText("Notification failure");
        }
    });
}

You can use Retrofit. Subscribe devices to topic news. Send notification from one device to other.

and

and FirebaseAPI

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


2) send messages inside the application

@AjaySharma as I remember, FMC console doesn't have tools for it, you can make a topic programmatically (see above my pseudo code).

@Maxim Firsoff- How to create a topic from FCM console or any other way ?

Good idea, but: Topic messages are optimized for throughput rather than latency. For fast, secure delivery to single devices or small groups of devices, target messages to registration tokens, not topics.

Wouldn't this still require use of the Authorization key on the client side? Which makes it insecure. Also I don't even know if creating a separate topic for each user is a good idea.

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


Developers can use Cloud Functions to keep users engaged and up to date with relevant information about an app. Consider, for example, an app that allows users to follow one another's activities in the app. In such an app, a function triggered by Realtime Database writes to store new followers could create Firebase Cloud Messaging (FCM) notifications to let the appropriate users know that they have gained new followers.

Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.

Note
Rectangle 27 0

How to send device to device messages using Firebase Cloud Messaging?


Developers can use Cloud Functions to keep users engaged and up to date with relevant information about an app. Consider, for example, an app that allows users to follow one another's activities in the app. In such an app, a function triggered by Realtime Database writes to store new followers could create Firebase Cloud Messaging (FCM) notifications to let the appropriate users know that they have gained new followers.

Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.

Note