简体   繁体   English

为什么我的对象在此类中被垃圾回收

[英]Why are my objects garbage-collected in this class

I have a class that loads data from an API and stores/ handles the results as a POJO. 我有一个从API加载数据并以POJO形式存储/处理结果的类。 It looks roughly like this (some stuff omitted that doesn't concern the question): 看起来大致像这样(省略了一些与问题无关的内容):

public class ResultLoader {

    Search search;
    Result result;

    static ResultLoader instance;

    private ResultLoader() {

    }

    public static synchronized ResultLoader getInstance() {

        if (instance == null) {
            instance = new ResultLoader();
        }

        return instance;

    }

    public void init(@NonNull Search search) {
        this.search = search;
    }
}

The Result object can get so large that it becomes too large to be passed around Activities via Intents , so, as you can see, I designed the ResultLoader as a Singleton so every class can access the Result object. Result对象可能会变得很大,以至于它变得太大而无法通过IntentsActivities传递,因此,如您所见,我将ResultLoader设计为Singleton以便每个类都可以访问Result对象。

I simulate the Android device running low on memory by limiting background processes to one , then switch around some apps, go back to my app. 我通过将后台进程限制为一个来模拟Android设备的内存不足,然后切换一些应用程序,返回到我的应用程序。

On my ResultLoader 's instance, either the Result object became null or the instance was recreated; 在我的ResultLoader的实例上,Result对象变为null或重新创建了实例; i checked this with 我检查了这个

ResultLoader.getInstance().getResult() == null

How can this be and what can I do to prevent this? 怎么会这样,我怎么做才能防止这种情况?

Your objects GC'ed because android killed your app. 因为android杀死了您的应用,所以您的对象被GC了。 So it destroyed all loaded classes with static data. 因此,它使用静态数据销毁了所有已加载的类。 Next time when you get back to your app new app created and new ResultLoader class loaded with instance field equals null. 下次,当您回到您的应用程序时,将创建新的应用程序,并使用实例字段将新的ResultLoader类加载为null。 When you try to get instance via getInstance method new instance created with empty result. 当您尝试通过getInstance方法获取实例时,创建的新实例的结果为空。

You should save your Result to persistent memory. 您应该将结果保存到永久内存中。 Eg when you get result save it to a file. 例如,当您得到结果时,将其保存到文件中。 And when you create ResultLoader check that file exists and load data from a file. 并且当您创建ResultLoader时,请检查该文件是否存在并从文件中加载数据。 Or load result again if your app got killed. 或者,如果您的应用程序被杀死,则再次加载结果。

In android, your app can and will be recreated due to numerous reasons (low memory being one of them). 在android中,由于多种原因(低内存是其中之一),您可以并且将重新创建您的应用。

See this answer here to implement a saveinstancestate behavior on a custom class. 请参阅此处的答案以在自定义类上实现saveinstancestate行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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