【发布时间】:2018-03-04 22:35:28
【问题描述】:
我正在 Android Studio 中开发一个简单的游戏,我正在调用 GameOver 活动,并使用“重试”按钮形成游戏活动(刚刚命名为 MainActivity)。当主角与其中一个怪物发生碰撞时会调用它。我的问题是,当我尝试通过((Activity)getContext()).finish(); 完成时,我的应用程序关闭而不是开始新活动。这是启动它的方法:
public void isCharacterDead(){
for (Monster item : monsters) {
if (characters.get(0).deadCollision.contains(item.collision.centerX(), item.collision.centerY())) {
player.stop();
long gameOverDelayEnd = (System.nanoTime()/1000000)+1000;
long gameOverDelayStart = System.nanoTime()/1000000;
while(gameOverDelayStart < gameOverDelayEnd){
gameOverDelayStart = System.nanoTime()/1000000;
}
characters.remove(0);
Intent gameOver = new Intent(getContext(),GameOver.class);
gameOver.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
((Activity)getContext()).finish();
getContext().startActivity(gameOver);
}
}
}
我的 GameOver Activity 是:
public class GameOver extends Activity {
private Button tryAgain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//removing the title from the screen in order to have empty screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setContentView(R.layout.activity_game_over);
tryAgain = (Button) findViewById(R.id.tryagain);
tryAgain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent game = new Intent(GameOver.this, MainActivity.class);
GameOver.this.finish();
startActivity(game);
}
});
}
}
现在,如果我不使用((Activity)getContext()).finish();,它将启动 GameOver 活动,当单击 Try Again 时,我将移动到 Game Activity(MainActivity) 的新实例。但它会通过 GameOver 中的“重试”按钮降低每次新开始时的性能。我想这是由于在最后一个游戏中开始新游戏活动而没有完成它。关于如何避免这种情况的任何建议? android 监视器内没有任何异常(我的 GPU 监视器也被禁用)。
【问题讨论】:
-
你为什么使用 Intent.FLAG_ACTIVITY_NEW_TASK 以及你的代码是在哪里写的? getContext() 方法是如何工作的?
-
isCharacterDead() 在自定义视图中。在更新精灵位置的每一帧之后调用它。
标签: java android android-activity view