gpt4 book ai didi

android - Activity 在 finish() 之后仍然继续;

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:51 26 4
gpt4 key购买 nike

我有一个测验应用程序,它有一个用于整个游戏 Activity 的计时器,您应该在指定的时间内回答尽可能多的问题..

指定的分钟数结束后,它将带您进入显示您分数的结果 Activity 。在后退时,我创建了一个警告对话框,询问您是否要返回主菜单。如果单击是,页面应返回主菜单并停止/终止游戏 Activity 。

但是,当我单击"is"时,它将返回到主菜单,但当您仍在应用程序的任何位置时,结果仍会显示我之前的游戏 Activity 。也许我还没有真正完成游戏 Activity ,..这是我 Activity 中的计时器和后退按钮 fragment :

new CountDownTimer(seconds, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Seconds left: " + millisUntilFinished / 1000);
}
public void onFinish() {
Intent intent = new Intent(GameActivityAddition.this, Score.class);
intent.putExtra("totalscore", score);
intent.putExtra("numberquestions", rowId);
intent.putExtra("d", difficulty);
db.close();
startActivity(intent);
}
}.start();

@Override
public void onBackPressed() {
AlertDialog.Builder abuilder = new Builder(GameActivityAddition.this);
abuilder.setMessage("Return to Main Menu?");
abuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
Intent main = new Intent(GameActivityAddition.this, Main.class);
startActivity(main);
finish();
}
});
abuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = abuilder.create();
alert.show();
}

最佳答案

不能保证 finish() 会立即关闭您当前的 Activity (这取决于 Android。)


要解决你的问题试试这个,


保留对计时器的引用(当用户离开当前 Activity 时,您将使用它来取消计时器),

CountDownTimer resultTimer = new CountDownTimer(seconds, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Seconds left: " + millisUntilFinished / 1000);
}
public void onFinish() {
Intent intent = new Intent(GameActivityAddition.this, Score.class);
intent.putExtra("totalscore", score);
intent.putExtra("numberquestions", rowId);
intent.putExtra("d", difficulty);
db.close();
startActivity(intent);
}
}.start();


并在 onBackPressed() 中 - 在 setPositiveButton 回调中取消定时器,


@Override
public void onBackPressed() {
AlertDialog.Builder abuilder = new Builder(GameActivityAddition.this);
abuilder.setMessage("Return to Main Menu?");
abuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
resultTimer.cancel(); //Stop the timer
resultTimer = null;
Intent main = new Intent(GameActivityAddition.this, Main.class);
startActivity(main);
finish();
}
});
abuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = abuilder.create();
alert.show();
}

关于android - Activity 在 finish() 之后仍然继续;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12419496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com