How avoid returning to login layout pressing the back button/key?
Solution 1
I've implemented something similiar using SharedPreferences
. I did this:
LoginActivity
SharedPreferences settings;
public void onCreate(Bundle b) {
super.onCreate(b);
settings = getSharedPreferences("mySharedPref", 0);
if (settings.getBoolean("connected", false)) {
/* The user has already login, so start the dashboard */
startActivity(new Intent(getApplicationContext(), DashBoardActivity.class));
}
/* Put here the login UI */
}
...
public void doLogin() {
/* ... check credentials and another stuff ... */
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("connected", true);
editor.commit();
}
In your DashBoardActivity
override the onBackPressed
method. This will take you from DashBoardActivity
to your home screen.
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
Hope it helps.
Solution 2
One idea is to initially launch the dashboard and then launch the login over it in a new Activity
if you detect that the user isn't logged in. You can then skip past the login dialog as needed. If you set noHistory="true"
on the login Activity
in your manifest, it will be prevented from reappearing on back pressed.
Solution 3
Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.
@Override
public void onBackPressed() {
moveTaskToBack(true);
super.onBackPressed();
}
SoldierCorp
Full-stack web and mobile developer Portfolio: https://edgardorl.com Youtube: http://youtube.com/SoldierCorp0
Updated on July 23, 2022Comments
-
SoldierCorp almost 2 years
I want create an app for my institute.
The problem is: my application will have two layouts (login and dashboard).
Students can correctly fill out the login form, enter the dashboard, press buttons, and fill other fields. But if the user then presses the back button, it should not return to the login screen, but remain in the dashboard, or failing that, exit the application.
Then if a student reopens the application and it's already logged, he should be automatically redirected to the dashboard, and not the login screen, unless the user press the logout button on the dashboard, then redirect him back to the login screen.
How could you do that?
Edit: I implemented 2 intents and 2 activities, and new questions arose me is that when I press the home button and from the taskmanager I open the app, open in the activity that was left, but if the open from the icon to open the app again from the first activity, as do to open in the last one was left?