Muhammad Yousuf
Muhammad Yousuf

Reputation: 178

Firebase Cloud Messaging Notification From Android App

I want to send notifications from an android device to multiple android devices and I am using FCM to send notifications but the problem is I am not receiving any thing. I followed some tutorials and as well as some links here on stackoverflow but I don't understand what am I doing wrong. I tried to send notification using retrofit and okhttp but I can't seem to generate the notification. From Firebase Console I can generate the notification but not from android app.

Using Retrofit

Retrofit code

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://fcm.googleapis.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
API api = retrofit.create(API.class);
PushNotificationModel pushNotificationModel = new PushNotificationModel(
        "/topics/Receive",
        new NotificationModel(
                "Mobile",
                "I am ready for you"
        )
);
Call<PushNotificationModel> call = api.sendNotification(pushNotificationModel);
call.enqueue(new Callback<PushNotificationModel>() {
    @Override
    public void onResponse(Call<PushNotificationModel> call, Response<PushNotificationModel> response) {
        Log.e(TAG, "onResponse: Code: " + response.code() /*+ " Response: " + new Gson().toJson(response)*/);
    }

    @Override
    public void onFailure(Call<PushNotificationModel> call, Throwable t) {
        Log.e(TAG, "onFailure: " + t.getMessage());
    }
});

POJO classes

public class PushNotificationModel {
    private String to;
    private NotificationModel notification;

    public PushNotificationModel(String to, NotificationModel notification) {
        this.to = to;
        this.notification = notification;
    }
}

public class NotificationModel {
    private String title, body;

    public NotificationModel(String title, String body) {
        this.title = title;
        this.body = body;
    }
}

Interface

public interface API {

    @Headers({
            "Authorization:key=AAAAO-53MSs:APA91bFR...JNL7GjX1D",
            "Content-Type:application/json"
    })
    @POST("fcm/send")
    Call<PushNotificationModel> sendNotification(@Body PushNotificationModel pushNotificationModel);
}

SOLUTION

I was able to solve the problem by cleaning and rebuilding the project and sometimes on first initial deployment of project I wasn't able to receive notification so closing the app, removing from multitasking bar and re-opening the app solved the problem I was able to receive the notifications properly :). Doesn't matter what you use either volley or retrofit works on both.

Upvotes: 0

Views: 1277

Answers (1)

Abu Saeed
Abu Saeed

Reputation: 1170

Below code will send notification to a group of device that are subscribed to the topic called topicName.

//send notification to other user
public void sendNotificationToUser() {
        JSONObject mainObj = new JSONObject();
        try {
            mainObj.put("to", "/topics/" + topicName); // topicName = your topic name
            JSONObject notificationObj = new JSONObject();
            notificationObj.put("title", "Add your title");
            notificationObj.put("body", "Body section");
            mainObj.put("notification", notificationObj);

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,"https://fcm.googleapis.com/fcm/send",
                    mainObj, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                public Map<String, String> getHeaders() {

                    Map<String, String> header = new HashMap<>();
                    header.put("content-type", "application/json");
                    header.put("authorization", "key="+key);//key = your Database Key
                    return header;
                }
            };
            requestQueue.add(jsonObjectRequest);
            //
        } catch (Exception ignored) {
        }

}
//send notification to other user above

For receiving notification add this FCMService.class to your project

public class FCMService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    //message is recieved. Do whatever you want to do 
}

@Override
public void onNewToken(@NonNull String s) {
            FirebaseMessaging.getInstance().subscribeToTopic("your topic name here").addOnSuccessListener(new OnSuccessListener<Void>() {//subcribe again if some error occured
        @Override
        public void onSuccess(Void aVoid) {
        }
    });
    super.onNewToken(s);
}

}

Don't forget to register in manifest. Add below code inside manifest>application

        <service
        android:name=".FCMService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

Adding firebase-key in app source code isn't a good idea. You can use Firebase Cloud function[have to upgrade project to use Function]

Upvotes: 1

Related Questions