Search code examples
androidandroid-intentandroid-activityandroid-lifecycle

Android : How to resume from last activity after clearing stack


I have 3 activities LandingActivity -> LoginActivity -> MainActivity I have a login button in Landing activity that starts LoginActivity which takes me to MainActivity after successful login , I cleared the task in LoginActivity so when I press back button on MainActivity the app goes to backroung since it is the root in the task the problem is when I resume it starts from LandingActivity how can I fix that to make it resume from MainActivity

AndroidManifest

<activity android:name=".activity.LandingActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".activity.MainActivity"/>
    <activity android:name=".activity.SignUpActivity"/>
    <activity android:name=".activity.LoginActivity"/>

intent used in login button

val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK )
startActivity(intent)

Solution

  • What you want to do is save a boolean in your shared preferences that saves the state of being logged in. In LandingActivity's onCreate check that boolean, if it's true just clear the task and jump to your MainActivity no UI will show and it'll look like the user just went directly to the main activity. If you then implement logout your app will revert to the old behavior automatically.

    Login button behavior:

    PreferenceManager.getDefaultSharedPreferences(this)
            .edit()
            .putBoolean("is_logged_in", true)
            .apply()
    val intent = Intent(this, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or 
    Intent.FLAG_ACTIVITY_CLEAR_TASK )
    startActivity(intent)
    

    LandingActivity's onCreate:

    override fun onCreate(savedInstanceState: Bundle?) {
        val isLoggedIn = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("is_logged_in", false)
        if (isLoggedIn) {
            val intent = Intent(this, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or 
            Intent.FLAG_ACTIVITY_CLEAR_TASK )
            startActivity(intent)
            return
        }
        // Your normal initialization code here...
    }