【问题标题】:How to delete file when application is closed应用程序关闭时如何删除文件
【发布时间】:2016-04-06 20:30:22
【问题描述】:

我想在我的应用关闭时删除一个文件。我在我的活动的onDestroy 方法中执行删除。但是当我检查文件是否被删除时,关闭应用程序后,文件仍然存在。

到目前为止,我的代码如下所示:

@Override
protected void onDestroy() {

    File file = new File(Environment.getExternalStorageDirectory().getPath(), "fileName.txt");
    if(file.exists()){
        file.delete();
    }

    super.onDestroy();
}

编辑:要求显示有关创建临时文件的代码的 sn-p:

try {
        file = File.createTempFile(Environment.getExternalStorageDirectory().getPath(), fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }

【问题讨论】:

标签: java android file ondestroy


【解决方案1】:

你不应该依赖onDestroy方法被调用(系统可以在生命周期到达这个阶段之前中断你的进程)。 我建议您使用临时文件夹来保存这样的文件,但您仍然有责任将临时文件的大小保持在合理的范围内(~1 mb)。


UPDATE(与临时文件 sn-p 相关)

您正在尝试提供 ExternalStorageDirectory 的完整路径作为文件名前缀。 但这种方法有点不同。 File.createTempFile 函数除了使用随机名称在特殊的临时文件目录中创建文件外,什么都不做。因此,我们仍然有责任提供一个临时文件夹,让系统知道该文件适合删除:

public File getTempFile(Context context, String url) {
    File file;
    try {
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName, null, context.getCacheDir());
    catch (IOException e) {
        // Error while creating file
    }
    return file;
}

cachedDir 是内部存储,这意味着其他应用无法在此处写入文件,因此您应该实现 FileProvider 以提供临时文件的 URI。

【讨论】:

  • 临时文件似乎很有希望,但是,我认为我不能使用临时文件,因为我将这些文件用作相机拍摄的照片service
  • 为什么你认为你不能?
  • 当相机服务将图像字节数组写入该文件时,我收到了一个空异常错误,该文件确实是作为临时文件创建的
  • 能否提供您的代码 sn-p 您正在创建文件的位置?
【解决方案2】:

我发现您创建文件的方式存在一些潜在问题,尤其是当您想删除它们时。您不妨以这种方式将文件存储在应用程序的本地缓存中。

// get the cache directory for our present `Activity`; 
// referred to by `context`
File directory = context.getCacheDir(); 

File file = File.createTempFile("prefix", "extension", directory);

[Docs] 这些文件对您的应用来说是私有的,如果设备存储空间不足,Android 可以删除它们。虽然你不应该依赖这个。

您可能想看看Android Activity Life-cycle。因此,如果您跟踪您在会话中创建的文件。在您的onDestroy() 中删除这些文件。我建议将此列表保存为SharedPref 或其他名称。原因? onDestroy() 并不是这个星球上最可靠的东西。如果您保存了文件,您可以在下次调用 onDestroy() 时将其删除(如果它们仍然存在)。

就个人而言,我可能不会为此使用onDestroy()。也许onStop() 更可靠。它是你的设计,你将是最好的评委。 :)

【讨论】:

    【解决方案3】:

    您可以尝试使用 Application 。您可以覆盖onTerminate() 来删除您的文件。

    【讨论】:

    • 来自docsThis method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多