After Home button press re-launching app shows ini

2019-02-12 00:20发布

问题:

I have an application that has an initial activity (A - also the one specified in the launcher) from which it allows the user to launch another activity (B). I am saving the state of Activity B (onSaveInstanceState() and restoring it in onCreate()).

On some phones (N1 and Motrola Milestone as of now but not the Galaxy S) after launching B if the user presses the home button (i.e. app goes to background) and then immediately re-launches the app, they are shown activity A again (not B). But if they launch it from the 'Recent' apps (Home button long press) they are taken to the activity B.

From what I understand of the Android docs, unless the task has been killed (doesnt seem like the case here as nothing else is done except re-launch the activity from the app screen) we should see activity B restored on launch (as that is on top of the stack). So I just can't seem to figure out what the heck is wrong here.

BTW orientation changes during app usage works fine (everything saves and restores fine). This weird problem has been bugging me for some time now and by trial and error I discovered that when I disabled orientation for that activity and then trying the re-launching got B to show as expected.

So has anyone else faced something like this and if so how can this be resolved?

I am looking into saving the running activity in SharedPreferences (as mentioned in this post) and they restoring it from that in activity A, however would like to know if I am missing something here. Shouldn't having B restored on re-launch be the default behavior?

回答1:

Try adding this to your activity inside the manifest file:

android:launchMode="singleTask"

This resolved the issue in my app .... if I understand your problem correctly.



回答2:

Use android:launchMode="singleInstance" instead



回答3:

In your AndroidManifest, in the activity tag, just add

android:alwaysRetainTaskState="true"


回答4:

This is because another instance of app is launching when icon is pressed.

  // To prevent launching another instance of app by clicking app icon 
                if (!isTaskRoot()
                        && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
                        && getIntent().getAction() != null
                        && getIntent().getAction().equals(Intent.ACTION_MAIN)) {

                    finish();
                    return;
                }

write the above code in your launcher activity before calling setContentView. This will solve the problem



回答5:

This answer is for someone coming from search engine due to similar kind of issue.

I had,

Launcher Activity -> A 
Main Activity -> B

Always starts A after pressing HOME button or Switching from task list when application was in B.

Finally found that the problem was in manifest, removed

android:noHistory = "true"

from Activity declaration of B in manifest and it was resolved.