gpt4 book ai didi

android - 在 Home 按下导致静态变量被销毁之前,系统是否有任何回调

转载 作者:行者123 更新时间:2023-11-29 01:53:04 25 4
gpt4 key购买 nike

我在Activity

中有如下一段代码
// Cache object is holding other resources like thread handle, file handle.
// Explicit clean up is required when it is no longer used.
public static Cache cache = new Cache();

@Override
public void onPause() {
super.onPause();

if (this.isFinishing()) {
cache.cleanUp();
}
}

请注意,我需要检查 isFinishing,因为手机旋转、按下主页、启动新 Activity ...也会触发 onPause。因此,由于这种“简单”操作而导致清理缓存违背了拥有 Cache 对象的目的。

但是,我的设计存在资源泄漏的可能。

  1. 运行应用
  2. 按主页
  3. 通过运行其他内存密集型应用程序来运行它们,按 Home,然后再次运行其他应用程序。
  4. 在某些时候,系统发现它应该删除我的应用程序,因为它已经有一段时间没有激活了。因此,cache 将变为空。 但是,我没有机会调用 cache.cleanUp
  5. 长按主屏幕按钮。我的应用仍应出现在列表中。
  6. 选择它。该 Activity 将再次 onCreate,并再次创建静态缓存的第 2 个实例。

在这种情况下,我们会发生资源泄漏,因为先前分配的旧线程句柄、第一个缓存对象拥有的文件句柄仍在系统中。我们无法对它们进行处理定位,因为第一个缓存对象已被系统销毁。

我希望每当系统因按下主页而决定销毁我的应用程序时,系统都会有一个回调。有了这样的回调,我可以在我的静态对象被销毁之前对它们执行必要的清理调用。

我可以知道如何实现吗?

最佳答案

In such case, we are having resource leak, as the previous allocated old thread handles, file handles owned by 1st cache object, are still in the system

GC 会处理它。这就是您的应用程序被杀死的原因。这样这些内存就会被清理并被其他应用程序使用。

关于android - 在 Home 按下导致静态变量被销毁之前,系统是否有任何回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16784238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com