2017-03-01 96 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