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

后端 未结 13 1926
Happy的楠姐
Happy的楠姐 2020-11-22 01:47

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 cr

相关标签:
13条回答
  • 2020-11-22 02:00

    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:

    1. You have to use the same Google account on the devices
    2. You can't send high priority messages

    Reference: Firebase doc See the section "Managing device groups on Android client apps"

    0 讨论(0)
  • 2020-11-22 02:01

    So I had an idea here. See: If the FCM, as well as the GCM, has a endpoit to http request where we can send a post json with our message data, including the token (s) of devices that we want this message to be delivered.

    So why not send a post to Firebase server with this notification to be delivered to user B? you understand ?

    So, you send the message and chat with a call post to ensure delivery of the notification if the user is with your app in the background. I am also in need of it soon, I will test later. What do you say about?

    0 讨论(0)
  • 2020-11-22 02:03

    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

    0 讨论(0)
  • 2020-11-22 02:10

    1) subscribe an identical topic name, for example:

    • ClientA.subcribe("to/topic_users_channel")
    • ClientB.subcribe("to/topic_users_channel")

    2) send messages inside the application

    GoogleFirebase : How-to send topic messages

    0 讨论(0)
  • 2020-11-22 02:11

    You can do it using Volly Jsonobject request....

    follow this Steps first:

    1 copy legacy server key and store it as Legacy_SERVER_KEY

    Legacy Server key

    you can see in picture how to get

    2 You need Volley dependency

    compile 'com.mcxiaoke.volley:library:1.0.19'

    Code for send Push:-

    private void sendFCMPush() {
    
        String Legacy_SERVER_KEY = YOUR_Legacy_SERVER_KEY;
        String msg = "this is test message,.,,.,.";
        String title = "my title";
        String token = FCM_RECEIVER_TOKEN;
    
        JSONObject obj = null;
        JSONObject objData = null;
        JSONObject dataobjData = null;
    
        try {
            obj = new JSONObject();
            objData = new JSONObject();
    
            objData.put("body", msg);
            objData.put("title", title);
            objData.put("sound", "default");
            objData.put("icon", "icon_name"); //   icon_name image must be there in drawable
            objData.put("tag", token);
            objData.put("priority", "high");
    
            dataobjData = new JSONObject();
            dataobjData.put("text", msg);
            dataobjData.put("title", title);
    
            obj.put("to", token);
            //obj.put("priority", "high");
    
            obj.put("notification", objData);
            obj.put("data", dataobjData);
            Log.e("!_@rj@_@@_PASS:>", obj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.e("!_@@_SUCESS", response + "");
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("!_@@_Errors--", error + "");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Authorization", "key=" + Legacy_SERVER_KEY);
                params.put("Content-Type", "application/json");
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        int socketTimeout = 1000 * 60;// 60 seconds
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jsObjRequest.setRetryPolicy(policy);
        requestQueue.add(jsObjRequest);
    }
    

    Just Call sendFCMPush();

    0 讨论(0)
  • 2020-11-22 02:11

    Simplest way :

    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());
            }
        });
    }
    

    Create Class to make Object:

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

    Create Class to make Object:

    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;
    }
    }
    
    0 讨论(0)
提交回复
热议问题