我正在制作一款安卓应用,包括主菜单和游戏活动两个活动。目前应用程序运行良好,而且在两个活动之间切换也正常工作。但是,当游戏活动正在运行时我按下了Home键,再次打开游戏时就会出现黑屏并且没有任何反应。我已经创建了所有的生命周期方法并且每次调用时都打印信息,但是当我尝试重新打开应用程序时,它不会调用主菜单或游戏活动的onCreate()、onStart()或onResume()方法。如果我到任务管理器中关闭应用程序,然后再重新打开它,它会像预期的那样打开到主菜单活动。问题只会在我按下Home键然后再次打开应用程序时出现。有没有办法解决这个问题?
以下是我的游戏活动的一些代码,包括所有的生命周期方法:
以下是我的游戏活动的一些代码,包括所有的生命周期方法:
public class Klondike extends Activity{
private KlondikeGameView gameView;
private StatsHandler statsHandler;
private KlondikeGameStats gameStats;
private RelativeLayout mainLayout;
public boolean createSavedGame;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createSavedGame = true;
setContentView(R.layout.klondike);
mainLayout = (RelativeLayout) findViewById(R.id.main_klondike_layout);
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
this.statsHandler = new StatsHandler();
this.gameStats = new KlondikeGameStats(System.currentTimeMillis());
gameView = new KlondikeGameView(getApplicationContext(), this, dm.heightPixels, dm.widthPixels, statsHandler, gameStats);
mainLayout.addView(gameView);
gameView.startGameThread();
}
@Override
protected void onStart() {
super.onStart();
System.out.println("OnStart was called for Klondike");
}
@Override
protected void onResume() {
super.onResume();
System.out.println("OnResume was called for Klondike");
if (KlondikeSaveHandler.checkIfSavedStateExists(getApplicationContext())){
KlondikeSaveHandler.restoreSavedState(getApplicationContext(), gameStats, gameView.getGameBoard());
}
}
@Override
protected void onPause() {
super.onPause();
System.out.println("OnPause was called for Klondike");
if (createSavedGame){
KlondikeSaveHandler.prepareSavedGame(getApplicationContext(), gameStats, gameView.getGameBoard());
System.out.println("Game saved");
}
else {
System.out.println("Game not eligible for saving");
}
}
@Override
protected void onStop() {
super.onStop();
System.out.println("OnStop was called for Klondike");
}
@Override
protected void onRestart() {
super.onRestart();
System.out.println("OnRestart was called for Klondike");
}
@Override
protected void onDestroy() {
super.onDestroy();
System.out.println("OnDestroy was called for Klondike");
}
}
在我按下主页按钮后,onPause被调用,游戏得到了正确的保存。
这是清单文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.thomas.solitaire" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.app.thomas.solitaire.MainMenu"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.app.thomas.solitaire.Klondike"
android:label="Klondike"
android:theme="@style/AppTheme">
</activity>
</application>
</manifest>