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) {

                    }
                });




            }
        });
Kuls
  • 2,047
  • 21
  • 39
  • 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](https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html): and then study this [sample using Cloud Functions](https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens) – Frank van Puffelen Oct 02 '17 at 14:22

3 Answers3

11

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.

Arrabidas92
  • 1,113
  • 1
  • 9
  • 20
  • and how can i get it? –  Oct 02 '17 at 13:47
  • and with this FCM how can i send notification inside my app with code and not with the firebase console? –  Oct 02 '17 at 13:48
  • 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 logic – Neeraj Krishna Oct 02 '17 at 15:22
7

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

kunwar97
  • 775
  • 6
  • 14
  • I don't understand where should i write the ID token of the user who will recive the message. –  Oct 03 '17 at 11:01
  • In FCM notifier class in "to" replace"/topics/topic" with "user token" – kunwar97 Oct 03 '17 at 11:05
  • ok perfect. Just one more thing: Should i write something in the manifest? –  Oct 03 '17 at 11:08
  • you have to implement FirebaseMesaagingService and FirebaseIdService in client app so you have to add these services in the manifest of the client app – kunwar97 Oct 03 '17 at 11:13
  • this is only related to add notification payload & what about data payload & how to add it.@kunwar97 – Pratiksha Shaha Feb 14 '20 at 08:43
  • Hi @PratikshaShaha I have updated my answer. However this method is not recommended because it creates security risk – kunwar97 Feb 17 '20 at 05:39
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.

rashidotm
  • 392
  • 2
  • 12