【问题标题】:Clearing Cache in Nougat Programmatically not allowing以编程方式清除 Nougat 中的缓存不允许
【发布时间】:2018-07-30 06:33:57
【问题描述】:

我想在服务器上执行一些活动后清除我的应用程序的缓存。它在三星手机(Android 5.0)中运行良好,但在华为手机(Android 7)中没有清除缓存。 我认为 Nougat 没有授予该应用程序的权限。任何有关此问题的帮助将不胜感激。

缓存清除代码:

       public static void trimCache(Context context) {
         try {
        Toast.makeText(context,"hit on trim function 
        ",Toast.LENGTH_SHORT).show();
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            boolean check =deleteDir(dir);
            System.out.println("cache content check" +check);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}

public static boolean deleteDir(File dir) {
   Log.e("Mainactivity","Inside delete");
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        Log.e("Mainactivity","Inside delete if condition"+children);
        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();
}

在 Manifest 中添加了权限:

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

【问题讨论】:

标签: java android android-7.0-nougat


【解决方案1】:

我认为您的问题在@CommonsWare 回答here 中得到了很好的解释:

在 Android 6.0 之前,CLEAR_APP_CACHE 的保护级别为 很危险,所以普通的 SDK 应用程序可以在清单中请求它。

从 Android 6.0 开始,CLEAR_APP_CACHE 的保护级别为 签名|特权。普通的安卓应用无法容纳这个 允许。如果您的应用已签名,您只能持有此权限 使用固件的签名密钥,或者您安装在特权 系统分区。

【讨论】:

    【解决方案2】:

    对于两者,Android 6.0 以下和 Android 6.0 以上,这对我都有效:

    1. 声明 Manifest 权限:

      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
      
    2. 在你想清除缓存的地方声明这个方法:

      private static void deleteCache(Context context) {
          try {
              File dir = context.getCacheDir();
              deleteDir(dir);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      
      private static boolean deleteDir(File dir) {
          if (dir != null && dir.isDirectory()) {
              String[] children = dir.list();
              for (String aChildren : children) {
                  boolean success = deleteDir(new File(dir, aChildren));
                  if (!success) {
                      return false;
                  }
              }
              return dir.delete();
          } else if (dir != null && dir.isFile()) {
              return dir.delete();
          } else {
              return false;
          }
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2015-03-27
      相关资源
      最近更新 更多