2017-03-01 93 views
0

我需要清除应用程序的缓存而不强制关闭应用程序。我需要应用才能继续运行。我正在使用espresso来测试应用程序,但我需要在应用程序启动之前清除缓存。有没有办法做到这一点?清除应用程序的缓存而无需强制关闭应用程序

public static void clearPreferences(Activity activity) { 
    try { 
     // clearing app data 
     String packageName = activity.getPackageName(); 
     Runtime runtime = Runtime.getRuntime(); 
     runtime.exec("pm clear "+packageName); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

这就是我。但它关闭应用程序并终止测试案例

+0

删除所有文件在'getCacheDir()',使用普通的Java I/O类,比如'File'。 – CommonsWare

+0

检查此链接。 http://stackoverflow.com/questions/23908189/clear-cache-in-android-application-programmatically –

回答

0

请检查此链接下面的帮助给你。

http://stackoverflow.com/questions/23908189/clear-cache-in-android-application-programmatically 


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

添加权限在menifest