How can i send push notification to specific users just knowing the userID inside Button OnClickListener? Firebase
Asked Answered
B

3

7

I just need to send a push notification to a specific users inside my Button OnClickListener. Is it possible with userId and all information of this specific user?

this is my Button OnClickListener() code

richiedi_invito.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                databaseReference = FirebaseDatabase.getInstance().getReference();

                databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        lista_richieste = (ArrayList) dataSnapshot.child("classi").child(nome).child("lista_richieste").getValue();
                        verifica_richieste = (String) dataSnapshot.child("classi").child(nome).child("richieste").getValue();




                        if (!lista_richieste.contains(userID)){
                            ArrayList lista_invito = new ArrayList();
                            lista_invito.add(userID);
                            if (verifica_richieste.equals("null")){
                                databaseReference.child("classi").child(nome).child("richieste").setValue("not_null");
                                databaseReference.child("classi").child(nome).child("lista_richieste").setValue(lista_invito);


                            }
                            else{
                                lista_richieste.add(userID);
                                databaseReference.child("classi").child(nome).child("lista_richieste").setValue(lista_richieste);

                            }


                            //invitation code here



                            Fragment frag_crea_unisciti = new CreaUniscitiFrag();
                            FragmentManager fragmentManager= getFragmentManager();
                            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                            fragmentTransaction.replace(R.id.fragment_container, frag_crea_unisciti);
                            fragmentTransaction.addToBackStack(null);
                            fragmentTransaction.commit();

                            Toast.makeText(getActivity(), "Richiesta di entrare inviata correttamente", Toast.LENGTH_SHORT).show();

                        }else{
                            Snackbar.make(layout,"Hai già richiesto di entrare in questa classe",Snackbar.LENGTH_SHORT).show();


                    }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });




            }
        });
Barnes answered 2/10, 2017 at 13:35 Comment(1)
You'll need to use Firebase Cloud Messaging to send push notifications. In addition you'll need to run code on a trusted environment. I recommend reading this tutorial here: and then study this sample using Cloud FunctionsPinhead
G
8

First, the user has to generate String token = FirebaseInstanceId.getInstance().getToken(); and then store it in Firebase database with userId as key or you can subscribe the user to any topic by FirebaseMessaging.getInstance().subscribeToTopic("topic");

To send the notification you have to hit this API: https://fcm.googleapis.com/fcm/send

With headers "Authorization" your FCM key and Content-Type as "application/json" the request body should be:

{ 
  "to": "/topics or FCM id",
  "priority": "high",
  "notification": {
    "title": "Your Title",
    "text": "Your Text"
  },
  "data": {
    "customId": "02",
    "badge": 1,
    "sound": "",
    "alert": "Alert"
  }
}

Or you can use okHttp which is not recommended method because your FCM key will be exposed and can be misused.

public class FcmNotifier {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static void sendNotification(final String body, final String title) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    JSONObject json = new JSONObject();
                    JSONObject notifJson = new JSONObject();
                    JSONObject dataJson = new JSONObject();
                    notifJson.put("text", body);
                    notifJson.put("title", title);
                    notifJson.put("priority", "high");
                    dataJson.put("customId", "02");
                    dataJson.put("badge", 1);
                    dataJson.put("alert", "Alert");
                    json.put("notification", notifJson);
                    json.put("data", dataJson);
                    json.put("to", "/topics/topic");
                    RequestBody body = RequestBody.create(JSON, json.toString());
                    Request request = new Request.Builder()
                            .header("Authorization", "key=your FCM key")
                            .url("https://fcm.googleapis.com/fcm/send")
                            .post(body)
                            .build();
                    Response response = client.newCall(request).execute();
                    String finalResponse = response.body().string();
                    Log.i("kunwar", finalResponse);
                } catch (Exception e) {

                    Log.i("kunwar",e.getMessage());
                }
                return null;
            }
        }.execute();
    }
}

NOTE: THIS SOLUTION IS NOT RECOMMENDED BECAUSE IT EXPOSES FIREBASE API KEY TO THE PUBLIC

Gretchen answered 2/10, 2017 at 14:22 Comment(6)
I don't understand where should i write the ID token of the user who will recive the message.Barnes
In FCM notifier class in "to" replace"/topics/topic" with "user token"Gretchen
ok perfect. Just one more thing: Should i write something in the manifest?Barnes
you have to implement FirebaseMesaagingService and FirebaseIdService in client app so you have to add these services in the manifest of the client appGretchen
this is only related to add notification payload & what about data payload & how to add it.@GretchenCytogenetics
Hi @PratikshaShaha I have updated my answer. However this method is not recommended because it creates security riskGretchen
B
13

To send a push notification to a specific single user with Firebase, you only need is FCM registration token which is the unique identifier of the user device to receive the notification.

Here is Firebase FCM documentation to get this token : FCM Token registration

Basically :

  • You get a FCM token for the user
  • Then you store this FCM token on your server or database by associating this FCM token with the user ID for example.
  • When you need to send a notification, you can retrieve this FCM token stored on your server or database with the user id and use Firebase Cloud Functions. Here is a specific case study to send a notification for a specific user : Cloud Functions

Only the user id itself isn't enough to send a notification for a specific user.

Boccie answered 2/10, 2017 at 13:45 Comment(3)
and how can i get it?Barnes
and with this FCM how can i send notification inside my app with code and not with the firebase console?Barnes
There are push notification providers like Bluemix Push Notifications and several others who do the mapping between userId and the device token. Best is to use it rather than writing your own logicPrecedent
G
8

First, the user has to generate String token = FirebaseInstanceId.getInstance().getToken(); and then store it in Firebase database with userId as key or you can subscribe the user to any topic by FirebaseMessaging.getInstance().subscribeToTopic("topic");

To send the notification you have to hit this API: https://fcm.googleapis.com/fcm/send

With headers "Authorization" your FCM key and Content-Type as "application/json" the request body should be:

{ 
  "to": "/topics or FCM id",
  "priority": "high",
  "notification": {
    "title": "Your Title",
    "text": "Your Text"
  },
  "data": {
    "customId": "02",
    "badge": 1,
    "sound": "",
    "alert": "Alert"
  }
}

Or you can use okHttp which is not recommended method because your FCM key will be exposed and can be misused.

public class FcmNotifier {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static void sendNotification(final String body, final String title) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    JSONObject json = new JSONObject();
                    JSONObject notifJson = new JSONObject();
                    JSONObject dataJson = new JSONObject();
                    notifJson.put("text", body);
                    notifJson.put("title", title);
                    notifJson.put("priority", "high");
                    dataJson.put("customId", "02");
                    dataJson.put("badge", 1);
                    dataJson.put("alert", "Alert");
                    json.put("notification", notifJson);
                    json.put("data", dataJson);
                    json.put("to", "/topics/topic");
                    RequestBody body = RequestBody.create(JSON, json.toString());
                    Request request = new Request.Builder()
                            .header("Authorization", "key=your FCM key")
                            .url("https://fcm.googleapis.com/fcm/send")
                            .post(body)
                            .build();
                    Response response = client.newCall(request).execute();
                    String finalResponse = response.body().string();
                    Log.i("kunwar", finalResponse);
                } catch (Exception e) {

                    Log.i("kunwar",e.getMessage());
                }
                return null;
            }
        }.execute();
    }
}

NOTE: THIS SOLUTION IS NOT RECOMMENDED BECAUSE IT EXPOSES FIREBASE API KEY TO THE PUBLIC

Gretchen answered 2/10, 2017 at 14:22 Comment(6)
I don't understand where should i write the ID token of the user who will recive the message.Barnes
In FCM notifier class in "to" replace"/topics/topic" with "user token"Gretchen
ok perfect. Just one more thing: Should i write something in the manifest?Barnes
you have to implement FirebaseMesaagingService and FirebaseIdService in client app so you have to add these services in the manifest of the client appGretchen
this is only related to add notification payload & what about data payload & how to add it.@GretchenCytogenetics
Hi @PratikshaShaha I have updated my answer. However this method is not recommended because it creates security riskGretchen
D
0

Another way is make a user subscribe to a topic named after his/her uid. then send the notification to a topic with the uid name.

I haven't tested this myself yet but I have read it here sometime ago.

Decca answered 4/10, 2022 at 4:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.