-2

I want if click on press back button, checking if previous exists

I dont use put extra

public void onBackPressed() {
    super.onBackPressed();
    if (//Have activity){
        // Go to home
    } else {
        // Go to register
    }
} 
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
My Name
  • 285
  • 1
  • 4
  • 18
  • 1
    This would be help you [Gett activity stack](http://stackoverflow.com/questions/5975811/how-to-check-if-an-activity-is-the-last-one-in-the-activity-stack-for-an-applica?answertab=active#tab-top) – Prameshwar May 02 '17 at 07:55
  • 3
    Does this answer your question? [How to check if an activity is the last one in the activity stack for an application?](https://stackoverflow.com/questions/5975811/how-to-check-if-an-activity-is-the-last-one-in-the-activity-stack-for-an-applica) – Sk Suraj Aug 14 '20 at 07:47

3 Answers3

4

You can check this method:

if (!isTaskRoot()) {
    super.onBackPressed();//or finish()
} else {
    Intent intent = new Intent(Main2Activity.this, MainActivity.class);
    startActivity(intent);
    finish();
}
Nicat
  • 194
  • 4
  • 12
1

I use this code an work correct :

if (isTaskRoot()) { // do something }
My Name
  • 285
  • 1
  • 4
  • 18
0
        // isTaskRoot() returns 'true' if this is the root activity, else 'false'.
        
        /* If it returns 'true' this means the current activity is the root activity of your 
         application right now & no activity exist on the back stack, if you press back at 
         this moment your app will be closed. But now you can handle the back press by checking 
         is the current activity a root activity or not like below */
        
        if(isTaskRoot()) {
            // Start an activity or do whatever you want
        } else {
            super.onBackPressed();
        }
Sk Suraj
  • 500
  • 2
  • 15