6

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();
1
  • 1
    Did you make the effort to read the doc ? Commented Apr 26, 2018 at 15:09

3 Answers 3

6

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.

1

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?

0

For closing activity use finish() method.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.