问题
My use case for a game looks so: I have a LoadingActivity, which loads (by AsyncTask, but this doesn't matter) and stores all the graphics needed for the game in a static class. After the loading finished, the MenuActivity appears. From this Activity I can launch other Activities like LikeBeginActivity.
This is the snippet of the manifest:
<activity
android:name="my.domain.mygame.LoadingActivity"
android:alwaysRetainTaskState="true"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="my.domain.mygame.MenuActivity"
android:theme="@android:style/Theme.NoTitleBar" >
</activity>
<activity
android:name="my.domain.mygame.LevelBeginActivity"
android:theme="@android:style/Theme.NoTitleBar" >
</activity>
The invocations look like this:
LoadingActivity
public void startMenu()
{
final Intent gameIntent = new Intent(this, MenuActivity.class);
startActivity(gameIntent);
}
MenuActivity
buttonStartNewGame.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent levelIntent = new Intent(MenuActivity.this, LevelBeginActivity.class);
levelIntent.putExtra(IntentConstants.STARTLEVELINDEX, 0);
startActivity(levelIntent);
}
});
The annoying problem is that when I'm in the LevelbeginActivity and press HOME, and resume the game by launcher, it always starts at LoadingActivity, but why is the whole task cleared? That doesn't make sense to me. Then I thought about adding
android:alwaysRetainTaskState="true"
to the LoadingActivity in the manifest, but this doesn't help either. Why does it start the whole task again? This is very problematic because I run out of memory if the LoadingActivity is started over and over again. (The next issue will be the back button behaviour, but that's another problem). I could tinker some ugly loading behaviour by saving the last Activity name as SharedPreferences or something, but I'd rather prefer a clean solution to this.
回答1:
Android will destroy Activities
if the system needs the memory. You have to make sure that you save the state of your Activity in onSaveInstanceState()
so that you can manually resume it afterwards. You can save the needed values in SharedPreferences
or in an SQLiteDatabase
回答2:
Another instance of app is launched. That is the reason for the issue.
// To prevent launching another instance of app on 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
来源:https://stackoverflow.com/questions/25855220/android-when-resuming-app-after-pressing-home-app-always-starts-at-root-activi