猿问

以编程方式清除 Nougat 中的缓存不允许

我想在服务器上执行一些活动后清除我的应用程序的缓存。它在三星手机(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();

}

在清单中添加权限:


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

  tools:ignore="ProtectedPermissions"/>


HUX布斯
浏览 120回答 2
2回答

慕森王

对于低于 Android 6.0 和高于 Android 6.0 的两者,这对我有用:声明清单权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>从要清除缓存的位置声明此方法:private static void deleteCache(Context context) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; File dir = context.getCacheDir();&nbsp; &nbsp; &nbsp; &nbsp; deleteDir(dir);&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }}private static boolean deleteDir(File dir) {&nbsp; &nbsp; if (dir != null && dir.isDirectory()) {&nbsp; &nbsp; &nbsp; &nbsp; String[] children = dir.list();&nbsp; &nbsp; &nbsp; &nbsp; for (String aChildren : children) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boolean success = deleteDir(new File(dir, aChildren));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!success) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return dir.delete();&nbsp; &nbsp; } else if (dir != null && dir.isFile()) {&nbsp; &nbsp; &nbsp; &nbsp; return dir.delete();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}

慕森卡

我觉得你的问题是在 Android 6.0 之前,CLEAR_APP_CACHE 的保护级别为危险,因此普通 SDK 应用程序可以在清单中请求它。从 Android 6.0 开始,CLEAR_APP_CACHE 的保护级别为签名|特权。普通 Android 应用无法持有此权限。只有当您的应用程序使用固件的签名密钥进行签名或者您安装在特权系统分区上时,您才能拥有此权限。
随时随地看视频慕课网APP

相关分类

Java
我要回答