如何终止活动并切换到另一个活动?

时间:2014-09-19 12:30:30

标签: java android

我做这样的事情:

public class MyActivity extends Activity {
  @Override
  public void onStart() {
    super.onStart();
    User user = new Entrance().enter();
    // continue with user, since it's a valid one
  }
}
// I'm using this class from many activities
public class Entrance {
  public User enter() {
    try {
      User user = new Hub().enter();
    } catch (AuthenticationFailedException ex) {
      this.startActivity(new Intent(this, LoginActivity.class));
      this.finish();
    }
    return user;
  } 
}

此代码不起作用,因为finish()不会抛出异常并让执行流程继续。这种情况的正确设计是什么?

3 个答案:

答案 0 :(得分:0)

您可以使用Activity.isFinishing()方法分隔逻辑流。

public void onStart() {
    super.onStart();
    User user = new Entrance().enter();
    // continue with user, since it's a valid one
    if (isFinishing()) {
        ...
    } else {
        ...
    }
}

答案 1 :(得分:0)

由于您正在使用多个活动的Entrance类,因此您应该将Activity的Context传递给Entrance类中的enter()方法。它应该如下:

public User enter(Context context) {
  try {
    User user = new Hub().enter();
  } catch (AuthenticationFailedException ex) {
    context.startActivity(new Intent(context, LoginActivity.class));
    context.finish();
  }
  return user;
} 

答案 2 :(得分:0)

尝试这一点,首先创建一个意图,第二个完成活动开始下一个/期望活动通过意图

Intent loginIntent=new Intent(MyActivity.this, LoginActivity.class);
MyActivity.this.finish();
startActivity(loginIntent);