java 在android中退出应用程序时如何删除由createTempFile创建的所有临时文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42464264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:39:54  来源:igfitidea点击:

How to delete all temp files which created by createTempFile when exit an App in android?

javaandroid

提问by HelloCW

I use the following code to create some temp files, and wrapped tem as inputsteam to send to client side.

我使用以下代码创建一些临时文件,并将 tem 包装为 inputteam 以发送到客户端。

I understand that the temp files can be deleted automatically by android system when disk space low.

我知道当磁盘空间不足时,android 系统可以自动删除临时文件。

But I hope to I can delete the temp files by myself when I exit the App, how can I do? Thanks!

但是我希望我可以在退出应用程序时自己删除临时文件,我该怎么办?谢谢!

Code

代码

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

采纳答案by Jared Rummler

Delete the files in onDestroyif isChangingConfigurations()is falseor isFinishingis true. Example:

删除onDestroyif isChangingConfigurations()isfalseisFinishingis 中的文件true。例子:

@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();
}

回答by Atef Hares

call the deleteOnExit()method!

调用deleteOnExit()方法!

Or

或者

call the delete()method in the onStop()of your activity.

delete()onStop()您的活动中调用该方法。

Edit:

编辑:

It might be better if you called delete()in onDestroy()to insure that your code works even if app is destroyed by system.

如果你叫这可能是更好delete()onDestroy(),以确保您的代码的工作,即使应用程序是由系统破坏。

回答by Sridhar

It would be better if you can maintain a Set (Avoid Duplicates) for all files you create.

如果您可以为您创建的所有文件维护一个集合(避免重复)会更好。

And iterate the file list and delete every file one by one.

并迭代文件列表,将每个文件一一删除。

 public static final Set<String> TMP_FILES = new HashSet<>();

And delete all by iterating.

并通过迭代删除所有内容。

public void deleteTempFiles() {
  for(String myTempFile: TMP_FILES) {
    try {
      new File(myTempFile).delete();
    } catch (Exception e) {
      // Handle if needed.
    }
  }
}

回答by Luís Gon?alves

Unfortunately it appears you have to delete these files one by one, by previously saving them in an array.

不幸的是,您似乎必须通过先前将它们保存在数组中来一个一个地删除这些文件。

That being said, if you check Android Developers pageon this issue it makes it as if you could delete the cached files "on a regular basis and also regularly delete other files you no longer need". However I don't think there is an explanation on how to do it.

话虽如此,如果您查看有关此问题的Android 开发人员页面,就会发现您可以“定期删除缓存文件并定期删除您不再需要的其他文件”。但是,我认为没有关于如何做到这一点的解释。

回答by Doilio Matsinhe

Try Using WorkManager to make sure it cleans up the temp files even after the app is closed.

尝试使用 WorkManager 确保即使在应用程序关闭后它也会清理临时文件。

    override fun doWork(): Result {

            return try {
                applicationContext.cacheDir?.let {
                    if(it.exists()){
                        val entries = it.listFiles()
                        if (entries != null){
                            for (entry in entries) {
                                Timber.i("My file: ${entry.name}")
                                entry.delete()
                            }
                        }
                    }
                }
                Result.success()
            } catch (e: Exception) {
                Timber.e(e)
                Result.failure()
            }

        }

回答by HazeyAce

I ended up here looking for a way to remove temp files that I was creating for camera intents, I actually used a combination of Sridhar'sanswer and the cleanOldFilesfunction from this answer

我最终在这里寻找一种方法来删除我为相机意图创建的临时文件,我实际上结合使用了Sridhar 的答案和此答案中cleanOldFiles功能

I was creating a new image file using createTempFileand then adding that to

我正在创建一个新的图像文件createTempFile,然后将其添加到

public static final HashSet<File> TEMP_FILES = new HashSet<>();

public static final HashSet<File> TEMP_FILES = new HashSet<>();

To iterate and remove from the set using the normal foreach loop was throwing a java.util.ConcurrentModificationExceptionso I updated the loop using an Iterator

使用正常的 foreach 循环迭代并从集合中删除会抛出一个,java.util.ConcurrentModificationException所以我使用一个Iterator

more on iterators

更多关于迭代器

Thought I'd post in case it helps someone else, thanks to Sridhar and ggrandes from the other post for the help.

我想我会发布以防它帮助其他人,感谢来自其他帖子的 Sridhar 和 ggrandes 的帮助。

public synchronized void cleanTempFiles(final int secondsOld) {
    long now = (System.currentTimeMillis() / 1000);
    for (Iterator<File> iterator = TEMP_FILES.iterator(); iterator.hasNext(); ) {
        File f = iterator.next();
        long expired = (f.lastModified() / 1000) + secondsOld;
        if (now >= expired) {
            Log.d(TAG, "Deleted file - \"" + f.getAbsolutePath() +"\"");
            f.delete();
            iterator.remove();
        }
    }
}

The function removes files older than a given time value in seconds and is called like

该函数以秒为单位删除早于给定时间值的文件,并被调用

cleanTempFiles(3); // or however long

回答by EJoshuaS - Reinstate Monica

First, keep in mind that "exit" for an Android app means something very different than it does for a desktop application. See this articlefor details, but the short answer is that, in general, you have no ideawhen the OS is actually going to close your app (even if it's not visible). In fact, there isn't an explicit guarantee that the OS will close it at all.

首先,请记住,Android 应用程序的“退出”与桌面应用程序的含义非常不同。有关详细信息,请参阅这篇文章,但简短的回答是,一般而言,您不知道操作系统何时真正关闭您的应用程序(即使它不可见)。事实上,没有明确保证操作系统会关闭它。

A few ideas can be found here (it's C#/Xamarin.Android but same exact idea for Java): How to detect application exit on android?

可以在这里找到一些想法(它是 C#/Xamarin.Android,但与 Java 完全相同):How todetection application exit on android?

In addition to the stuff listed there, you could also try registering broadcast receivers for when the phone's shutting down.

除了此处列出的内容之外,您还可以尝试在手机关机时注册广播接收器。

Another (worse, in my opinion) way is to simply do this when the app becomes no longer visible (in onStop). As noted above, however, this isn't the same thing as the program actually closing (because you don't know when - or even if - the OS will actually close the app).

另一种(更糟糕的是,在我看来)方法是在应用程序不再可见(在 中onStop)时简单地执行此操作。然而,如上所述,这与程序实际关闭不同(因为您不知道操作系统何时 - 甚至是否 - 实际关闭应用程序)。