Home » Android » android – Resume last activity when launcher icon is clicked

android – Resume last activity when launcher icon is clicked

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

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;
}

Answer:

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

Answer:

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

Answer:

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.

Answer:

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!

Answer:

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... 
}