android - Android Activity 的多个实例是否应该显示在内存分析器中?

标签 android memory-leaks android-activity

当我单击应用程序导航时,我发现每次启动新 Intent 时 Android 都会创建一个新的 Activity 实例(使用以下代码):

Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);

根据我所读到的内容,这似乎是默认行为。我猜测这意味着堆现在将分配多个实例来维护应用程序的历史记录。然而帕特里克·杜布罗伊在他的video on Memory management中说除非存在内存泄漏,否则只有一个 Activity 实例应该出现在堆转储中。

我的问题有两个:每次启动 Intent 时都会创建一个新的 Activity 实例,我这样说对吗?如果是这样,堆转储中出现多个实例是否表明存在内存泄漏?

更新 基于the Tasks and Back Stack guide :

Because the activities in the back stack are never rearranged, if your application allows users to start a particular activity from more than one activity, a new instance of that activity is created and pushed onto the stack (rather than bringing any previous instance of the activity to the top). As such, one activity in your application might be instantiated multiple times (even from different tasks)

最佳答案

如果在您的应用程序中,您正在执行以下操作:

Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);

然后,Android 确实会创建一个 HomeActivity 的新实例,并将其放在 Activity 堆栈的顶部。这将导致 HomeActivity多个实例。如果这不是您想要的(而且可能也不是您想要的),那么有几种可能的方法来处理这个问题。

由于我不了解您的应用程序并且您没有发布任何代码或任何内容,因此我需要做出一些假设。我假设您的 HomeActivity 是您用来启动应用程序的第一个 Activity (也称为根 Activity )。我还假设 HomeActivity 启动其他 Activity ,并且在启动其他 Activity 时不会自行调用 finish()

如果是这种情况,那么您可以通过执行以下操作从应用程序中的任何 Activity 返回到您的 HomeActivity:

Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

假设 HomeActivity 在 list 中没有android:launchMode="singleTop" 定义,这会导致该 Activity 中的所有 Activity堆栈(包括 HomeActivity)将完成,并将创建一个 HomeActivity 的新实例作为堆栈中的唯一 Activity。

如果您只想删除 现有 HomeActivity 实例之外的所有 Activity 并返回到该实例,您需要执行以下操作:

Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

这将导致 Activity 堆栈中的所有 Activity (除了HomeActivity)完成,并将调用 onNewIntent() ,然后调用 onResume() 在您现有的 HomeActivity 实例上。

如果我的假设不正确,请纠正我,我可以提出其他建议。

关于android - Android Activity 的多个实例是否应该显示在内存分析器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903669/

相关文章:

java - 如何在Range Seekbar中设置进度间隔

Android List<T> 等价物

Android 将事件添加到 CustomPreference 元素 (TextView)

java - Android读取文件编码问题

android - 内存泄漏和 OutOfMemoryError

c++ - 内存问题,不知道为什么。什么():std::bad_alloc

android - 在按钮上拖动 TextView - 应用程序崩溃

ios - methodSignatureForSelector 内存泄漏

android - 启动第三个 Activity 时崩溃

java - 如何获取Android操作系统中注册的所有 Activity ?