android中的finish()与onDestroy()函数的区别

本文详细解析了Android中Activity的生命周期,特别是onDestroy()和finish()方法的区别与联系。通过阅读本文,开发者能够更好地理解如何正确地管理和释放Activity资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是我从官网找到的API解释,具体是在android.app.Activity包下

finish()

open fun finish(): Unit

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

onDestroy()

protected open fun onDestroy(): Unit

Perform any final cleanup before an 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. You can distinguish between these two scenarios with the isFinishing method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause or onSaveInstanceState, not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

If you override this method you must call through to the superclass implementation.

看到一大串英文应该头大吧,我来解释下。onDestroy()被调用:这可能是因为活动正在完成,也可能是因为系统临时销毁活动的此实例以节省空间。并且可以使用isFinishing方法来区分这两种情况。而finish()是当您的活动完成并应关闭时,请调用此选项。

所以onDestroy是俩种情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值