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) { Log.d(TAG, "starting..."); if (isStorageWritable()) { File cachePath = CommonActivity.getCacheDir(this); try { if (cachePath.isDirectory()) { long totalSize = 0; ArrayList fileList = new ArrayList(); 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() { 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."); } }