Android back to previous activities

I have two actions: MainActivity and NextActivity . From MainActivity I can go to NextActivity and then use Intent to return to MainActivity . But then OnCreate and other things will be called, and everything will look like everything is initialized again. I want to return to the state just as it was before I introduced NextActivity .

I realized that if I use the physical back button on my phone, this is achieved.

So how to return to activity as a back button?

PS. I tested finish() but didn't help.

+6
source share
2 answers

you can just call onBackPressed() instead of using Intent to return to MainActivity ..

For instance:

 public void onClick() { onBackPressed(); } 

Note: finish() should do exactly what you want.

+25
source

Suppose you have two operations A and B. You move from A to B. A goes to the background.

B is pushed onto the back stack, and B is focused. When you press the back button, activity B pops out of the back stack. Activity A resumes.

Note. Several tasks can be held in the background at once. However, if the user starts many background tasks at the same time, the system may begin to destroy background actions in order to restore memory, as a result of which the activity states will be lost. See the next section on activity status.

http://developer.android.com/training/basics/activity-lifecycle/starting.html Actions that have been destroyed must be recreated. Activity is destroyed and is recreated when the screen orientation changes.

http://developer.android.com/training/basics/activity-lifecycle/starting.html

http://developer.android.com/guide/components/tasks-and-back-stack.html You should see how the back stack works.

In your case, the finish should work for you (by clicking the "Back" button).

Note. The system calls onDestroy () after it has already called onPause () and onStop () in all situations except one: when you call finish () from the onCreate () method.

Suppose you have a third C action and want to go to Activity A.

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { onBackPressed(); } return super.onKeyDown(keyCode, event); } public void onBackPressed() { Intent myIntent = new Intent(ActivityC.this, MainActivity.class); myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack startActivity(myIntent); finish(); return; } 
+4
source

All Articles