Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How avoid returning to login layout pressing the back button/key?

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?

like image 982
SoldierCorp Avatar asked Apr 20 '12 20:04

SoldierCorp


3 Answers

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.

like image 122
Marcos Avatar answered Oct 21 '22 10:10

Marcos


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.

like image 43
Jon O Avatar answered Oct 21 '22 12:10

Jon O


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();
}
like image 28
Li3ro Avatar answered Oct 21 '22 10:10

Li3ro