Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finish not stoping the activity code execution

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?

like image 395
Mohammed H Avatar asked Dec 15 '22 00:12

Mohammed H


2 Answers

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).

like image 78
Gabe Sechan Avatar answered Jan 02 '23 18:01

Gabe Sechan


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");
}
like image 20
makovkastar Avatar answered Jan 02 '23 17:01

makovkastar