Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

android - How to return to the latest launched activity when re-launching application after pressing HOME?

Familiar scenario: I have a Main activity that launches a Game activity when a button is pressed. If the user presses HOME, and then launches my application again, it should be presented with the Game activity, which is what he was doing last when using the application.

However, what happens instead is he gets the Main activity again. I have the feeling that Android is creating another instance of MainActivity and adding it to the stack for that application, instead of just picking whatever was on the top, because if I press BACK after relaunching the app, I get to the Game activity! And the Main.onCreate method is called every time, instead of calling GameActivity.onResume.

My AndroidManifest.xml is pretty much 'bare bones':

<activity android:name="MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name="GameActivity" android:label="@string/app_name">
</activity>

As you can see, nothing too fancy.

And this is how the new activity is launched, very simple too:

Intent intent = new Intent(this, GameActivity.class);
startActivity(intent);

In theory this should work in Android just "out of the box", as the answer to a very similar question says: Maintaining standard application Activity back stack state in Android (using singleTask launch mode), but it isn't.

I've been reading and re-reading the documentation on Activity and Task and Stacks and browsing all related answers in SO but I can't understand why such a simple setup is not quite working as expected.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
    @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
        // Activity was brought to front and not created, 
        // Thus finishing this will get us to the last viewed activity 
        finish(); 
        return; 
    } 

    // Regular activity creation code... 
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...