Reputation: 5839
I am in details activity and I want to return to the home activity , what is the difference between pressing back button and calling finish method on details activity ?
Upvotes: 11
Views: 5974
Reputation: 4199
onBackPressed:
If you are defining onBackPressed() Method in your activity it means you are overriding the default behavior of backButton as onBackPressed() method gets called when you press back button.
If you have not Override onBackPressed() method from your Activity then, it will invoke finish() for your Activity. You don't need to call finish() explicitly. It will display Activity which is in the top of the Activity Stack and there is empty Stack then you will quite from the application. If you have Override onBackPressed() method then you have to call finish() explicitly to destroy activity.
Finish:
If you implement finish() method it intended to close current Activity. If your application don't have top backstack will redirect to android Home Screen. When calling finish() on an activity, the method onDestroy() is executed. This method can do things like:
Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed
Upvotes: 1
Reputation: 13415
If you have not Override onBackPressed()
method from your Activity
then, it will invoke finish()
for your Activity
. You don't need to call finish()
explicitly..
So by that it will display Activity
which is in the top of the Activity Stack
. And there is empty Stack
then you will quite from the application.
If you have Override onBackPressed()
method then You have to call finish()
explicitly to destroy activity.
Upvotes: 14
Reputation: 295
As I got both finish and back button destroy the activity. The only difference I found is that when you press back button it is invoke. onBackPress event
Upvotes: 2
Reputation: 234795
You can call finish()
from your code; you can't press the back button from code. Normally, pressing the back button results in a call to finish()
. The difference is whether you want your code or the user to initiate the action.
Upvotes: 3