finish not stoping the activity code execution

房东的猫 提交于 2019-12-23 12:16:40

问题


I tried the following code

Log.d("t20", "First here");
startActivity(new Intent(this, AnotherActivity.class));     
finish();
Log.d("t20", "Then Here");

log output:

First here
Then Here

Why the second log message is printed? The execution should be stopped at finsh(), right?


回答1:


No, finish is not an abort. The function will continue, and when it gets back to the Looper inside the Android framework running the event loop it will begin the deinitialization sequence (calling onPause, onStop, and onDestroy).




回答2:


After calling finish() your activity will not be immediately finished but only planned to be 'finished'. So execution of code will continue. To check if finish() was called on an Activity instance you can invoke Activity.isFinishing() method.

From docs:

Check to see whether this activity is in the process of finishing, either because you
called finish() on it or someone else has requested that it finished. 

So your code sample will look like this:

Log.d("t20", "First here");
startActivity(new Intent(this, AnotherActivity.class));     
finish();
if (!isFinishing()) {
    Log.d("t20", "Then Here");
}



回答3:


When calling finish() on an activity, the method onDestroy() is executed this method can do things like:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog
  4. Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed


来源:https://stackoverflow.com/questions/22525064/finish-not-stoping-the-activity-code-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!