Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: When to end class with finish()?

I often see examples of classes which end with finish(), but definitely not always. My question is when should you end a class with finish()? And what does it do exactly, what is the difference between ending a class with the back button and ending it with finish()?

Thanks in advance!

like image 618
Xander Avatar asked Oct 16 '12 10:10

Xander


People also ask

What is the use of finish () in android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

What happens when you call finish () inside onCreate ()?

Within this onCreate() method if we call finish() method then it will execute the whole onCreate() method first and then it will execute the lifecycle method onDestroy() and the Activity gets destroyed.

How do you check if activity is finished or not?

Using activity. isFinishing() is the right one solution. it return true if activity is finished so before creating dialog check for the condition. if true then create and show dialog.

Does finish call onPause?

Android will generally call onPause() if you call finish() at some point during your Activity's lifecycle unless you call finish() in your onCreate() .


1 Answers

finish() can be called to kill (destroy) an Activity instance. If you don't need to close your Activity manual, which is true in many cases, you don't need to call this method.

But if you require a button somewhere in your activity that says "close", then you should use this method. But in general the back button behavior in Android will handle things like this.

The back button does not actually finish your activity, finish() calls the onDestory() method right away, while the back button does not.

When the back button is pressed, the onStop() method is called, but the onDestory() method call might be delayed by the system, this so that the Activity can be resumed by the system which is cheaper (in resources) than a full restart.

Lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Finish(): http://developer.android.com/reference/android/app/Activity.html#finish()

like image 57
Rolf ツ Avatar answered Sep 24 '22 16:09

Rolf ツ