Search code examples
androidandroid-intentandroid-notificationsandroid-pendingintent

Android GCM notification doesn't redirects to intended activity when app is in background


Hi I have created a notification intent as follows

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK );
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(getNotificationIcon())
        .setContentTitle(title)
        .setContentText(text)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);


int notification_id = (int) System.currentTimeMillis();
notificationManager.notify(notification_id, notificationBuilder.build());

Everything works perfectly if the app is closed. But if app is running in background, it just pops last opened activity from background to foreground. I want to go to exact page received in the data. Someone help, I tried many combinations of FLAGS.


Solution

  • AS @rahul pointed out if you change PendingIntent.FLAG_UPDATE_CURRENT to Intent.FLAG_NEW_ACTIVITY_TASK it works as I required, but one problem I founded is that if you have multiple notifications in the notification bar only one action will work. When tapped on the remaining ones it will just clear from there, no actions will work. The following is the correct solution -

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                            .setSmallIcon(getNotificationIcon())
                            .setContentTitle(title)
                            .setContentText(text)
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);