简体   繁体   中英

Why should we call finish() method after sending an intent?

I just came across this code in

Intent wizard = new Intent();
wizard.setClass(this, A.class);
wizard.putExtra("Domain", A.getInstance().B);
startActivity(wizard);
finish();

Why should we call finish() method here? What's it purpose?

finish() Call this when your activity is done and should be closed, when starting an activity calling finish() will close the current activity and it will not be available in the Activity Stack.

在此处输入图片说明

finish(); 

finish用于关闭当前活动。就像您正在将数据发送到其他活动/打开新活动并关闭当前活动一样。

You are not imperative forced to do that... normally people do that if and only if the want to destroy the activity that is starting the intent, but that must no be your case...

in the life cycle of android you will see:

assuming you activity is visible, then calling finish() method will call

onPause() , then onStop() and finally the onDestroy()

在此处输入图片说明

Let's understand it using few quotes

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


onDestroy() - The final call you receive before your activity is destroyed. This can happen either because the activity is finishing ( someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space.

when you call finish() on an activity, the methods followed by onDestroy() is executed.. eg: onPause() > onStop() > and onDestroy() they can be differ from the place you call finish() !

onDestroy() is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.

It inform the system that you want to finish the selected Activity so it wil call onDestroy() after you finish the activity.( but this does not mean that onDestroy() only gets called by finish(),system can do that when it's running out of resources after the activity is sent to the back state )

Also there are more interesting questions like Activity.finish() called but activity stays loaded in memory that you might like

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM