admin
7 天以前 7f0825f8195a522ed7e8bcdb6347f3a719e06c74
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.weikou.beibeivideo.util.cache;
 
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
 
import com.lcjian.library.util.cache.DiskLruCache;
import com.lcjian.library.util.common.StorageUtils;
 
import java.io.File;
import java.io.IOException;
 
public class DiskLruCacheManager {
 
    private static DiskLruCacheManager instance;
    private DiskLruCache cache;
 
    private static int getVersionNum(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 1;
        }
    }
 
    public DiskLruCacheManager(Context context) {
        try {
            cache = DiskLruCache.open(
                    new File(StorageUtils.getCacheDirectory(context)
                            .toString(), "http"), getVersionNum(context),
                    1, 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    public static DiskLruCacheManager getInstance(Context context) {
        if (instance == null)
            instance = new DiskLruCacheManager(context);
        return instance;
    }
 
 
    public void cache(String key, String value) {
        if (cache == null)
            return;
        DiskLruCache.Editor editor = null;
        try {
            editor = cache
                    .edit(key);
            editor.set(0, value);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 取缓存
     *
     * @param key
     * @return
     */
    public String getCache(String key) {
        if (cache == null)
            return null;
        DiskLruCache.Snapshot snapshot = null;
        try {
            if (cache != null) {
                snapshot = cache.get(key);
                if (snapshot != null) {
                    return snapshot.getString(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (snapshot != null) {
                snapshot.close();
            }
        }
        return null;
    }
 
 
}