Android: get most recent intent

2019-08-11 08:51发布

问题:

How can I get the last intent sent to an activity?

The docs for onNewIntent() suggest I would need to do something like this:

class MyActivity {
    public void onNewIntent(Intent intent){
        setIntent(intent);
        reactToIntentAndDoStuff()
        super.onNewIntent(Intent intent);
    }
    public void onCreate(){
        reactToIntentAndDoStuff()
        super.onCreate();
    }
    public void onResume(){
        reactToIntentAndDoStuff()
        super.onResume();
    }
    public void reactToIntentAndDoStuff(){
        Intent intent = getIntent();
    }
}

Does this look about right? Or is there a better way? My activity's launchMode will be singleTop. It will need to react to the same Intent in more or less the same way, whether it's already instantiated or not.

回答1:

I think this is the correct way :) Please check if you really need to call reactToIntentAndDoStuff() in onResume() method. I think its not needed.

super.onCreate(); should be first line in onCreate() method.

getIntent() returns an Intent which was received when Activity launched first time. This does not update unless we call setIntent(newIntent) method.