【问题标题】:Clear Cache in Android Application programmatically以编程方式清除 Android 应用程序中的缓存
【发布时间】:2014-05-28 09:47:42
【问题描述】:

以编程方式清除 android 应用程序中的缓存的正确方法是什么。我已经在使用以下代码,但它看起来不适合我

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

【问题讨论】:

  • 还要检查 getExternalCacheDir()
  • @for3st 我们可以只为 webview 清除缓存吗?
  • WebView.clearCache(boolean includeDiskFiles) 将清除应用程序中所有 webvie 的缓存
  • @RizwanAhmed 你找到解决上述问题的方法了吗

标签: android


【解决方案1】:

如果您正在寻找自己应用程序的删除缓存,那么只需删除您的缓存目录即可!

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) { e.printStackTrace();}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
        return dir.delete();
    } else if(dir!= null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}

【讨论】:

  • 在您要删除应用程序缓存的那个操作上。可以在 OnDestroy 或您的应用程序中的某个地方执行此操作
  • 此代码从不删除文件。当 dir.isDirectory() == false 它只返回 false。由于您无法删除非空目录,因此这是行不通的。你应该添加一个 else:if (dir != null &amp;&amp; dir.isDirectory()) { ... }else if(dir.isFile()) { return dir.delete(); }
  • @dhams 这种方法是否也会清除我的共享偏好数据?因为我想保留它并只清除缓存中的图像!!!
  • @Saty: 不,这不会清除共享偏好
  • 他们在文档中写道,我们不需要额外的权限来执行此操作。 “应用程序不需要额外的权限来读取或写入返回的路径,因为该路径存在于它们的私有存储中。” developer.android.com/reference/android/content/…
【解决方案2】:

Kotlin 有一个单行代码

context.cacheDir.deleteRecursively()

【讨论】:

  • 完美答案,这在 Java 中也应该可用: context.getCacheDir().deleteRecursively()
【解决方案3】:

来自 dhams 的答案是正确的(经过多次编辑),但是正如对代码的多次编辑所显示的那样,很难编写正确且健壮的代码来自己删除目录(带有子目录)。所以我强烈建议使用Apache Commons IO,或者其他可以为你做这件事的API:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS:如果你使用 context.getExternalCacheDir() 返回的目录,也要删除它。

为了能够使用 Apache Commons IO,请将其添加到您的 build.gradle 文件中的 dependencies 部分:

compile 'commons-io:commons-io:2.4'

【讨论】:

  • gradle 文件中的编译行现在将是implementation 'commons-io:commons-io:2.5'。我首先尝试了 2.6,但出现了一些错误,例如 noSuchMethodException,所以现在请使用 2.5 版本。最新版本在这里:mvnrepository.com/artifact/commons-io/commons-io
【解决方案4】:

我认为您应该将clearApplicationData() 放在super.OnDestroy(). 之前

您的应用在关闭后无法处理任何方法。

【讨论】:

【解决方案5】:

试试这个

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

【讨论】:

  • 我怎样才能使用你的代码并只删除 shared_prefs 缓存?你能帮我吗...
【解决方案6】:

如果你使用的是 kotlin,那么:

context.cacheDir.deleteRecursively()

【讨论】:

    【解决方案7】:

    如果您使用的是 Android Studio 4.4.2

    getCacheDir().delete();
    

    【讨论】:

      【解决方案8】:

      我不确定,但我也播下了这段代码。 这条鳕鱼会更快,在我看来它也很简单。 只需获取您的应用程序缓存目录并删除目录中的所有文件

      public boolean clearCache() {
          try {
      
              // create an array object of File type for referencing of cache files   
              File[] files = getBaseContext().getCacheDir().listFiles();
      
              // use a for etch loop to delete files one by one
              for (File file : files) {
      
                   /* you can use just [ file.delete() ] function of class File
                    * or use if for being sure if file deleted
                    * here if file dose not delete returns false and condition will
                    * will be true and it ends operation of function by return 
                    * false then we will find that all files are not delete
                    */
                   if (!file.delete()) {
                       return false;         // not success
                   }
              }
      
              // if for loop completes and process not ended it returns true   
              return true;      // success of deleting files
      
          } catch (Exception e) {}
      
          // try stops deleting cache files
          return false;       // not success 
      }
      

      通过getBaseContext().getCacheDir().listFiles()获取File数组中的所有缓存文件 然后通过file.delet()方法循环一个一个地删除

      【讨论】:

      • 不鼓励仅使用代码的答案,因为它们没有说明如何解决问题。请更新您的答案,以解释这如何改进该问题已有的其他已接受和赞成的答案,并删除代码中无效文本的多个实例(“在此处输入代码”)。请查看How do I write a good answer
      【解决方案9】:

      将此代码放入MainActivityonStop()方法中

      @Override
      protected void onStop() {
          super.onStop();
          AppUtils.deleteCache(getApplicationContext());
      }
      
      public class AppUtils {
          public static void deleteCache(Context context) {
              try {
                  File dir = context.getCacheDir();
                  deleteDir(dir);
              } catch (Exception e) {}
          }
      
          public static boolean deleteDir(File dir) {
              if (dir != null && dir.isDirectory()) {
                  String[] children = dir.list();
                  for (int i = 0; i < children.length; i++) {
                      boolean success = deleteDir(new File(dir, children[i]));
                      if (!success) {
                          return false;
                      }
                  }
                  return dir.delete();
              } else if(dir!= null && dir.isFile()) {
                  return dir.delete();
              } else {
                  return false;
              }
          }
      }
      

      【讨论】:

        【解决方案10】:

        使用 kotlin: 来删除内容:

        for (file:File in context?.cacheDir?.listFiles()!!){
                     file.delete()
                 }
        

        【讨论】:

          【解决方案11】:

          这段代码帮助了我:

          // your code
          deleteCache(getContext);
          //
          
          public void deleteCache(Context context) {
              try {
                  File dir = context.getCacheDir();
                  if (dir.list() != null) {
                      deleteDir2(dir);
                  }
              } catch (Exception e) { e.printStackTrace();}
          }
          
          public boolean deleteDir2(File dir) {
              if (dir.isDirectory()) {
                  for (File child : dir.listFiles()) {
                      boolean success = deleteDir2(child);
                      if (!success) {
                          return false;
                      }
                  }
              }
              return dir.delete();
          }
          

          【讨论】:

          • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
          【解决方案12】:

          此代码将删除应用程序的整个缓存,您可以检查应用程序设置并打开应用程序信息并检查缓存大小。使用此代码后,您的缓存大小将为 0KB 。所以它并享受干净的缓存。

           if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
                      ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                              .clearApplicationUserData();
                      return;
                  }
          

          【讨论】:

          • 我认为这也会清除数据,而不仅仅是缓存。
          • 这也会删除应用数据,而不是只清除缓存。这个 clearApplicationUserData() api 不应该仅仅用于清除缓存。
          猜你喜欢
          • 1970-01-01
          • 2015-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多