一开始我有扎实的Java知识,但是我才刚刚开始使用Android。
我的Android应用程序正在下载一些相当复杂的数据(文本、日期、图像),我将它们保存在一个自定义对象中。数据需要不时地刷新。但是,下载的数据通常不会更改。
为了将数据保存在内存中,我使用了Application对象。不幸的是,当应用程序被终止时,应用程序对象实例看起来被销毁了。
因此,我想知道在onPause()过程中序列化并将我的自定义对象(包含在应用程序对象中)保存在内部存储中是否是一种好的实践。显然,我会先从onResume()中读取文件,然后再从互联网上重新加载。这个想法也是为了实现离线查看。
从长远来看,计划是将下载日期的代码转移到后台服务中。由于在Android中似乎有许多不同的方法来保持应用程序状态,我想确定这是正确的方法。
发布于 2012-09-26 00:54:24
尝试使用这些方法类保存您需要的对象(实现序列化):
public synchronized boolean save(String fileName, Object objToSave)
{
try
{
// save to file
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
if (file.exists())
{
file.delete();
}
file.getParentFile().mkdirs();
file.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(objToSave);
oos.close();
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return false;
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
public synchronized Object load(String fileName)
{
try
{
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
if (!file.exists())
{
return null;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
savedObj = ois.readObject();
ois.close();
return savedObj;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}您需要对加载的对象进行强制转换()。CONTEXT是访问cachedir的Activity或ApplicationContext。您可以使用Environment.getExternalStorageState()来获取目录路径。别忘了加上"/filename“。
https://stackoverflow.com/questions/12587461
复制相似问题