When a user first runs your app Firebase generates a Token for that user and his device. Each time user deletes the app and reinstalls it will re-generate this Token. This also includes new devices of course since that is just like the first installation ever.
What I did with this is that I used the Firebase Realtime database in which I stored this Token for each user I have. Then when I need to send the notification to that user I just get that token and send it within my application. This is one old example on how I did that:
OkHttpClient client = new OkHttpClient();
Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);
JSONObject json = new JSONObject();
JSONObject notifJson = new JSONObject();
JSONObject dataJson = new JSONObject();
notifJson.put("text", body);
notifJson.put("title", title);
dataJson.put("customId", "02");
json.put("notification", notifJson);
json.put("data", dataJson);
json.put("to", firebase_token);
RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.toString());
.header("Authorization", "key="+server_key)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) { //do something if notification is sent successfully }
You can do this using your code to send notifications to a specific user. This is, of course, if you want to send a notification from your code. If you want to use a server or something there is documentation you can follow here: https://firebase.google.com/docs/cloud-messaging/android/send-multiple
What I used in this example:
notifJson
- notification part
dataJson
- data part of notification
body
- the body of my notification
title
- the title of my notification
firebase_token
- Token of user I am sending a notification to, this is retrieved earlier with Firebase real-time database
server_key
- Server key from Firebase configuration
In the IF statement
below if the response was successful I add some data to my real-time database but you can do anything else you want.