简体   繁体   中英

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?

Set the below flags of the PendingIntet so that you can update if there is a current pending intent with the new PendingIntent .

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 
              PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM