Android click on notification does not open the at

2019-06-21 05:43发布

问题:

I want to open an Activity when I click on the notification from the Status bar. I have seen this answered on StackOverflow but none of these answers work for me. This issue is only seen on Lollipop devices and best way to reproduce is: 1. launch the app. 2. Back ground the app. 3. Receive a push notification. 4. Click on the notification and try with 3-4 push notifications.

Below is my code: I have also tried the following:

  1. adding Intent.ACTION_MAIN
  2. Intent.CATEGORY_LAUNCHER to the intent
  3. PendingIntent.FLAG_UPDATE_CURRENT.
  4. android:exported="true" in my AndroidManifest.xml

but nothing works. I am seeing this issue only on Lollipop devices. Please note I see this issue intermittently. Is this something related to the intent getting cached and not getting delivered. Please help.

PendingIntent pendingIntent = getPendingIntent(context, payload);
Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_stat)
            .setContentTitle(res.getString(R.string.app_name))
            .setContentText(payload.getMessage())
            .setTicker(payload.getMessage())
            .setContentIntent(pendingIntent)
            .setSound(soundUri);

private PendingIntent getPendingIntent(Context context, NotificationPayload payload) {
    int requestID = (int) System.currentTimeMillis();
    Intent intent = new Intent(context, DeepLinkActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setPackage(BuildConfig.APPLICATION_ID);
    intent.putExtra(NotificationHelper.KEY_NOTIFICATION_PAYLOAD, payload);
    return PendingIntent.getActivity(context, requestID, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
}

回答1:

try adding Intent.FLAG_ACTIVITY_CLEAR_TASK flag in the intent

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

this seems to solve my problem



回答2:

Have you set the pending intent in the notification setContentIntent method?

Try this, it works for me on all api versions

        Intent intent = new Intent(this, TestActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.logo)
                .setContentTitle(getResources().getString(R.string.notification_title))
                .setContentIntent(pendingIntent);

  NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());