Search code examples
androidandroid-lifecycleactivity-lifecycle

Is Android app visible during onCreate()?


I plan on checking login status of a user in onCreate of MainActivity - and if the user is logged in - immediately redirect to some other View (e.g. ProfileActivity)

I am worried that MainActivity will flicker into the users view before disappearing. Is this of any concern?


Solution

  • I would suggest you to keep MainActivity as LAUNCHER (on singleTask mode) and check the login status before you pass layout to it. This approach will avoid logged in users to wait for 2nd Activity to be launched.

    Note that in @Nicola De Fiorenze answer Activity instance will get killed in all cases. Hence you will create 2 instances of Activity even for users who have already passed login phase.

    Code may look like this:

    Manifest:

    <activity
        android:name="MainActivity"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    

    MainActivity:

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        if(!AuthUtils.isLoggedIn()){
            LoginActivity.startActivity(this);
            finish();
            return;
        }
    
        // Once you know user is logged in, pass layout to activity
        setContentView(resLayoutId);
    }