Search code examples
javaandroidback-buttononbackpressed

Android backpressed not working


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);
}

Solution

  • 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.