Ad

Wrong Notification When Messages Are Unread On Android

I'm using Firebase cloudmessaging for my Android application notifications, So my issue is when I send a notification if the user dismisses the notification the next notification that I send if clicked is opening the the first notification that have been dismissed so even if I send the third notification and the user dismissed both first and second notifications, if clicked the third one it's going to open the first notification. I'm using Firebase cloud messaging with data and sending the (title, excerpt, image, link). in the notification bar everything is cool and correct but when clicked the link is changed and the webview is going to open the first notification.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"),
                    Integer.parseInt(remoteMessage.getData().get("topic")), remoteMessage.getData().get("link"), remoteMessage.getData().get("imageUrl"), Integer.parseInt(remoteMessage.getData().get("id")));

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(),
                    0, " ", " ", 0);
        }
    }
    // [END receive_message]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    @TargetApi(Build.VERSION_CODES.O)
    private void sendNotification(String messageTitle, String messageBody, int topic, String link, String imageUrl, int id) {

        PendingIntent pendingIntent;
        if (topic == 1){
            Intent intent = new Intent(this, WebActivity.class);
            // Create the TaskStackBuilder and add the intent, which inflates the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addNextIntentWithParentStack(intent);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("link", link);
            intent.putExtra("title", messageTitle);
            // Get the PendingIntent containing the entire back stack
            pendingIntent =
                    stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
        }else{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("link", link);
            intent.putExtra("topic", topic);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        String channelId = getString(R.string.default_notification_channel_id);

        InputStream in;
        Bitmap myBitmap = null;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            in = connection.getInputStream();
            myBitmap = BitmapFactory.decodeStream(in);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setPriority(NotificationManager.IMPORTANCE_DEFAULT)
                        .setChannelId(channelId)
                        .setSmallIcon(R.drawable.ic_stat_name)
                        .setLargeIcon(myBitmap)
                        .setContentTitle(messageTitle)
                        .setContentText(messageBody)
                        .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent))
                        .setAutoCancel(true)
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(messageTitle))
                        .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(myBitmap))
                        .setGroupSummary(true)
                        .setGroup(String.valueOf(topic))
                        .setContentIntent(pendingIntent);

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

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = "The Channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(channelId, name, importance);
            channel.setDescription(description);
            channel.setShowBadge(true);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
            notificationManager.createNotificationChannelGroup(new NotificationChannelGroup(String.valueOf(topic), "Articles"));
        }

        notificationManager.notify(id /* ID of notification */, notificationBuilder.build());
    }
}

The expected result is if the user dismissed the first notification, And for the second notification if clicked, the webview opens the second information send from the notification.

Ad

Answer

So after alot of research I found out that I have to update my intent with PendingIntent.FLAG_UPDATE_CURRENT and changed the request code for the intent every time a new intent is created, that's the new code for any one had this issue in the future:

PendingIntent pendingIntent;
        if (topic == 1){
            Intent intent = new Intent(this, WebActivity.class);
            // Create the TaskStackBuilder and add the intent, which inflates the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addNextIntentWithParentStack(intent);
            intent.putExtra("link", link);
            intent.putExtra("title", messageTitle);
            intent.setAction("actionstring" + System.currentTimeMillis());
            // Get the PendingIntent containing the entire back stack
            pendingIntent =
                    stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
        }else{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("link", link);
            intent.putExtra("topic", topic);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }
Ad
source: stackoverflow.com
Ad