简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM