Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this.finish() really do? Does it stop my code running?

Tags:

android

I'm a bit hazy about what exactly this.finish() does. Specifically, I just wrote the following lines of code in an activity:

this.finish();
Globals gs = (Globals) getApplication();
gs.MainActivity.finish();

The code is meant to close the current activity and also close the core activity of the app. And it works great. However, I got wondering... obviously the current activity isn't quite ended after the first line is executed. And what if I was to call this.finish() and then start on some complicated computation?

My question is: When I call this.finish(), when exactly does my Activity get taken down?

like image 814
Chris Rae Avatar asked Dec 06 '22 10:12

Chris Rae


2 Answers

Whatever method called finish() will run all the way through before the finish() method actually starts. So, to answer your question, after the calling method finishes then your activity will run its finish method. If you don't want the method to continue then you can add a return statement after finish

like image 97
codeMagic Avatar answered Feb 20 '23 09:02

codeMagic


I'm a bit hazy about what exactly this.finish() does

Calling finish() basically just notifies the Android OS that your activity is ready to be destroyed. Android will then (whenever its ready) call onPause() on the activity and proceed to destroy it (no guarentee onDestroy() will be called), via the activity lifecycle. In general, you probably should not be doing any more execution after you call finish(). According to the Android docs, you should call finish() when you are ready to close the activity.

when exactly does my Activity get taken down?

I am guessing your activity will simply be added to some destroy queue. During this time you might be able to continue executing until the OS destroys it. I believe you are for sure allowed to finish executing the method from which finish() was called.

like image 20
Joel Avatar answered Feb 20 '23 10:02

Joel