gpt4 book ai didi

android - 在内存中的何处存储持久(直到重启)数据?

转载 作者:行者123 更新时间:2023-11-29 21:46:28 26 4
gpt4 key购买 nike

目前,我将数据存储在我的 Application 类的静态属性中。当应用程序关闭时,数据仍然存在,但是当应用程序从最近的菜单中清除(或缓存的进程被终止)时,Application 类似乎也从内存中删除。

我需要可以从 Activity/fragment 以及 BroadcastReceiver 轻松访问数据。启动 MainActivity 时首先加载数据。你可以在 my GitHub project 查看我的代码.

更新

我正在使用 SQLite 存储数据, Activity 在启动时将数据加载到内存中。不过,我认为我无法通过 BroadcastReceiver 执行此操作,因为它们的生命周期有限,而且 SQLite 可能会长期运行。主要问题是我需要我的 BroadcastReceiver 能够像 Activity 一样操作相同的数据。

最佳答案

另一种有趣的可能性是将数据存储为 xml 文件。您可以使用它,例如简单的 XML 库:http://simple.sourceforge.net/

首先你应该在模型类中做注解,

@Root
public class Example {

@Element
private String text;

@Attribute
private int index;

public Example() {
super();
}

public Example(String text, int index) {
this.text = text;
this.index = index;
}

public String getMessage() {
return text;
}

public int getId() {
return index;
}
}

然后你可以保存这些对象:

 Serializer serializer = new Persister();
Example example = new Example("Example message", 123);
File result = new File("example.xml");

serializer.write(example, result);

要再次获取此文件,应该这样做:

Serializer serializer = new Persister();
File source = new File("example.xml");

Example example = serializer.read(Example.class, source);

这是从项目站点获取的最简单示例之一,但可以编写嵌套对象和列表。它也有很好的记录

关于android - 在内存中的何处存储持久(直到重启)数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686766/

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