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

后端 未结 13 1925
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:13

    In my case I use retrofit with this class Message:

    public class Message {
    
        private String to;
        private String collapseKey;
        private Notification notification;
        private Data data;
    
        public Message(String to, String collapseKey, Notification notification, Data data) {
            this.to = to;
            this.collapseKey = collapseKey;
            this.notification = notification;
            this.data = data;
        }
    }
    

    Data

    public class Data {
    
        private String body;
        private String title;
        private String key1;
        private String key2;
    
        public Data(String body, String title, String key1, String key2) {
            this.body = body;
            this.title = title;
            this.key1 = key1;
            this.key2 = key2;
        }
    }
    

    Notification

    public class Notification {
    
        private String body;
        private String title;
    
        public Notification(String body, String title) {
            this.body = body;
            this.title = title;
        }
    }
    

    this the call

    private void sentToNotification() {
        String to = "YOUR_TOKEN";
        String collapseKey = "";
        Notification notification = new Notification("Hello bro", "title23");
        Data data = new Data("Hello2", "title2", "key1", "key2");
        Message notificationTask = new Message(to, collapseKey, notification, data);
    
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://fcm.googleapis.com/")//url of FCM message server
                .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
                .build();
    
        ServiceAPI api = new retrofit.create(ServiceAPI.class);
    
        Call call = api .sendMessage("key=YOUR_KEY", notificationTask);
    
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, retrofit2.Response response) {
                Log.d("TAG", response.body().toString());
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
    
                Log.e("TAG", t.getMessage());
            }
        });
    }
    

    our ServiceAPi

    public interface ServiceAPI {
        @POST("/fcm/send")
        Call sendMessage(@Header("Authorization") String token, @Body Message message);
    }
    

提交回复
热议问题