Reputation: 3470
I know that a call to finish()
does not cause the activity to return and exit its current scope immediately. It will continue to execute lines of code until it reaches a return
statement or end of the method.
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish()
// this still executes
Log.d(TAG, "onClick - post finish()");
}
And I am aware that multiple methods called within a certain scope all continue to execute until completion when a finish()
call is invoked. So in the code below each of the Log.d
statements is shown in my Logcat.
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
/* Perform a method */
doThis();
Log.d(TAG, "onClick - post finish()");
}
private void doThis(){
Log.d(TAG, "doThis called");
/* Perform another method */
doThat();
Log.d(TAG, "doThis - post finish()");
}
private void doThat(){
Log.d(TAG, "doThat called");
/* Finish the activity! */
finish();
Log.d(TAG, "doThat - post finish()");
}
Here is the Logcat output for the code above:
07-31 14:44:28.354 25367-25367/com.test.app D/MainActivity﹕ doThis called
07-31 14:44:28.354 25367-25367/com.test.app D/MainActivity﹕ doThat called
07-31 14:44:28.355 25367-25367/com.test.app D/MainActivity﹕ doThat - post finish()
07-31 14:44:28.355 25367-25367/com.test.app D/MainActivity﹕ doThis - post finish()
07-31 14:44:28.355 25367-25367/com.test.app D/MainActivity﹕ onClick - post finish()
EDIT:
Is there a better way to stop all code execution when the finish()
method is called? Perhaps using something like CoreyOgburn suggested with willFinish() or
markedToFinish()? Or maybe a way to
finishImmediately()`?
My code that is run after finish()
has no way to know if the Activity is going to be finished. If I didn't want future code to run I would have to add a return
statement after the doThis()
and doThat()
.
Upvotes: 0
Views: 164
Reputation: 684
I have a static util function i use to make sure i dont run into edge case of trying to continue with my general activity work when finish is called.
public static boolean activityNotFinished(Activity activity) {
if (activity == null) {
return false;
}
if (activity.isFinishing()) {
return false;
}
if (activity.isDestroyed()) {
return false;
}
return true;
Upvotes: 1
Reputation: 75629
Finish is NOT terminating anything instantly. Unless you return from your onCreate()
(or whatever) your activity lives. It is marked for killing but unless you return control to the framework it will NOT be killed.
Upvotes: 0