我正在研究一个必须在整个活动中维护全局状态的android项目。为此,我正在成功扩展应用程序。然而,该项目的一个新要求是即使应用程序被android操作系统杀死也要保持状态,并且对于这个简单的扩展应用程序将是不够的,因为该对象将与应用程序一起被杀死。序列化扩展的对象应用程序
为了解决这个我已经实现Serializable接口来扩展应用对象:
public class AppState extends Application implements Serializable
,然后我写时的主要活动被破坏的对象私有存储:
@Override
public void onDestroy() {
super.onDestroy();
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
FileOutputStream fos = null;
// If there's a certificate creation in progress, let's store it more
// permanently before killing the app.
if (appState.getCertificate() != null) {
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(appState);
byte[] buf = bos.toByteArray();
fos = openFileOutput(Constants.objectStoreFileName, Context.MODE_PRIVATE);
fos.write(buf);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
然后我通过调用恢复对象:
private void getAppStateFromFile() {
FileInputStream fis = null;
ObjectInputStream ois = null;
ByteArrayOutputStream bos = null;
try {
fis = openFileInput(Constants.objectStoreFileName);
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
AppState appStateFromFile = (AppState) ois.readObject();
if (appStateFromFile != null) {
// restore values from appStateFromFile
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
deleteFile(Constants.objectStoreFileName);
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
它工作正常,但我g不知道有多少人使用过这种方法。我认为这很常见,因为我已经阅读了很多关于人们想要更长期地保存国家的信息。但对我的surprice googling“'扩展应用程序实现Serializable'android”返回0结果。由于某种原因,这不是推荐的方法吗?否则,它可以作为解决面临同样问题的其他人的解决方案。
lol不在应用程序上实现可序列化。取而代之的是让一个Singleton对象具有你想要的所有变量。然后你可以使这个序列化并使用它。 – Blundell
我大部分都很好奇,看它是否可以工作,因为我已经在使用Application,所以很容易就可以测试它。但后果是什么? – user909722
它不会工作.... – Blundell