Activity layout blinking after finish() is called

arthursfreire picture arthursfreire · Aug 4, 2015 · Viewed 7.4k times · Source

When I open my app, an Activity is started, and inside its onCreate method I'm checking some conditions. If the condition is true, I finish my current Activity and open another one. The problem is: The first activity blinks on the screen and then the second one is opened. The code is below:

public class FirstActivity extends Activity {
    @Override
    protected final void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //some code here...
        checkSomeStuff();
        setContentView(R.layout.my_layout);
        //some code here...
    }
    private void checkSomeStuff() {
        if (/*some condition*/) {
            final Intent intent = new Intent(this, SecondActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            finish();
            startActivity(intent);
        }
    }
}

Notice that setContentView() is after the check, but before the second activity is started, the first one still blinks on the screen. Does anyone know how to make it not blink?

Thanks in advance.

Answer

PSchuette picture PSchuette · Aug 4, 2015

The purpose of finish() is to destroy the current activity and remove it from the back stack. By calling finish then firing the intent, you are asking the activity to destroy it self (I assume the blink is it trying to recover) then firing the intent to the second. Move finish to after startActivity()

 @Override
protected final void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //some code here...
    if(checkSomeStuff()) {
         setContentView(R.layout.my_layout);
         //some code here...
    }
}

private boolean checkSomeStuff() {
    if (/*some condition*/) {
        final Intent intent = new Intent(this, SecondActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return false;
    }
    return true;
}