I need one help regarding cache memory in my android app. I am Running server (android) in a device. I want to do clear cache of that app programmatically. I have database in that server. Based on that database my client operations are going on. So I don't want it (Database) to get effected. I just want to clear cache not to clear data. Please help me with this.
Asked
Active
Viewed 1.9k times
7
-
If you are using Kotlin see my answer at the bottom for a oneliner – Merthan Erdem Mar 11 '21 at 14:23
3 Answers
6
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
@Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
@Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception e) {
e.printStackTrace();
}
}
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 {
return false;
}
}
6
On Kotlin you can just call
File(context.cacheDir.path).deleteRecursively()

Merthan Erdem
- 5,598
- 2
- 22
- 29
-
1
-
-
1@manjesh23 you need to get the context from somewhere (if you are outside of an activity), you need to pass it to the method. You can also try "this" instead of context or "this@YourActivity" for example – Merthan Erdem Nov 26 '21 at 19:08
3
Code for clearing the cache:
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
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();
}
return false;
}

luckyging3r
- 3,047
- 3
- 18
- 37

Md Hussain
- 411
- 4
- 10