Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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();
like image 502
R.katiana Avatar asked Apr 26 '18 14:04

R.katiana


People also ask

What does Super onBackPressed () do?

All callbacks registered via addCallback are evaluated when you call super. onBackPressed() . In Android 12 (API level 32) and lower, onBackPressed is always called, regardless of any registered instances of OnBackPressedCallback .

Does fragment have onBackPressed?

2- All the fragments willing to intercept the BackPress event had to implement the interface above which caused them having the onBackPressed() function call. Now the fragment can respond to BackPress events and do something and based on if the event was consumed or not they can return true or false.


2 Answers

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.

like image 62
vincrichaud Avatar answered Oct 15 '22 09:10

vincrichaud


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?

like image 33
snachmsm Avatar answered Oct 15 '22 11:10

snachmsm