Search code examples
javaandroidandroid-ondestroy

Why cache data is not deleting on app destroy


When I try using the code bellow in the onDestroy() method in MainActivity it seams it does not work. What I am doing wrong?

Code:

@Override
protected void onDestroy() {
    super.onDestroy();
    deleteCacheData();
}

public void deleteCacheData() {
    File cacheDir = this.getCacheDir();
    File[] files = cacheDir.listFiles();

    if (files != null) {
        for (File file : files) {
            file.delete();
        }
    }
}

Solution

  • There is two cases with your code:

    1. You can't reliably depends on the case that onDestroy() method will be called. Because there is no such guarantee that it will always be called by the system. Here the excerpt from onDestroy() documentation:

      protected void onDestroy ()

      Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

      Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

      Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

    2. You should call your deleteCacheData() before calling the super.onDestroy(). So, this is incorrect:

      @Override
      protected void onDestroy() {
          super.onDestroy();
          deleteCacheData();
      }
      

      this is the correct one:

      @Override
      protected void onDestroy() {
          deleteCacheData();
          super.onDestroy();
      }