jwBurnside
jwBurnside

Reputation: 867

Calling onNewIntent() from a notification

MainActivity hosts all of my fragments.

I need to display one particular fragment when the user clicks on a Notification that was received from Google Cloud Messaging.

I was under the impression that I could handle this from onNewIntent(), but this method doesn't seem to fire after I press the notification.

Here's my send notification method in my GcmIntentService class:

private void sendNotification(String message, String eventId) {

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

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.putExtra(Constants.eventIdBundleKey, eventId);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
            Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_test)
                    .setContentTitle(getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(message))
                    .setContentText(message);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}

and here in MainActivity, where I'm trying to receive and process:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);


    if(intent.hasExtra(Constants.eventIdBundleKey)) {

        Fragment fragment = GiftsPriceFragment.newInstance(Common.retrieveAppUser(this), null, null);
        mFm.beginTransaction().replace(R.id.content_frame, fragment)
                .addToBackStack(GiftsPriceFragment.FRAGMENT_TAG).commit();

    }

}

Any idea why onNewIntent() doesn't get called?

Upvotes: 6

Views: 7564

Answers (1)

Nitesh
Nitesh

Reputation: 3903

Try setting launchMode of your activity as "singleTop" in manifest.

From Official documentation.

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

Upvotes: 11

Related Questions