diff options
Diffstat (limited to 'org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/CacheCleanupService.java')
-rwxr-xr-x | org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/CacheCleanupService.java | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/CacheCleanupService.java b/org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/CacheCleanupService.java new file mode 100755 index 0000000..ec73e34 --- /dev/null +++ b/org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/CacheCleanupService.java @@ -0,0 +1,79 @@ +package org.fox.ttcomics2.utils; + +import android.app.IntentService; +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; + +public class CacheCleanupService extends IntentService { + private final String TAG = this.getClass().getSimpleName(); + + public CacheCleanupService() { + super("CacheCleanupService"); + } + public CacheCleanupService(String name) { + super(name); + } + + public static boolean isStorageWritable() { + String state = Environment.getExternalStorageState(); + return Environment.MEDIA_MOUNTED.equals(state); + } + @Override + protected void onHandleIntent(Intent workIntent) { + Log.d(TAG, "starting..."); + + if (isStorageWritable()) { + File cachePath = getExternalCacheDir(); + + 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."); + } +}
\ No newline at end of file |