【问题标题】:How to clear application cache programatically in Marshmallow如何在 Marshmallow 中以编程方式清除应用程序缓存
【发布时间】:2016-10-12 05:24:37
【问题描述】:

我想在 Android Marshmallow 6.0 中以编程方式清除我的应用程序缓存。我尝试了以下代码,但它在 Marshmallow 中不起作用。我在堆栈溢出中读到,API 级别 19 已弃用以下代码。我在 Manifests.xml 中添加了 CLEAR_APP_CACHE 权限

 public  void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

 public  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;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

【问题讨论】:

  • 怎么不工作了?你的应用程序崩溃了吗?请详细说明,以便人们更好地帮助您。
  • @HadiSatrio 感谢您的回复。我在 Android Studio 的 Monitors 选项卡中看到过。它不会释放内存。而且它还会使我的应用程序因内存不足的错误而崩溃。我没有存储卡,我的手机里只有 500mb 的可用内存。
  • 我也面临同样的问题。如果有人解决了请帮忙。谢谢

标签: android performance android-studio


【解决方案1】:

在您的清单中添加以下权限:

<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />

您还应该检查外部缓存目录。

public  void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
            File exDir = context.getExternalCacheDir();
            if (exDir != null && exDir.isDirectory()) {
                deleteDir(exDir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

【讨论】:

  • 我忘了添加我的问题,但我已经添加了权限。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
相关资源
最近更新 更多