我使用以下方法通过向用户提示警告框来退出应用程序。
但是我的应用程序要求离开 2 次。
代码:
@Override
public void onBackPressed()
{
new AlertDialog.Builder(this)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
最佳答案
这可能是几件事的结果:
您还覆盖了
void onKeyDown(...)
或void dispatchKeyEvent(...)
并在那里调用onBackPressed();
你已经覆盖了
void finish()
然后你调用第二个对话框您的应用实例化了 2 次
(出于任何原因——查看您的代码?)你故意打开你的 Activity 两次,然后我在这里有一个修复:)
用这段代码替换你的代码来打开它:Intent intent = new Intent(this, yourSubActivityClass.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent);
来自文档:
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
如果其中一些对您有帮助,请在评论中告诉我
否则发布更多代码,我会尽力帮助您;)
关于android - 应用程序要求两次退出 onBackPressed(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901983/