Android application loses state after launching another intent

只愿长相守 提交于 2019-12-24 09:49:22

问题


So I have the following:

A Common class that many of my Activities access in my android application, via setting the class in my manifest:

<application android:name="com.dev.games.phraseparty.Common"... />

Now, within this class I have several objects that are constructed to preserve application state and common services to perform applications that are constructed in the Common constructor

ie

GameStateVO gameState;

public Common()
{
    gameState = new GameStateVO();
}

My problem is that my Activity has an Admob ad. When the user clicks on the ad, it calls the webbrowser intent to open the ad URL in a webbrowser.

Now, when I click back from the webbrowser launched by admob, it takes me back to the caling activity and the OnCreate method is called.

This activity then gets a null pointer exception because it will do something like:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Common common = this.getApplication();

//null pointer here since the game state VO is null since the Common has lost its state.
int score = common.getGameState().getScore();

}

回答1:


If you have no active foreground activity, then your process is ripe for shutdown by the OS to obtain more resources. The browser app in particular i've noticed uses a lot of resources and can quickly lead to background activities and later processes being killed off. Having a service can help keep your process around, but even then it can still be killed off if needed. I think you'll need to use the activity lifetime cycle method to save & restore your state. See the process lifecycle section of the docs for more info




回答2:


You might want to look into implementing the onSaveInstanceState method: this lets you store any relevant information before it gets killed off. See http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29 for the actual call you need to implement, and Saving Android Activity state using Save Instance State for a quite excellent example.



来源:https://stackoverflow.com/questions/6025554/android-application-loses-state-after-launching-another-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!