Search code examples
androideclipseandroid-activityfragmentsoftkeys

Avoid returning to previous activity


I have an app that at the start checks if the user is logged and acts in two ways:

1) jumps the registration/login activity starting directly from the second activity if the user is logged in

2) let the user do the registration/login process starting from the relative activity

But I have a problem: if the user is logged in(and the app starts directly from the second activity) and presses the back soft key, the app shows the registration/login activity.

How can I avoid it?

I was thinking about modifying the softkey behaviour by calling onBackPressed() in the second activity, but I think it's not so right...


Solution

  • let's assume your have your StartActivity, that has the logic of opening LoginActivity or MainActivity. TO you AndroidManifest.xml add the following XML:

        <activity
            android:name="com.example.StartActivity"
            android:label="@string/app_name"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    

    and in your StartActivity, after calling startActivity(newActivityIntent) call finish(). Example:

    Intent intent;
    if (isLoginRequired) {
        intent = new Intent(this, LoginActivity.class);
    } else {
        intent = new Intent(this, MainActivity.class);
    }
    startActivity(intent);
    finish();