在Android中退出应用程序时,如何删除createTempFile创建的所有临时文件? [英] How to delete all temp files which created by createTempFile when exit an App in android?
本文介绍了在Android中退出应用程序时,如何删除createTempFile创建的所有临时文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码创建一些临时文件,并将tem包裹为输入组以发送到客户端.
I use the following code to create some temp files, and wrapped tem as inputsteam to send to client side.
我了解到,当磁盘空间不足时,临时文件可以由android系统自动删除.
I understand that the temp files can be deleted automatically by android system when disk space low.
但是我希望退出应用程序时可以自己删除临时文件,该怎么办?谢谢!
But I hope to I can delete the temp files by myself when I exit the App, how can I do? Thanks!
代码
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);
推荐答案
如果 isChangingConfigurations()
为 false
则删除 onDestroy
中的文件 isFinishing
是 true
.示例:
Delete the files in onDestroy
if isChangingConfigurations()
is false
or isFinishing
is true
. Example:
@Override protected void onDestroy() {
super.onDestroy();
if(!isChangingConfigurations()) {
deleteTempFiles(getCacheDir());
}
}
private boolean deleteTempFiles(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
deleteTempFiles(f);
} else {
f.delete();
}
}
}
}
return file.delete();
}
这篇关于在Android中退出应用程序时,如何删除createTempFile创建的所有临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文