Finish old activity and start a new one or vice versa

后端 未结 7 2162
轮回少年
轮回少年 2020-12-02 15:16

I know, that I get the same result with both code snippets

finish();
startActivity(newActivity);

and

startActivity(newActiv         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 15:39

    There is an important difference in application task behavior depending on the order of startActivity() and finish() invocations.

    The case I am describing is scoped only to the situation when the current activity (the one being stopped) is the only one in the task.

    Normally you would expect that the starting intent (the intent you create to start another activity) is not altered by the system. And that is not the case if finish() is called on the last activity in the task before calling startActivity().

    In this case the ActivityManager, a system component, while executing the startActivity() adds Intent.FLAG_ACTIVITY_NEW_TASK flag to your intent.

    When this happens, then one may notice a log entry in the LogCat similar to this one:

    W/ActivityManager: startActivity called from finishing ActivityRecord{4a19b47 u0 com.foo.bar/com.foo.bar.SplashActivity t4928 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.foo.bar/com.foo.bar.MainActivity }

    And this is the turning point from which (under some conditions) things may go wrong.

    To sum up, if you want to be on a safe side (rather than experience unexpected side effects of the FLAG_ACTIVITY_NEW_TASK being added to the intent), then the order must be:

    • startActivity()
    • finish()

    Demo project.

    Screen recordings:

    • startActivity_finish.mp4 - works as expected.
    • finish_startActivity.mp4 - unexpected activity duplicate.

提交回复
热议问题