Search code examples
javamobilelauncher

How to re-launch main activity after pressing back to go to home in Android


My project has 2 activities- First.java and Second.java

First.java is the launcher activity. I have manually set the onbackPressed() for Second.java so that when I press the back button from Second.java, it takes the user to home.

When I re-open the application, I am getting Second.java but I want First.java to be displayed again.

I have used this code to go to home:

@Override
public void onBackPressed()
{
    moveTaskToBack(true);
}

Solution

  • Assuming your Activity class is First.java and you're executing code in Second.java, this must do the trick:

    @Override
    public void onBackPressed()
    {
        Intent intent = new Intent(this, First.class);
        finish(); // to simulate "restart" of the activity.
        startActivity(intent);
    }
    

    Also you can check, Activity.recreate() if you're using API 11 and beyond.¡