![](/img/trans.png)
[英]After pressing back button, not coming to main activity instead closing the app
[英]Closing app on pressed hardware button back twice returns to a previous activity instead
在我的主要活动中,通知用户按下硬件后退按钮以退出应用程序。 在大多数情况下,这都是可行的,除非用户死亡。 当用户死亡时,转到GameOverActivity。 如果用户在此活动中按“后退”按钮,然后继续在主要活动上按两次“后退”,则它将重新打开游戏结束活动。 这是代码,我已经在游戏结束活动中的后退按钮上声明了finish(),但似乎无济于事。
MainScreen返回退出方法:
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
GameOverActivity代码:
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent mainScreenActivityIntent = new Intent(GameOverActivity.this, MainScreenActivity.class);
startActivity(mainScreenActivityIntent);
finish();
}
});
}
@Override
public void onBackPressed() {
Intent mainScreenActivityIntent = new Intent(GameOverActivity.this, MainScreenActivity.class);
mainScreenActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainScreenActivityIntent);
finish();
}
这是碰撞以及因此创建GameOverActivity的逻辑:
if (weight.getBounds().intersect(player.getBounds())) {
player.setTouched(false);
Intent gameOverIntent = new Intent(this.getContext(), GameOverActivity.class);
this.getContext().startActivity(gameOverIntent);
((Activity) getContext()).finish();
}
我认为您对Activity的生命周期有些困惑。 按下GameOverActivity
实例化一个新的mainScreenActivity
,这将产生您的问题。
并在您的GameOverActivity中onbackpressed调用super.onBackPressed
@Override
public void onBackPressed()
{
super.onBackPressed();
// and dont start a new activity as you are stacking MainActivity instances
finish()
}
您将开始一个新活动,而刚刚完成当前活动,则添加必要的代码以完成从onBackPressed开始的活动。
您应该在启动Activity GameOverActivity
之后立即在MainScreen
调用finish()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.