summaryrefslogtreecommitdiff
path: root/org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/CacheCleanupService.java
blob: d68e03925d0480dcabc0dd7ee2c0f33aa7941b2a (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
package org.fox.ttcomics2.utils;

import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.JobIntentService;
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 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<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.");
    }
}