【问题标题】:cannot understand the finish method android [duplicate]无法理解完成方法android [重复]
【发布时间】:2017-09-20 08:45:52
【问题描述】:
protected void onCreate(Bundle savedInstanceState) {
  //if user is already logged in open the profile activity directly
  if (SharedPrefManager.getInstance(this).isLoggedIn()) {
    finish();
    startActivity(new Intent(this, Home.class));
  }
  buttonSignIn.setOnClickListener(this);
  buttonSignUp.setOnClickListener(this);
}

如果用户已经登录,有人可以向我解释为什么在启动 Home.class 之前调用 finish()。我正在尝试浏览一些源代码但无法理解这一点。

【问题讨论】:

  • 调用finish()后程序执行不会停止。它只是意味着“完成这个活动,然后开始 Home 活动”。
  • 好的,finish 是否会查找 startActivty() 函数?
  • 如果我在完成和开始活动之间有一些代码行怎么办?
  • stackoverflow.com/questions/18111245/…之后找到了我真正需要的东西,谢谢大家

标签: java android


【解决方案1】:

当你调用finish(); 它更像是这样做的意图:

Intent intent = new Intent(whereYouareActivity.this , mainActivity.class};
startActivity(intent);

【讨论】:

    【解决方案2】:

    当您完成一项活动时,活动会被销毁,但流程不会。这是 Android 编程的一个重要方面,对于了解它与其他平台有何不同非常重要。

    您可以通过添加这些行来完成您的活动:-

    if (SharedPrefManager.getInstance(this).isLoggedIn()) {            
            startActivity(new Intent(this, Home.class));
            finish();
        }
    

    【讨论】:

      【解决方案3】:

      finish() 之后,您无法从活动中获取上下文。

      你必须像这样开始活动:

      if (SharedPrefManager.getInstance(this).isLoggedIn()) {            
              startActivity(new Intent(this, Home.class));
              finish();
          }
      

      【讨论】:

      • 那么在开始一个新的活动之后调用finish是不是更好?
      • 是的,正确的方式
      【解决方案4】:

      通过调用finish(),您可以主动关闭您当前的活动。这可以防止您的活动在用户按下后退按钮时再次显示。

      【讨论】:

        猜你喜欢
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-08
        • 2020-01-07
        • 1970-01-01
        • 2015-06-26
        • 2017-11-23
        相关资源
        最近更新 更多