简体   繁体   English

如何完成当前活动并开始另一个活动?

[英]How to finish the current activity and start another one?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
/**
     * Check for login session. If not logged in launch
     * login activity
     * */
    if (MyApplication.getInstance().getPrefManager().getUser() == null) {
        launchLoginActivity();
        Log.e(TAG, "Still im in MainActivity !!! ");
    }
 ....
 ....

and this is the launch activity method: 这是启动活动方法:

 private void launchLoginActivity() {
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    Log.e(TAG, "launchLoginActivity");
    startActivity(intent);
    finish();
}

The activity is launched but I still am in my main activity. 该活动已启动,但我仍处于主要活动中。

As you can see in the console, the two log messages are displayed. 如您在控制台中所看到的,将显示两条日志消息。

One in launch method, and another one in the main activity after the launch method is called. 一个在启动方法中,另一个在启动方法调用后的主活动中。

How can I finish my main activity and not display the log message in the main activity? 如何完成我的主要活动,而在主要活动中不显示日志消息?

错误

Your main activity will, eventually, finish after you exit from onCreate() . onCreate()退出后,您的主要活动最终将结束。 Put some debug logging in your main activity's onDestroy() and you will see you get in there. 在主要活动的onDestroy()放置一些调试日志,您将看到您进入那里。 If you want to skip everything after invoking your second activity then just put a return after that. 如果要在调用第二个活动后跳过所有内容,则在此之后再输入一个return There is also the Activity.isFinishing() API which returns true if your activity is being finished. 还有一个Activity.isFinishing() API,如果您的活动结束,该API将返回true。

Well, finish() the activity in question and then return so that the starting activity breaks out of the 'onCreate' method and the acitvity is destroyed through the normal live cycle. 好了,完成所讨论的活动,然后返回,以便开始活动脱离“ onCreate”方法,并且活动在正常的活动周期中被破坏。

if (MyApplication.getInstance().getPrefManager().getUser() == null) {
    launchLoginActivity(); //the finish part already happens here. I did not see that.
    return;
    Log.e(TAG, "Still im in MainActivity !!! ");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM