before I used getExternalCacheDir() to get ext cache dir path for cache images, but sometime I clicked "Clear data" from Setting-AppInfo,then getExternalCacheDir() return null, because all package folders were removed from "Android/data ",So I think I can generate it first ,but I tried some ways I cant do this successfully, can anyone teach me how to do ? why I cant create this directory? and in this case, how to do will be more elegant solution?
thanks!
public static String getAppCacheStorageDir(Context context,String folder) {
// http://stackoverflow.com/questions/10123812/diff-between-getexternalfilesdir-and-getexternalstoragedirectory
// http://stackoverflow.com/questions/16562165/getexternalcachedir-returns-null-after-clearing-data
// final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?
// context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();
//// return cachePath + File.separator + context.getPackageName()+ File.separator +folder;
// return cachePath + File.separator +folder;
boolean isExtStorageMounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?
true: false;
if(isExtStorageMounted){
if(checkOrRebaseAppExtCacheDir(context)){
return context.getExternalCacheDir().getPath()+ File.separator +folder;
}else{
return context.getCacheDir().getPath() + File.separator +folder;
}
}
return context.getCacheDir().getPath() + File.separator +folder;
}
public static boolean checkOrRebaseAppExtCacheDir(Context context){
String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?
Environment.getExternalStorageDirectory().getPath()
+File.separator+"Android"
+File.separator+"data"
+File.separator+context.getPackageName()
+File.separator+"cache"
:
null;
if(cachePath!=null){
File file = new File(cachePath);
if (!file.exists()) {
getPermissionForAppExtCacheDir(context);
return file.mkdirs();
}else{ return true; }
}else{
return false;
}
}
public static void getPermissionForAppExtCacheDir(Context context)
{
String command = "chmod 777 "
+
Environment.getExternalStorageDirectory().getPath()
+File.separator+"Android"
+" "+
Environment.getExternalStorageDirectory().getPath()
+File.separator+"Android"
+File.separator+"data"
+" "+
Environment.getExternalStorageDirectory().getPath()
+File.separator+"Android"
+File.separator+"data"
+File.separator+context.getPackageName()
+" "+
Environment.getExternalStorageDirectory().getPath()
+File.separator+"Android"
+File.separator+"data"
+File.separator+context.getPackageName()
+File.separator+"cache"
;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
Before I have added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>