October 21, 2024
Chicago 12, Melborne City, USA
Android

How Can I Receive Notifications with Firebase Cloud Messaging in Android?


I’m trying to receive notifications in my Android app using Firebase Cloud Messaging (FCM). But it doesn’t work the way I want. I have two devices and I send notifications from one to the other. I get notifications on my second device. However, when I click it, it does not enter the activity I want. To investigate the problem, when I held down the notification and looked through the settings, I realized that it did not actually go to the notification channel I created. For example, I create a notification and service named "Comment Channel", but the notification is sent to a channel named "Miscellaneous". I want to listen to the incoming notification.

On the first device I sent notifications to, I added options such as click_action, channel_id, android_channel _id to the JSON data, but this time no notifications were sent. Can you please help?

// First Device (to send notification)

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
    GoogleCredentials googleCredentials;
    try {

        InputStream inputStream = getApplicationContext().getAssets().open(fcmServiceJsonPath);
        googleCredentials = GoogleCredentials
                .fromStream(inputStream)
                .createScoped("https://www.googleapis.com/auth/firebase.messaging");
        googleCredentials.refreshIfExpired();
        AccessToken token = googleCredentials.getAccessToken();
        if (token == null) {
            return;
        }

        String tokenValue = token.getTokenValue();
        try {
            OkHttpClient client = new OkHttpClient();
            // Notification payload
            JSONObject notification = new JSONObject();
            notification.put("title", title);
            notification.put("body", body);
            //notification.put("channel_id", "post_comment");
            // If I enable this, the notification goes away, it gives a 404 error.

            JSONObject data = new JSONObject();
            data.put("title", title);
            data.put("body", body);
            data.put("notification_id", String.valueOf(notification_id));
            data.put("post_id", String.valueOf(getPostId));
            data.put("comment_id", String.valueOf(inserted_comment_id));
            data.put("top_comment_id", String.valueOf(inserted_top_comment_id));
            data.put("comment_count", String.valueOf(comments_size));
            data.put("post_owner_user_id", String.valueOf(getPostOwnerUserId));
            data.put("post_owner_username", String.valueOf(getPostOwnerUsername));
            data.put("inserted_db", is_reply_comment ? "sub_comment" : "comment");
            data.put("timestamp", String.valueOf(System.currentTimeMillis()));

            // Request payload
            JSONObject message = new JSONObject();
            message.put("token", fcmToken);
            message.put("notification", notification);
            message.put("data", data);


          //  message.put("android", new JSONObject().put("priority", "high"));
           //JSONObject androidPayload = new JSONObject();
           //JSONObject notificationPayload = new JSONObject();
           //notificationPayload.put("click_action", "post_comment");
           //notificationPayload.put("channel_id", "Yorum Bildirimi");
           //androidPayload.put("notification", notificationPayload);
           //message.put("android", androidPayload);
            //   message.put("click_action", ".activity.PostCommentActivity");


            JSONObject requestBody = new JSONObject();
            requestBody.put("message", message);
            RequestBody bodyRequest = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    requestBody.toString()
            );
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(fcmUrl)
                    .post(bodyRequest)
                    .addHeader("Authorization", "Bearer " + tokenValue)
                    .addHeader("Content-Type", "application/json")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException ioException) {
                    Log.d("TAG_EXCEPTION", "Bildirim gönderilemedi: " + ioException.getMessage());
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    if (response.isSuccessful()) {
                        Log.d("TAG_EXCEPTION", "Notification sent successfully!");
                    } else {
                        Log.d("TAG_EXCEPTION", "Notification. Mistake: " + response);
                    }
                }
            });
        } catch (JSONException e) {
            Log.d("TAG_EXCEPTION", "JSON Ex: " + e.getMessage());
        }
    } catch (IOException e) {
        Log.d("TAG_EXCEPTION", "Service JSON Ex: " + e.getMessage());
    }
});

// Second Device (to receive notifications)

// Manifest

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


        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_notification_icon" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorPrimaryContainer" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/fcm_comment_channel" />

// FCM Service


public class FCMService extends FirebaseMessagingService {
    private static final String TAG = "TAG_COMMENT_FCM";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "RemoteMessage Running"+"getFrom: "+remoteMessage.getFrom());

        if (remoteMessage.getNotification() != null) {
            sendNotification(remoteMessage);
        }
    }


    @Override
    public void onNewToken(@NonNull String token) {
        Log.d(TAG, "Refreshed token: " + token);
    }


    public void sendNotification(RemoteMessage remoteMessage) {
        String messageTitle =remoteMessage.getData().get("title");
        String messageBody = remoteMessage.getData().get("body");

        String postIdStr = remoteMessage.getData().get("post_id");
        String commentIdStr = remoteMessage.getData().get("comment_id");
        String timestamp = remoteMessage.getData().get("timestamp");


        int postId = postIdStr != null ? Integer.parseInt(postIdStr) : 0;
        int commentId = commentIdStr != null ? Integer.parseInt(commentIdStr) : -1;



        Intent intent = new Intent(this, PostCommentActivity.class);
        intent.putExtra("notification_type", "fcm");
        intent.putExtra("post_id", postId);
        intent.putExtra("comment_id", commentId);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        Toast.makeText(getApplicationContext(), "notif", Toast.LENGTH_SHORT).show();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        SharedPreferencesReceiver.setCommunityNotification(getApplicationContext(), true);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, commentId, intent, PendingIntent.FLAG_IMMUTABLE);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(getString(R.string.fcm_comment_channel),
                    getString(R.string.fcm_comment_channel),
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(getString(R.string.fcm_comment_channel));
            channel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, getString(R.string.fcm_comment_channel))
                        .setSmallIcon(R.drawable.ic_notification_icon)
                        .setChannelId(getString(R.string.fcm_comment_channel))
                        .setContentTitle(messageTitle)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setColor(ContextCompat.getColor(this, R.color.colorPrimaryContainer))
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setWhen(System.currentTimeMillis())
                        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                        .setContentInfo("Info")
                        .setContentIntent(pendingIntent)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(messageBody));


        notificationManager.notify(commentId, notificationBuilder.build());
    }
}
JSONObject androidPayload = new JSONObject();
JSONObject notificationPayload = new JSONObject();
//notificationPayload.put("click_action", "post_comment");
notificationPayload.put("channel_id", "post_comment");
androidPayload.put("notification", notificationPayload);
message.put("android", androidPayload);



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video