Luca Orlandi
Luca Orlandi

Reputation: 77

How can I send notification to specific User using the user's token in Firebase?

I am developing an android app (java), I am using Firebase, for each registered user I have a token of the device, how can I send a notification to a specific user using his token ?

Upvotes: 0

Views: 1445

Answers (2)

Mubashar Hussain
Mubashar Hussain

Reputation: 305

For sending a notification to users the only thing required is that user's token. You can send notification using FCM. Here, I'm sharing my FCM class which can be used for this purpose. It is using Okhttp3 requests, so make sure you add its dependency.

    implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'

After adding this dependency, all you have to do is to use this FCM class.

FCMMessages.java

public class FCMMessages {

    private Context context;

    public void sendMessageSingle(Context context, final String recipient, final String title, final String body, final Map<String, String> dataMap)
    {
        this.context = context;

        Map<String, Object> notificationMap = new HashMap<>();
        notificationMap.put("body", body);
        notificationMap.put("title", title);

        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("notification", notificationMap);
        rootMap.put("to", recipient);
        if (dataMap != null)
            rootMap.put("data", dataMap);

        new SendFCM().setFcm(rootMap).execute();
    }


    public void sendMessageMulti(Context context, final JSONArray recipients, final String title, final String body, final Map<String, String> dataMap) {
        this.context = context;

        Map<String, Object> notificationMap = new HashMap<>();
        notificationMap.put("body", body);
        notificationMap.put("title", title);
        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("notification", notificationMap);
        rootMap.put("registration_ids", recipients);
        if (dataMap != null)
            rootMap.put("data", dataMap);

        new SendFCM().setFcm(rootMap).execute();
    }

    @SuppressLint("StaticFieldLeak")
    class SendFCM extends AsyncTask<String, String, String> {

        private String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
        private Map<String, Object> fcm;

        SendFCM setFcm(Map<String, Object> fcm) {
            this.fcm = fcm;
            return this;
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, new JSONObject(fcm).toString());
                Request request = new Request.Builder()
                        .url(FCM_MESSAGE_URL)
                        .post(body)
                        .addHeader("Authorization","key=" + StaticConfig.myMessagingAuth)
                        .build();
                Response response = new OkHttpClient().newCall(request).execute();
                return response.body().string();

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject resultJson = new JSONObject(result);
                int success, failure;
                success = resultJson.getInt("success");
                failure = resultJson.getInt("failure");
            //Toast.makeText(context, "Sent: " + success + "/" + (success + failure), Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
//                Toast.makeText(context, "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Make sure you get the messagingAuth from your firebase project settings. To get the messagingAuth token, follow these steps:

Open Firebase Project > Project Settings > Cloud Messaging > Server key

Copy the value of server key and paste it as messagingAuth in your android project.

To send a notification to single user token use sendMessageSingle method. It would be like

String user_token = "wiubd92uhe91dik-q";
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageSingle(MainActivity.this, user_token, notification_title, notification_des, null);

To send a notification to multiple user tokens use sendMessageMulti method. It would be like

ArrayList<String> user_tokens = new ArrayList<>();
user_tokens.add(token_1);
user_tokens.add(token_2);
user_tokens.add(token_3);
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageMulti(MainActivity.this, new JSONArray(user_tokens), notification_title, notification_des, null);

Upvotes: 2

Kamal Nayan
Kamal Nayan

Reputation: 1718

Use this YouTube link here EDMT Dev has implemented the following in his Eat it new series. And kindly mark this as the correct answer if this helps you.

Add the below dependency

 `implementation 'io.reactivex.rxjava2:rxandroid:2.1.1`'

Now Create these classes :

Token Model This Model is used to retrieve token data( Token , Phone ). I have also a variable for the phone because I made this class according to my datastructure . Kindly modify the code according to your need

public class TokenModel {

private String phone,token;

public TokenModel() {
}

public TokenModel(String phone, String token) {
    this.phone = phone;
    this.token = token;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getToken() {
    return token;
}

public void setToken(String token) {
    this.token = token;
}}

FCM Send Data Model

  public class FCMSendData {
private String to;
private Map<String,String> data;

public FCMSendData(String to, Map<String, String> data) {
    this.to = to;
    this.data = data;
}

public String getTo() {
    return to;
}

public void setTo(String to) {
    this.to = to;
}

public Map<String, String> getData() {
    return data;
}

public void setData(Map<String, String> data) {
    this.data = data;
}}

Create FCM Result Model

 class FCMResult {
    private String message_id;
    
    public FCMResult() {
    }
    
    public String getMessage_id() {
        return message_id;
    }
    
    public void setMessage_id(String message_id) {
        this.message_id = message_id;
    }}

Create RetrofitFCMClient

public class RetrofitFCMClient {
private static Retrofit instance;
public static Retrofit getInstance()
{
    if(instance==null)
    {
        instance  = new Retrofit.Builder().baseUrl("https://fcm.googleapis.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return instance;
    }
    return instance;
}}

Now we need to implement an interface //Authorization key is server key of Cloud Messaging

public interface IFCMService {

@Headers({
        "Content-Type:application/json",

        "Authorization:key=**YOUR_AUTHORIZATION KEY HERE**"

})
@POST("fcm/send")
Observable<FCMResponse> sendNotification(@Body FCMSendData body);}

Now We are ready to use the firebase messaging just need to put data and use our retrofit to push it

TokenModel tokenModel = dataSnapshot.getValue(TokenModel.class);
                                        //("FCM",tokenModel.getToken());
                                        Map<String, String> notiData = new  
HashMap<>();
             notiData.put(Common.NOTI_TITLE, "YOUR NOTIFICATION TITLE");
             notiData.put(Common.NOTI_CONTENT,"YOUR_NOTFICATION CONTENT );

    FCMSendData sendData = new FCMSendData(tokenModel.getToken(), 
notiData);
                                        
  compositeDisposable
 .add(ifcmService.sendNotification(sendData)
  .subscribeOn(Schedulers.io()).
                                           


  observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Consumer<FCMResponse>() {
                                        @Override
                                        public void accept(FCMResponse 
fcmResponse)              

     throws Exception {
                                            if (fcmResponse.getSuccess()  
== 1) {

                                                 
Toast.makeText(getContext(),     

    "Success", Toast.LENGTH_LONG).show();
                                            } else {
                                                 
Toast.makeText(getContext(), "Failed  
       to Notify", Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable 
throwable) throws Exception {
                                            Toast.makeText(getContext(),   
throwable.getMessage(), Toast.LENGTH_LONG).show();

                                        }
                                    }));




    

Use this YouTube link here EDMT Dev has implemented the following in his Eat it new series

Upvotes: 2

Related Questions