58

I am working on an Android application that requires a user to login before doing anything else. Currently I have created main Activity named LoginScreen and upon successful login this activity launches another Activity called Home. But I see a problem with this approach. What if user presses back button from Home activity? I dont want user going back to login screen. what is the correct way of stopping the user from doing that. Do I need to handle Key Press events?

2

6 Answers 6

54

What I ended up doing was to make my Home activity handle the intent android.intent.action.MAIN. Home activity, when launched, checks if the user is signed in or not (using shared preferences), if its not then it starts LoginActivity and calls finish() on its self.

LoginActivity on successful login starts the Main activity and this time because the user is logged on, the Main activity will continue its normal course. LoginActivity is declared as following in the manifest file:

<activity android:name="LoginScreen" android:label="@string/app_name"
    android:noHistory="true" android:excludeFromRecents="true">
</activity>

Setting noHistory and excludeFromRecents to true for LoginActivity means that the user cant return to this activity using back button.

9
  • 5
    After LoginActivity starts Home again, why don't you immediately finish() the LoginActivity too, just like you did with the Home activity? Why is android:noHistory a better approach here?
    – skrebbel
    Jul 5, 2013 at 8:05
  • 1
    Good question skrebbel :) Please, could you reason your solution or post differences between noHistory and finish() approach?
    – kravemir
    Sep 5, 2013 at 15:55
  • @skrebbel plz look at my comment to the answer by Jason-Robinson.
    – binW
    Jan 15, 2014 at 19:13
  • 2
    One problem with noHistory is that once the next activity is added to the stack, the noHistory activity may be destroyed. (It will likely be at that point.) The activity isn't merely skipped over when the user hits the back button...it's pre-emptively destroyed. So, if your Login activity has a Privacy Policy or something else that might push on to the back stack, your Login pag might go away.
    – ZaBlanc
    Aug 26, 2014 at 5:55
  • 1
    Why is the approach better than turning the login activity into the Launcher Activity and then on the login activity check if the user is logged on or not? Jul 29, 2016 at 18:25
22

After you call startActivity(...) in the LoginScreen activity, call finish(). This will remove that activity from the activity stack, so pressing back will essentially close your app once you're in your Home activity.

2
  • 1
    If I do that then when, for any reason, my app goes in to background like when I press home screen, then pressing my apps icon from main screen will again show the login activity which will be added on top of Home activity in the stack.
    – binW
    May 2, 2011 at 16:04
  • 1
    Then you need to check in the onCreate(...) of the LoginScreen if you have the sufficient data to move on, and if so, start the Home activity. If not, wait for the user to log in. You can do this with SharedPreferences if you need something simple. May 2, 2011 at 16:22
1

Try setting flags to the Intent.

Example:

new Intent(context, SomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

More information on flags: http://developer.android.com/reference/android/content/Intent.html#nestedclasses

1

See: https://stackoverflow.com/a/41290453/4560689 (text below)

To do this, you should create a single launcher activity with No Display (using Android's NoDisplay theme), that runs the logic of whether to go to the home screen or to log in/register.

First, in your manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.android">

<-- Permissions etc -->

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">

    <activity
        android:name=".onboarding.StartupActivity"
        android:label="@string/app_name"
        android:launchMode="singleInstance"
        android:theme="android:style/Theme.NoDisplay">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop" />

    <activity
        android:name=".authentication.controller.AuthenticationActivity"
        android:label="@string/title_sign_in"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize|stateHidden" />

    <-- Other activities, services, etc -->
</application>

Then, your StartupActivity:

package com.example.android.onboarding;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.example.android.MainActivity;

import com.example.android.authentication.controller.AuthenticationActivity;

import com.example.android.util.ResourceUtils;

public class StartupActivity extends Activity {
    private static final AUTHENTICATION_REQUEST_CODE = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (isLoggedIn()) {
            Intent startupIntent = new Intent(this, MainActivity.class);
            startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(startupIntent);
            finish();
        } else {
            Intent startupIntent = new Intent(this, AuthenticationActivity.class);
            startActivityForResult(startupIntent, AUTHENTICATION_REQUEST_CODE);
        }

        super.onCreate(savedInstanceState);
    }

    private boolean isLoggedIn() {
        // Check SharedPreferences or wherever you store login information
        return this.getSharedPreferences("my_app_preferences", Context.MODE_PRIVATE).getBoolean("loggedIn", false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AUTHENTICATION_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Intent startupIntent = new Intent(this, MainActivity.class);
            startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(startupIntent);
        }

        finish();
    }
}

Gist here: https://gist.github.com/chanakin/c44bf1c6a9a80d2640440b5aaa92c8ee

0
1

LoginActivity.xml

 <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true"
    android:background="#263238">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="80dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">

        <!-- App Logo -->
        <ImageView android:id="@+id/logo"
            android:src="@drawable/logo"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginBottom="20dp"
            android:layout_gravity="center_horizontal" />

        <!--Title TextView-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="STOCK BUDDY"
            android:id="@+id/title"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="#7B869B"
            android:layout_marginBottom="24dp"
            android:layout_gravity="center_horizontal"/>

        <!--User Email-->
        <EditText
            android:id="@+id/login_email"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"
            android:layout_centerVertical="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:ellipsize="start"
            android:gravity="center"
            android:hint="Email"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:textColorHint="#cccccc"
            android:textColor="#7B869B"
            android:maxLength="40"
            android:maxLines="1"
            android:inputType="textEmailAddress"
            android:background="@drawable/edittextshape"/>

        <!-- User Password -->
        <EditText
            android:id="@+id/login_password"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="10dp"
            android:layout_centerVertical="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:ellipsize="start"
            android:gravity="center"
            android:paddingRight="16dp"
            android:paddingLeft="16dp"
            android:hint="Password"
            android:textColor="#7B869B"
            android:textColorHint="#cccccc"
            android:maxLength="20"
            android:maxLines="1"
            android:inputType="textPassword"
            android:background="@drawable/edittextshape"/>

        <!--Login Button-->
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_login"
            android:layout_width="fill_parent"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="24dp"
            android:background="@drawable/buttonshape"
            android:text="Login"
            android:textSize="20sp"
            android:layout_height="40dp"
            android:textColor="#ffffff"
            android:shadowRadius="5"
            android:onClick="Login"/>

        <!--signup Link TextView-->
        <TextView android:id="@+id/link_signup"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="24dp"
            android:text="No account yet? Create one"
            android:gravity="center"
            android:textSize="12sp"
            android:textColor="#7B869B"/>

    </LinearLayout>
</ScrollView>

buttonshape.xml

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners
        android:radius="44dp"
        />
    <gradient
        android:angle="45"
        android:centerX="35%"
        android:centerColor="#63D0C3"
        android:startColor="#70DB9A"
        android:endColor="#56C5EE"
        android:type="linear"
        />
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp"
        />
    <stroke
        android:width="0dp"
        android:color="#878787"
        />
</shape>

edittextshape.xml

    <?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:thickness="0dp"
    android:shape="rectangle">
    <solid android:color="#ffffff"/>
    <stroke android:width="1dp"
        android:color="#ffffff" />
    <corners android:radius="44dp" />
</shape>

.....................

please see full code on https://androidpugnator.wordpress.com/2017/03/12/android-login-and-signup-screens

Image of login Screen

0
0

Call startActivity(...) in the LoginActivity on some event(say login button click ). Use a separate database class also to store username and password of user from HomeActivity class.

Handle the onKeyDown() event for controlling back button in HomeActivity(use finish() method).

In OnCreate() method of LoginActivity class use database connection to check whether the username & password already exist in the database table if yes then call startActivity() there too to directly go to HomeScreen from LoginScreen.This will not show the LoginScreen.

Hope this will work for you. Try it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.