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

Issue

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

                    }
                });




            }
        });

Solution

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

Answered By – kunwar97

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *