How to delete all temp files which created by crea

2020-06-03 01:05发布

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

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!

Code

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

标签: java android
7条回答
forever°为你锁心
2楼-- · 2020-06-03 01:47

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

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

        }
查看更多
登录 后发表回答