How to determine if a finish() call has been made in an Activity?

时间:2015-07-31 20:09:38

标签: android android-activity

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() ormarkedToFinish()? Or maybe a way tofinishImmediately()`?

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

2 个答案:

答案 0 :(得分:1)

我有一个静态的util函数,我用它来确保我不会遇到试图在调用finish时继续我的一般活动工作的边缘情况。

    public static boolean activityNotFinished(Activity activity) {
    if (activity == null) {
        return false;
    }

    if (activity.isFinishing()) {
        return false;
    }

    if (activity.isDestroyed()) {
        return false;
    }

    return true;

答案 1 :(得分:0)

完成 NOT 立即终止任何内容。除非你从onCreate()(或其他)你的活动回来。它被标记为杀戮,但除非你将控制权交还给框架,否则它不会被杀死。