Android - GCM push notification that sends user to

2019-05-26 09:14发布

问题:

I am able to create push notifications, and to send the user to whichever Activity I want, but I notice that whenever the user lands on that Activity, the onCreate function does not get called.

Is that supposed to be the case? How do I set it so that the onCreate of the Activity is called?

Here is my Activity:

public class QuestionActivity extends BaseListActivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState) 

and here is how the notification is generated:

    Intent notificationIntent = new Intent(context, MainActivity.class);
    if ( notification_type != null && notification_type.equals("question"))
    {
        notificationIntent = new Intent(context, QuestionActivity.class);
    }
    else
    if ( notification_type != null && notification_type.equals("plan"))
    {
        notificationIntent = new Intent(context, TopicActivity.class);              
    }

    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);        
    Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);            

    Notification notification = new NotificationCompat.Builder(context)
     .setContentTitle(title)
     .setContentText(message)
     .setContentIntent(intent)
     .setSmallIcon(icon)
     .setLights(Color.YELLOW, 1, 2)
     .setAutoCancel(true)
     .setSound(defaultSound)
     .build();

    notificationManager.notify(0, notification);

Thanks!

回答1:

The flags that you are using Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP mean that if the activity is already running in the current task, then instead of launching a new instance of that activity, the old existing activity will be used. In that case onCreate won't be called, since the activity already exists.