PendingIntent not opening Activity in Android 4.3

2019-01-31 18:32发布

问题:

In my Service, I open up a notification on normal run, using this code:

private final static NOTIFICATION_ID = 412434;
private void startNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            this);
    builder.setSmallIcon(R.drawable.notification);
    builder.setContentTitle("Running");

    final Intent intent = new Intent(this, MainActivity.class);
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    builder.setOngoing(true);
    builder.setAutoCancel(false);

    notification = builder.build();

    startForeground(NOTIFICATION_ID, notification);
}

The PendingIntent is to open the MainActivity when the Notification is tapped. This works perfectly fine on all my test devices, using Android 2.3.3, 2.3.5 and Android 4.1.

It does not work, however on my Nexus 7 (Android 4.3), this doesn't work at all. Nothing happens when I tap on the Notification.

Did something change in the way these are put together that I missed?

回答1:

There seems to be an issue on some 4.3 devices. It can be resolved by providing a non 0 value to the requestCode parameter.

Example:

PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);


回答2:

That's worked for me:

Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
contentIntent = PendingIntent.getActivity(this, randomInt, intent, PendingIntent.FLAG_UPDATE_CURRENT);