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

后端 未结 13 1908
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: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 call2 = firebaseAPI.sendMessage(new Message(token, notifydata));
    
        call2.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, retrofit2.Response response) {
                Log.e("#@ SUCCES #E$#", response.body().toString());
            }
    
            @Override
            public void onFailure(Call 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;
    }
    }
    

提交回复
热议问题