Rich Rich - 1 year ago 186
Java Question

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity's launchMode property to singleTop OR by adding the

flag to my Intent, that calling
would reuse a single Activity instance and give me the Intent in the
callback. I did both of these things, and
never fires and
fires every time. The docs also say that
returns the intent that was first passed to the Activity when it was first created. In
I'm calling
and I'm getting a new one every time (I'm creating the intent object in another activity and adding an extra to it...this extra should be the same every time if it was returning me the same intent object). All this leads me to believe that my activity is not acting like a "single top", and I don't understand why.

To add some background in case I'm simply missing a required step, here's my Activity declaration in the manifest and the code I'm using to launch the activity. The Activity itself doesn't do anything worth mentioning in regards to this:

in AndroidManifest.xml:


in my calling Activity:

Intent i = new Intent();
i.putExtra(EXTRA_KEY_ARTIST, id);
i.setClass(this, ArtistActivity.class);

znq znq
Answer Source

Did you check if onDestroy() was called as well? That's probably why onCreate() gets invoked every time instead of onNewIntent(), which would only be called if the activity is already existing.

For example if you leave your activity via the BACK-button it gets destroyed by default. But if you go up higher on the activity stack into other activities and from there call your ArtistActivity.class again it will skip onCreate() and go directly to onNewIntent(), because the activity has already been created and since you defined it as singleTop Android won't create a new instance of it, but take the one that is already lying around.

What I do to see what's going on I implement dummy functions for all the different states of each activity so I always now what's going on:

public void onDestroy() {
    Log.i(TAG, "onDestroy()");

Same for onRestart(), onStart(), onResume(), onPause(), onDestroy()

If the above (BACK-button) wasn't your problem, implementing these dummies will at least help you debugging it a bit better.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download