Search code examples
javaandroidandroid-intentnotificationsandroid-pendingintent

Android notification click to open app only works 1st time


I have a foreground service with a notification. I create the notification like this:

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setOngoing(true)
            .setContentTitle("App name")
            .setContentText(Utility.getNotificationContentText())
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentIntent(pendingIntent)
            .setOnlyAlertOnce(true)
            .build();

On the notification I set a pending intent like so:

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

When I click the notification the first time, it works as expected. It opens the app. However, when I click the notification the second time, nothing happens.

For what it's worth, I open the MainActivity.class, but my app has different fragments. I would like to open a specific fragment, but I am not sure if I can pass FragmentName.class into the intent.

Any help for getting the notification click to work every time?


Solution

  • I managed to fix it. The problem was that I was updating the notification with a intent that had the wrong class.