Home » Android » PendingIntent not opening Activity in Android 4.3

PendingIntent not opening Activity in Android 4.3

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

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);

Answer:

That’s worked for me:

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