R.katiana
R.katiana

Reputation: 75

The Difference Between finish(); and onBackPressed();

What is the difference between (finish()) and (onBackPressed()) to end the activity Programmatically ???

I want to close the activity after a command (intent) Is it better to close it by command (finish) or using the command (onBackPressed)

Intent intent = new Intent ();
intent.putString("name", "Your Name");
 setResult(RESULT_OK,intent);
 onBackPressed();

or this better

Intent intent = new Intent ();
intent.putString("name", "Your Name");
setResult(RESULT_OK,intent);
finish();

Upvotes: 6

Views: 6596

Answers (3)

vincrichaud
vincrichaud

Reputation: 2208

The differences

According to the Activity documentation :

OnBackPressed

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

This method is triggered when the user press the back button. This method could be override to do special stuff when pressing this button. By default the implementation of this method call the finish method.

finish

Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult()

This method finish the activity. It's not specially called on a user event. When you want to close an activity call this method. This method is not supposed to be overriden.


In your case

You want to cause the app to finish so you have to use finish(). Use onBackPressed() if you want to simulate the user pressed the back button.

Upvotes: 6

GParekar
GParekar

Reputation: 1219

For closing activity use finish() method.

if user presses system back button onBackPressed() method invoked at that time.

Upvotes: 0

snachmsm
snachmsm

Reputation: 19223

onBackPressed() is calling finish() inside by default if you won't override this method. use finish() just because it is intended to close Activity, which action you want to achieve, no one clicked "physical" (or on screen) back button.

in future this might be helpfull - recognizing when user pressed button, maybe for some Toast or preventional Dialog?

Upvotes: 1

Related Questions