【问题标题】:Don't make the application start once again after pressing "Close"按下“关闭”后不要让应用程序再次启动
【发布时间】:2012-04-05 04:15:24
【问题描述】:

我正在使用以下代码在活动之间切换:

Intent b = new Intent(nowActivity.this, About.class);
startActivity(b);
return true;

这段代码运行良好,但它似乎使它在现有活动之上开始了一个新活动。

示例:我在我的 Android 手机上启动应用程序并按下菜单按钮以在屏幕上显示选项菜单。然后我点击“关于”进入应用程序的关于页面。如果我然后按菜单中的“关闭”选项,第一页(应用程序的主屏幕)将在屏幕上可见,一切都回到第 1 格,就像我再次打开应用程序一样。

我不希望它像这样,我现在问你,我该如何解决这个问题?

提前致谢。

【问题讨论】:

  • 点击关闭按钮后不清楚你想要什么
  • 应用程序将在我按下“关闭”按钮后关闭。你知道这是有道理的
  • 你想让活动只运行一次?
  • 查看我对 Nishant 的回答的评论。
  • 尝试具体说明您想要实现的内容,以便获得您真正想要做的事情

标签: android eclipse android-activity


【解决方案1】:

我搞定了!这是解决方案:

nowActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menuItem1:
        Toast.makeText(this, "Du är redan på startsidan", Toast.LENGTH_SHORT).show();
        return false;

    case R.id.menuItem2:
        Intent b = new Intent(nowActivity.this, About.class);
        b.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(b);
        return true;

    case R.id.menuItem3:
        android.os.Process.killProcess(android.os.Process.myPid());
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

关于.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menuItem1:
        Intent a = new Intent(About.this, nowActivity.class);
        a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(a);
        return true;

    case R.id.menuItem2:
        Toast.makeText(this, "Du är redan på \"Om\"-sidan", Toast.LENGTH_SHORT).show();
        return false;

    case R.id.menuItem3:
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        System.exit(0);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

【讨论】:

    【解决方案2】:

    编辑您的代码:调用 finish() 以销毁第一个活动

    Intent b = new Intent(nowActivity.this, About.class);
    startActivity(b);
    finish();
    return true;
    

    【讨论】:

    • 谢谢,但我不想在切换到新活动时关闭活动。当我点击手机上的后退按钮时,应用程序会后退一步(例如从“关于”到“主页”)。如果我再次按下相同的按钮,应用程序将关闭,除非我先选择“关闭”。
    • 谢谢 :) 这些答案有点简洁,但请参阅我对 hopia 答案的评论。
    【解决方案3】:

    当用户点击您的“关闭”按钮时返回主屏幕怎么样?

    以下代码摘自: How to return to home screen from Activity

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
    

    【讨论】:

    • 谢谢!这稍微解决了我的问题。当我按下手机上的返回按钮时,应用程序会关闭,即使应用程序应该返回“主页”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多