Firebase Cloud Messaging with Java cannot send notifications to another device

I am trying to use HTTP POST to send notifications to a device.

When "A" is sent to "A", token A is successfully received. Then "A" sends B-token to "B" never . But when notification is sent to B by Google FCM server, it is successful.

This is a Java sender.

package com.example.wawa.fcmtest;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by user on 2017/4/12.
 */

public class FirebaseSender {

    public static void pushFCMNotification(String userDeviceIdKey, String title, String body) throws Exception{

        String authKey = "AIza.....";   // You FCM AUTH key
        String FMCurl = "https://fcm.googleapis.com/fcm/send";

        URL url = new URL(FMCurl);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization","key="+authKey);
        conn.setRequestProperty("Content-Type","application/json");

        JSONObject json = new JSONObject();
        json.put("to",userDeviceIdKey.trim());
        JSONObject info = new JSONObject();
        info.put("title", "123");   // Notification title
        info.put("body", "456"); // Notification body
        json.put("notification", info);
        json.put("priority","high");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(json.toString());
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + json);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    }
}

      

This is the FirebaseMessagingService.

package com.example.wawa.fcmtest;

import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
 * Created by user on 2017/4/12.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("FCM", "onMessageReceived:"+remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d("FCM","Message data payload: " + remoteMessage.getData());
        }


        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();
            Log.d("FCM", "Message Notification Title: " + title);
            Log.d("FCM", "Message Notification Body: " + body);
            Tool tool = new Tool(this);
            tool.setNotification(this,title,body);
        }
    }
}

      

+3


source to share


1 answer


Send notification from device A → B. Implement this class:



      public class FCMNotification {

// Method to send Notifications from server to client end.
public final static String AUTH_KEY_FCM = "YOUR_SERVERKEY";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

public static void pushFCMNotification(final String DeviceIdKey, final String title, final String body) throws Exception {

    AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            BufferedReader in = null;


            String authKey = AUTH_KEY_FCM;   // You FCM AUTH key
            String FMCurl = API_URL_FCM;

            URL url = null;
            try {
                url = new URL(FMCurl);
            } catch (MalformedURLException e) {
                Log.i("yoyoyo", "error: 1");
                e.printStackTrace();
            }
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection) url.openConnection();
            } catch (IOException e) {
                Log.i("yoyoyo", "error: 2");
                e.printStackTrace();
            }

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            try {
                conn.setRequestMethod("POST");
            } catch (ProtocolException e) {
                Log.i("yoyoyo", "error: 3");
                e.printStackTrace();
            }
            conn.setRequestProperty("Authorization","key="+authKey);
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            try {
                json.put("to",DeviceIdKey.trim());
            } catch (JSONException e) {
                Log.i("yoyoyo", "error: 4");
                e.printStackTrace();
            }
            JSONObject info = new JSONObject();
            try {
                info.put("title", title);   // Notification title
            } catch (JSONException e) {
                Log.i("yoyoyo", "error: 5");
                e.printStackTrace();
            }
            try {
                info.put("body", body); // Notification body
            } catch (JSONException e) {
                Log.i("yoyoyo", "error: 6");
                e.printStackTrace();
            }
            try {
                json.put("notification", info);
            } catch (JSONException e) {
                Log.i("yoyoyo", "error: 7");
                e.printStackTrace();
            }

            OutputStreamWriter wr = null;
            try {
                wr = new OutputStreamWriter(conn.getOutputStream());
            } catch (IOException e) {
                Log.i("yoyoyo", "error: 8");
                e.printStackTrace();
            }
            try {
                wr.write(json.toString());
            } catch (IOException e) {
                Log.i("yoyoyo", "error: 9");
                e.printStackTrace();
            }
            try {
                wr.flush();
            } catch (IOException e) {
                Log.i("yoyoyo", "error: 10");
                e.printStackTrace();
            }
            try {
                conn.getInputStream();
            } catch (IOException e) {
                Log.i("yoyoyo", "error: 11");
                e.printStackTrace();
            }

            return null;
        }
    };
    asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);



 }


}

      

0


source







All Articles