当主屏幕小部件 运行 时,数据对象的静态数组列表会导致内存泄漏吗

Can a static arraylist of data objects cause memory leaks while the homescreen widget is running

在下面的代码中,我有一个包含一堆变量的 Class。我创建了几个 class 的实例并将它们保存到数组列表中。 arraylist 是相同 class 的一部分,但标记为静态。 同一个应用程序有一个主屏幕应用程序小部件。 我担心静态数组列表将永远保留在内存中,直到用户删除应用程序小部件。这是真的? 静态数组列表是个好主意还是其他选择?

public class Data {
    public static ArrayList<Data> listData = new ArrayList<Data>();
    String string;
    int integer;
    Data(String string, int integer){
        this.string = string;
        this.integer = integer;
    }
}

public class DataChanger {
    DataChanger(){
        Data.listData.add(new Data("string", 1));
    }
}

static arraylist will stay in memory forever until the user deletes the app widget

这不太可能发生,因为 AppWidgetProvider BroadcastReceiver class Android 小部件很方便。如果您的应用程序没有其他内容 运行,您的进程可能会在 onUpdate() 次调用之间终止。

BroadcastReceiver 的官方文档非常清楚

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

参考文献 - Reference 1, Reference 2, Reference 3