-1

I'm trying to build a simple login & registration application in android. My problem is that I want to handle backpressed() but it is not working.

Example: I'm having 3 activities: signin, register and verify. What I need is if we back click on register or verify, the navigation should go to signin and if we back click on signin, the application should close.

I have tried these lines of code but they are not working. They will navigate to previously visited activity. This code is of signin activity

@Override
public void onBackPressed() {
    Intent i = new Intent();
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    finish();
}

This code is of register activity

@Override
public void onBackPressed() {
    Intent i = new Intent(getBaseContext(), LoginActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
}
Suraj Makhija
  • 1,376
  • 8
  • 16
Isurendrasingh
  • 432
  • 7
  • 20

4 Answers4

0

If you're building for API>16

@Override
public void onBackPressed(){
  finishAffinity();
  super.onBackPressed();
}
0

What I need is that if we back click on register or verify, the navigation should go to signin and if we back click on signin, the application should close.

To go to SignInActivity onBackpressd() from Verify and RegisterActivity:

@Override
public void onBackPressed() {
    Intent i = new Intent(this, SignInActivity.class);
    finishAffinity();
    startActivity(i);
}

In SignInActivity:

@Override
    public void onBackPressed() {
        finish();            
    }

Hope this helps.

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
0

This works for sure!!

   @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finishAffinity();
        System.exit(0);


    }
0

Finish will always go to the previous activity on the stack. The intent flags need to be set when your activity is LAUNCHED, not when your activity is being killed.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127