简体   繁体   中英

Resume last activity when launcher icon is clicked

As I see most of application resumes last activity when launcher icon is clicked. However it seems that this is not default behavior. In my application launcher activity is always started when launcher icon is clicked.

How can i configure my application to resume last activity when launcher icon is clicked and application is already running.

Problem:

I'm not qualified to say this a bug, but this behaviour has been around since the first Android version. There is a problem with tasks and roottasks in release builds when starting the application from the launcher. You can find the related bug report here .

Solution:

It can be fixed adding following code to your onCreate of your launcher activity:

if (!isTaskRoot()) {
    finish();
    return;
}

I met the same problem, and solve it by adding android:launchMode="singleInstance" to the application tag inside manifest. You can check the detail about the launchmode in

android:launchMode

You can test the flag: FLAG_ACTIVITY_BROUGHT_TO_FRONT to catch the case when the activity was brought to front and not created.

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {  
        finish(); 
        return; 
    } 

    // Regular activity creation code... 
} 

Are you sure that you don't exit your app? See also Activity Stack .

This depends on the lifecycle of your Activity. See "Activity Lifecycle" in the Android Developer site. If your activity is just paused it will resume if the activity comes back to the foreground thus also if you click the icon.

If you want to let the user continue the last activity even if the activity is destroyed then you must code an own solution to get to the right activity.

This is be an ugly hack, but you could try the following:

Put a static variable called lastStopped in your application subclass (or any singleton for that matter). Set it to null by default.

In the onCreate of your first activity you'll have something like this:

if (MyApp.lastStopped != null) {            

    Intent intent = new Intent(this, MyApp.lastStopped.getClass());
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
    finish();
    return;

}

Now any activity that you want to return to after pressing home should have:

@Override
protected void onStop() {

    super.onStop();
    MyApp.lastStopped = this;

}

Make sure you clear MyApp.lastStopped when you launch another activity to prevent memory leaks.

Let me know if this works for you, it did for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM