Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restart activity on back button pressed?

I'm going from main activity to another activity and then when I press back button I want to go back to the main activity and restart it. How can I do that?

like image 537
Wolf87 Avatar asked Nov 29 '22 03:11

Wolf87


2 Answers

You could just override the onBackButton pressed in your second activity to start the first one. Example:

@Override
public void onBackPressed() {
    startActivity(new Intent(this, FirstActivity.class));
}
like image 135
Dan Avatar answered Dec 01 '22 16:12

Dan


When you press the back button while in the second activity, then Android automatically invokes the previous activity on the back stack, which is in your case your main activity.

For more information, see the Android docs for Tasks and Back Stack.

Android calls the onResume() callback every time you return to an activity with the back button. Do all your "restart" work there.

like image 39
dermatthias Avatar answered Dec 01 '22 16:12

dermatthias