在Android中启动新的Activity后,调用finish()是一个好主意吗? [英] Is it a good idea to call finish() after starting a new Activity in Android?

查看:840
本文介绍了在Android中启动新的Activity后,调用finish()是一个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

赞:

startActivity(intent);
finish();

不调用finish() explicitly, onDestroy()不会被以前的Activity调用,并且我的内存(OutOfMemory Exception).

Without calling finish() explicitly, onDestroy() is not called for the former Activity, and I run out of memory (OutOfMemory Exception).

所以,打电话给finish() explicitly to prevent OutOfMemory Exception?

推荐答案

开始新活动时,当前活动将被推入当前任务的后堆栈. (您可以通过标志和/或清单更改此行为,但这是默认行为.)当用户按下后退功能时,顶部活动结束,并且弹出堆栈.结果是用户看到该应用程序返回到上一个活动.

When you start a new activity, the current activity is pushed onto the back stack of the current task. (You can change this behavior via flags and/or the manifest, but this is the default behavior.) When the user presses the back function, the top activity is finished and the stack is popped. The result is that the user sees the app return to the previous activity.

在开始新活动后调用finish()是完全可以的.结果是当前活动(不再是堆栈的顶部,因为您刚刚开始一个新活动)将被从堆栈中删除.然后,当用户按下Back(返回)时,它将转到后退堆栈上的上一个活动(如果堆栈为空,则退出您的应用程序).

It's perfectly fine to call finish() after starting a new activity. The result will be that the current activity (which is no longer at the top of the stack, since you just started a new one) will be removed from the stack. Then when the user presses Back, it will go to the previous activity on the back stack (or exit your app if the stack is empty).

例如,如果您通过始终启动一个新活动而从不调用finish()来在活动A和活动B之间来回跳动,则可能会导致OOM异常,因为堆栈中充满了每个活动的实例.

If you are bouncing back and forth between, say, activities A and B by always starting a new one and never calling finish(), this can cause an OOM exception as the stack fills up with instances of each activity.

您可以在指南主题任务和后退堆栈.它还描述了如何正确处理活动之间的循环.

You can read more about this in the guide topic Tasks and Back Stack. It also describes how to deal correctly with cycling between activities.

这篇关于在Android中启动新的Activity后,调用finish()是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆