为什么缓存数据不会在应用程序销毁时删除

Why cache data is not deleting on app destroy

当我尝试在 MainActivity 的 onDestroy() 方法中使用下面的代码时,它接缝它不起作用。我做错了什么?

代码:

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

如果您使用 Windows OS 因为在你的 Windows 任务管理器中,当 android studio 启动或构建 运行 或停止名为

Java Jmt先停止然后你可以直接删除两个构建文件夹不需要清除缓存

你的代码有两种情况:

  1. 你不能可靠地取决于 onDestroy() 方法将被调用的情况。因为没有这样的保证它会一直被系统调用。这里摘自 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. 您应该在调用 super.onDestroy() 之前调用您的 deleteCacheData()。所以,这是不正确的:

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

    这是正确的:

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