2

I want to build client and admin android apps such that the admin app sends a notification to FCM (API) and the users of the client app get this notification.

So, I used the Firebase Admin SDK to push the notification from the admin app to FCM by using the FCM documentation but there's something strange in the next code (from the documentation)

// This registration token comes from the client FCM SDKs.
String registrationToken = "YOUR_REGISTRATION_TOKEN";

// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(new Notification(
    "$GOOG up 1.43% on the day",
    "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."))
.setCondition(condition)
.build();


// Send a message to the device corresponding to the provided
    // registration token.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
 System.out.println("Successfully sent message: " + response);

As the send(RemoteMessage) accepts RemoteMessage not a Message object so how could I modified the previous code to a send the notification using RemoteMessage object

  • 1
    You mention SVM in your title. That's an acronym I'm not familiar with. What does it mean? – Frank van Puffelen Mar 14 '19 at 13:14
  • 1
    You tagged with `android`, but the Firebase Admin SDK is not meant to be used in client-side application code (as it grants the process it runs in unlimited access to your Firebase project). Where are you trying to run this code? – Frank van Puffelen Mar 14 '19 at 13:15

2 Answers2

1

You seem to be trying to mix the Firebase Admin SDK, with the Firebase Cloud Messaging SDK for Android. This is not possible.

Any process that uses the Admin SDK is granted full, unlimited access to your Firebase project. So if you were to put it in a client-side app, everyone with that app could send FCM messages to any of your users, but also: list all those users, delete your entire database, overwrite your Cloud Functions, etc. For this reason the Firebase Admin SDK should/can only be used in a trusted environment, such as your development machine, a server you control, or Cloud Functions.

To send messages to a device through Firebase Cloud Messaging, you will always need to have a trusted environment, often referred to as an app server in the FCM documentation.

When you run the Admin SDK on that trusted environment, you can call the FirebaseMessaging.getInstance().send() method, which takes the Message returned by build() as its parameter.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Use My code work like charms : sends a notification to a particular user and manages click of notification.

implementation 'com.google.firebase:firebase-messaging:20.1.3'
implementation 'com.google.firebase:firebase-analytics:17.2.3'

Manifest

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="default_channel_id" />

    <service
        android:name=".FCMService" >
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

Activity

  1.  project setting > cloud messaging > server key
      AUTH_KEY = server key

  2.  token id of a particular device is 
      String device_token = FirebaseInstanceId.getInstance().getToken();

When sending notification

  new Thread(new Runnable() {
        @Override
        public void run() {
            pushNotification(senderName + " : " + message);

        }
    }).start();

  private void pushNotification(String message) {
    JSONObject jPayload = new JSONObject();
    JSONObject jNotification = new JSONObject();
    JSONObject jData = new JSONObject();
        try {
            // notification can not put when app is in background
            jNotification.put("title", getString(R.string.app_name));
            jNotification.put("body", message);
            jNotification.put("sound", "default");
            jNotification.put("badge", "1");
            jNotification.put("icon", "ic_notification");

//            jData.put("picture", "https://miro.medium.com/max/1400/1*QyVPcBbT_jENl8TGblk52w.png");

            //to token of any deivce
            jPayload.put("to", device_token);

            // data can put when app is in background
            jData.put("goto_which", "chatactivity");
            jData.put("user_id", mCurrentUserId);

            jPayload.put("priority", "high");
            jPayload.put("notification", jNotification);
            jPayload.put("data", jData);

            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "key=" + AUTH_KEY);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            // Send FCM message content.
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jPayload.toString().getBytes());

            // Read FCM response.
            InputStream inputStream = conn.getInputStream();
            final String resp = convertStreamToString(inputStream);

        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is) {
        Scanner s = new Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next().replace(",", ",\n") : "";
    }

Add service Class

    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.util.Log;

    import androidx.annotation.NonNull;
    import androidx.core.app.NotificationCompat;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.iid.FirebaseInstanceId;
    import com.google.firebase.iid.InstanceIdResult;
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;

    public class FCMService extends FirebaseMessagingService {
        String goto_which, user_id;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
            Log.d("ff", "messddda recice: " + remoteMessage.getNotification().getTicker());
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();

            if (remoteMessage.getData().size() > 0) {
                goto_which = remoteMessage.getData().get("goto_which").toString();
                user_id = remoteMessage.getData().get("user_id").toString();
                Log.d("ff", "messddda send: " + goto_which);
            }
            sendnotification(title, body, goto_which, user_id);
        }

        private void sendnotification(String title, String body, String goto_which, String user_id) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("goto_which", goto_which);
            intent.putExtra("user_id", user_id);

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            Uri defaultsounduri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder nbuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setSound(defaultsounduri)
                    .setContentIntent(pendingIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, nbuilder.build());


            FirebaseInstanceId.getInstance().getInstanceId()
                    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                        @Override
                        public void onComplete(@NonNull Task<InstanceIdResult> task) {
                            if (!task.isSuccessful()) {
                                Log.w("f", "getInstanceId failed", task.getException());
                                return;
                            }

                            // Get new Instance ID token
                            String token = task.getResult().getToken();

                        }
                    });

        }
    }

Manage click of notification :

It calls launcher activity so in the launcher activity you can manage call of a particular activity

Your launcher activity looks like

 if (getIntent().getExtras() != null) {
        String goto_which = getIntent().getStringExtra("goto_which");
        String chatUser = getIntent().getStringExtra("user_id");

        if (goto_which.equals("chatactivity")) {
            Intent chatIntent = new Intent(getBaseContext(), ChatActivity.class);
            chatIntent.putExtra("user_id", chatUser);
            startActivity(chatIntent);
        } else if (goto_which.equals("grpchatactivity")) {
            Intent chatIntent = new Intent(getBaseContext(), GroupChatActivity.class);
            chatIntent.putExtra("group_id", chatUser);
            startActivity(chatIntent);
        }
    }
jay patoliya
  • 611
  • 7
  • 8