开发者

Android: State management seems wrong

Lets say we have activities A, B. A starts B and passes an Intent Extra "id". Now the weird-ness only seems to happen with certain actions.

Start App

A calls B passes Extra: id 1

While in B press the home button.

Find the app icon and click on it.

A calls B but this time 开发者_JAVA百科I pass in Extra: id 2

Now in B when it prints out the id it is 1 even though I specified id 2.

From further analysis it doesn't seem to be getting the new Intent, it seems to be using the old Intent, and the second time in doesn't seem to be calling the onCreate it goes straight to onRestart. So my question is, is there a way to onRestart have it get the correct Intent Extras? It seems to be grabbing the old saved extras.

I am sorry if this is hard to follow, I will see if I can get a small sample app put together that demonstrates this.

EDIT It appears this scenerio is not normal, and it is caused because in my AndroidManifest.xml I had my activities with the property android:launchMode="singleInstance" once I removed this it began acting as described by Rich.


When you press the Home button, B is still active. So, the next time you press your app's icon, all it's doing is resuming activity B. It's not starting A and redirecting to B as it did the first time.

Your best option is to maintain your state in a persistent storage (SharedPreferences, Sqlite, file, etc) so that you don't rely on the Intent extras being passed around. You can already see that this is too clumsy of a method to rely on.

The quick and dirty way to do it is to kill activity B when the user navigates away from it (thereby making sure that the next time your icon is pressed it loads Activity A first). Here's the code for doing that, but I definitely recommend saving state properly as described above over a solution like this.

@Override
public void onPause()
{
    super.onPause();
    finish();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜