4

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?

Chris Rae
  • 5,627
  • 2
  • 36
  • 51
  • You could try logging the time between your calling finish() and your Activity's onDestroy() being called for a rough estimate on how long it takes. – Raghav Sood Jan 10 '13 at 19:56
  • 1
    There is a good reply here. https://stackoverflow.com/a/22526967/2751547 – Zafer Feb 13 '18 at 16:29

4 Answers4

7

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

codeMagic
  • 44,549
  • 13
  • 77
  • 93
5

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.

Joel
  • 4,732
  • 9
  • 39
  • 54
2

Activity.finish() will not stop the current activity until the method is completely executed so to skip the remaining part of the code, you may use a return; use it with some condition to validate your skip.

if ( condition = true ) {

      this.finish();
      return;
}
MrManshenoy
  • 471
  • 4
  • 4
1

Chris, I am no expert, but at the answer here about finish() in android is basically what codeMagic just said. The link is valuable because of the discussion regarding onStop() and onDestroy()

Community
  • 1
  • 1
  • Whoop, you're right - I hadn't realised the question was a dupe (I was evidently using the wrong search terms!). – Chris Rae Jan 11 '13 at 05:55