Search code examples
javaandroidcachingtemporary-filestemp

Android Memory -- Temporary Files in Cache or Put on Disk, Delete When Done


I am writing an app which records and plays audio using a temporary file on the device and longer-term storage on the cloud, so it only needs to be available on the physical device when directly in use.

It allows the user to record and review a recording, then either delete it or upload it to the backend and then delete it from the phone. Later, the user then downloads the file from the backend server, listens to it, and it should be deleted off the phone.

These recordings may be up to 10-15 minutes long, so they can get fairly large.

I made the program work two different ways, but I'm not sure which one properly manages the memory and cache. The first by calling a temporary cache file with the following code:

    String fileName = UUID.randomUUID().toString().replaceAll("-", "");
    File tempFileDir = this.getCacheDir();
    File tempFile = File.createTempFile(fileName, ".3gp", tempFileDir);

This file is used but never directly deleted.

The other option is by saving a non-cache file to memory and then deleting it when no longer needed:

if (Utils.isExternalStorageWritable()) {

   String fileName = getRandomFileName();
   String outputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
   outputFile += "/" + fileName + ".3gp";

   //outputFile used in MediaRecorder to record sound file, etc.
   //once file is to be deleted:

    File file = new File(outputFile);
    boolean isDeleteSuccessful = file.delete();
    }

Is it better to do the second option so that I don't run into memory issues in the cache?


Solution

  • Thanks to the comments by Gusman I used the first approach to create a temporary file and included code to clean up the local files once they are loaded onto the backend server or in the event the user closes the app without uploading the recording (onDestroy()).

    Is it programmer responsibility to delete temp file