android - 应用程序要求两次退出 onBackPressed()

标签 android

我使用以下方法通过向用户提示警告框来退出应用程序。
但是我的应用程序要求离开 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();
    }

最佳答案

这可能是几件事的结果:

  1. 您还覆盖了 void onKeyDown(...)void dispatchKeyEvent(...) 并在那里调用 onBackPressed();

  2. 你已经覆盖了void finish()
    然后你调用第二个对话框

  3. 您的应用实例化了 2 次
    (出于任何原因——查看您的代码?)

  4. 你故意打开你的 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.

  5. 如果其中一些对您有帮助,请在评论中告诉我
    否则发布更多代码,我会尽力帮助您;)

关于android - 应用程序要求两次退出 onBackPressed(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901983/

相关文章:

android - Jetpack Compose 是否提供 Material AutoComplete TextView 替代品?

Android:工具栏上的向上按钮的右边距

java - 在 LinearLayout 中定位元素

android - 如何在Android上的Camera2 API中设置 '' CONTROL_AE_EXPOSURE_COMPENSATION''?

android - 如何将 Activity 注入(inject)另一个类(class)

android - 将 (Boost) Asio 与 Android NDK 结合使用的限制

android - 应用于文本的方法 canvas.rotate(90) 对于 android 4.0-4.1 已损坏

android - 以编程方式(和膨胀)向布局添加 View 非常慢

android - 有没有办法改变来自Android的音频输出的左右声道的音量?

java - Android:如何将字符串转换为日期