【问题标题】:android-activity start from where it closed when I exit the appandroid-activity 从我退出应用程序时关闭的位置开始
【发布时间】:2015-07-25 14:40:40
【问题描述】:

在 MainActivity 中,我有关闭应用程序的代码:

@Override
public void onBackPressed() {
    if (exit){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();

        super.onBackPressed();
    }else {
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }

当我想关闭应用程序时,我应该按 2 后退按钮。

问题是,当我关闭应用程序时,它从另一个活动开始,主要是从我去过的最后一个活动开始。

我怎样才能始终从 mainActivity 而不是其他活动开始活动?

【问题讨论】:

  • 知道onResume方法吗?你将不得不摆弄它!
  • 只是不要在最后调用 super.onBackPressed
  • 当您退出应用程序时,您正在导航到主页。这是你想做的吗?
  • 是的,如果您正在进行其他活动,那么您将如何转移到主要活动以运行上述代码?你完成所有活动了吗???

标签: android


【解决方案1】:

在每一个自动启动activity的/中编写这部分代码,

@Override
public void onBackPressed() {
YourActivityName.this.finish();
}

【讨论】:

    【解决方案2】:

    尝试启动模式:singleTask 或 singleInstance

    <activity
        android:name=".MainActivity"
        android:launchMode="singleInstance">
    

    【讨论】:

      【解决方案3】:

      使用这几行代码..

          @Override
       public void onBackPressed() {
           super.onBackPressed();
        if (exit){
        Intent intent = new Intent(Intent.ACTION_MAIN);
               intent.addCategory(Intent.CATEGORY_HOME);
               intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
               intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
              finish();
            }else {
               exit = true;
               new Handler().postDelayed(new Runnable() {
                @Override
                 public void run() {
                    exit = false;
                }
             }, 3 * 1000);
         }
      }
      

      【讨论】:

        【解决方案4】:

        覆盖 MainActivity 的 onBackPressed 方法,如下所示

        private int backpressedCount;
        @Override
        public void onBackPressed() {
            backpressedCount++;
            if (backpressedCount == 2) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
        

        【讨论】:

          【解决方案5】:

          当你关闭你的应用程序时,你必须杀死所有的活动,看看这个How to kill an application with all its activities?

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-12-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多