PendingIntent not opening Activity in Android 4.3

2019-01-31 18:11发布

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?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-31 18:52

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);
查看更多
做自己的国王
3楼-- · 2019-01-31 19:04

That's worked for me:

Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
contentIntent = PendingIntent.getActivity(this, randomInt, intent, PendingIntent.FLAG_UPDATE_CURRENT);
查看更多
登录 后发表回答