blob: 28c0656154208f7d1ef75dd787f90cfb980f1a15 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
package org.fox.ttcomics2.utils;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import org.fox.ttcomics2.CommonActivity;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import androidx.core.app.JobIntentService;
public class CacheCleanupService extends JobIntentService {
private final String TAG = this.getClass().getSimpleName();
public static boolean isStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
@Override
protected void onHandleWork(Intent workIntent) {
if (isStorageWritable()) {
File cachePath = new File(workIntent.getStringExtra("workDir"));
Log.d(TAG, "starting for directory: " + cachePath);
try {
if (cachePath.isDirectory()) {
long totalSize = 0;
ArrayList<File> fileList = new ArrayList<File>();
for (File file : cachePath.listFiles()) {
if (file.getName().toLowerCase().contains(".png")) {
totalSize += file.length();
fileList.add(file);
}
}
Log.d(TAG, "total cache size=" + totalSize);
if (totalSize >= CommonActivity.MAX_CACHE_SIZE) {
Log.d(TAG, "expiring oldest files...");
Collections.sort(fileList, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(), f2.lastModified());
}
});
for (File file : fileList) {
if (totalSize >= CommonActivity.MAX_CACHE_SIZE) {
totalSize -= file.length();
file.delete();
} else {
break;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d(TAG, "done.");
}
}
|