Clicking notification not opening app/activity

2019-08-01 07:43发布

问题:

I am having trouble having a notification open the app. I've followed the instructions on the Android docs, but to no avail. It creates the notification no problem, but clicking on it just dismisses it.

Please help! Thanks in advance!

Why is clicking the notification not opening the app?

Intent intent = new Intent(this, MainActivity.class);

    String type = "";
    if (extras.containsKey(KEY_TYPE)) type = extras.getString(KEY_TYPE);

    String text = "";

    if (type.equalsIgnoreCase(TYPE_MATCH_FOUND)) {
        // TODO: send intent with all variables, trigger matched fragment when user goes into app



        text = getResources().getString(R.string.msg_found_match);

        intent.putExtra(KEY_TYPE, TYPE_MATCH_FOUND);
    }
    else if (type.equalsIgnoreCase(TYPE_MESSAGE)) {
        // TODO: trigger chat fragment when user goes into app

        text = getResources().getString(R.string.msg_new_message_from);

        intent.putExtra(KEY_TYPE, TYPE_MESSAGE);
    }

    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);        

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("LFDate")
        .setContentText(text)
        .setAutoCancel(true)
        .setLights(Color.parseColor("#0086dd"), 2000, 2000);

    if (prefs.getNotificationVibrate()) mBuilder.setVibrate(new long[] {1000, 1000, 1000});
    if (prefs.getNotificationSound()) mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent);

    PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

回答1:

I faced this same problem earlier today, if you are using kitkat you will have to change to:

// Have pending intent use FLAG_CANCEL_CURRENT, cause on 
// kitkat you get a permission denied error
PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

or you can add the flag to your receiver, or activity launched from the notification in XML:

 android:exported="true"