在Android 4.0中使用DiskLruCache并没有提供openCache方法

47

终于做到了 https://dev59.com/Y2Ml5IYBdhLWcg3wXWET#32516598 - Muhammad Babar
3个回答

119

你可以使用Picasso作为图片加载器。

或者

这是我所做的:

我创建了一个名为DiskLruImageCache的类,其中包含一个来自Jake Wharton的DiskLruCache (与dev指南中简单实现相同的方法:高效显示位图)对象。

public class DiskLruImageCache {

    private DiskLruCache mDiskCache;
    private CompressFormat mCompressFormat = CompressFormat.JPEG;
    private int mCompressQuality = 70;
    private static final int APP_VERSION = 1;
    private static final int VALUE_COUNT = 1;
    private static final String TAG = "DiskLruImageCache";

    public DiskLruImageCache( Context context,String uniqueName, int diskCacheSize,
        CompressFormat compressFormat, int quality ) {
        try {
                final File diskCacheDir = getDiskCacheDir(context, uniqueName );
                mDiskCache = DiskLruCache.open( diskCacheDir, APP_VERSION, VALUE_COUNT, diskCacheSize );
                mCompressFormat = compressFormat;
                mCompressQuality = quality;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    private boolean writeBitmapToFile( Bitmap bitmap, DiskLruCache.Editor editor )
        throws IOException, FileNotFoundException {
        OutputStream out = null;
        try {
            out = new BufferedOutputStream( editor.newOutputStream( 0 ), Utils.IO_BUFFER_SIZE );
            return bitmap.compress( mCompressFormat, mCompressQuality, out );
        } finally {
            if ( out != null ) {
                out.close();
            }
        }
    }

    private File getDiskCacheDir(Context context, String uniqueName) {

    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
        final String cachePath =
            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                    !Utils.isExternalStorageRemovable() ?
                    Utils.getExternalCacheDir(context).getPath() :
                    context.getCacheDir().getPath();

        return new File(cachePath + File.separator + uniqueName);
    }

    public void put( String key, Bitmap data ) {

        DiskLruCache.Editor editor = null;
        try {
            editor = mDiskCache.edit( key );
            if ( editor == null ) {
                return;
            }

            if( writeBitmapToFile( data, editor ) ) {               
                mDiskCache.flush();
                editor.commit();
                if ( BuildConfig.DEBUG ) {
                   Log.d( "cache_test_DISK_", "image put on disk cache " + key );
                }
            } else {
                editor.abort();
                if ( BuildConfig.DEBUG ) {
                    Log.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + key );
                }
            }   
        } catch (IOException e) {
            if ( BuildConfig.DEBUG ) {
                Log.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + key );
            }
            try {
                if ( editor != null ) {
                    editor.abort();
                }
            } catch (IOException ignored) {
            }           
        }

    }

    public Bitmap getBitmap( String key ) {

        Bitmap bitmap = null;
        DiskLruCache.Snapshot snapshot = null;
        try {

            snapshot = mDiskCache.get( key );
            if ( snapshot == null ) {
                return null;
            }
            final InputStream in = snapshot.getInputStream( 0 );
            if ( in != null ) {
                final BufferedInputStream buffIn = 
                new BufferedInputStream( in, Utils.IO_BUFFER_SIZE );
                bitmap = BitmapFactory.decodeStream( buffIn );              
            }   
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
            if ( snapshot != null ) {
                snapshot.close();
            }
        }

        if ( BuildConfig.DEBUG ) {
            Log.d( "cache_test_DISK_", bitmap == null ? "" : "image read from disk " + key);
        }

        return bitmap;

    }

    public boolean containsKey( String key ) {

        boolean contained = false;
        DiskLruCache.Snapshot snapshot = null;
        try {
            snapshot = mDiskCache.get( key );
            contained = snapshot != null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if ( snapshot != null ) {
                snapshot.close();
            }
        }

        return contained;

    }

    public void clearCache() {
        if ( BuildConfig.DEBUG ) {
            Log.d( "cache_test_DISK_", "disk cache CLEARED");
        }
        try {
            mDiskCache.delete();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    public File getCacheFolder() {
        return mDiskCache.getDirectory();
    }

}

工具类源代码为:

public class Utils {
    public static final int IO_BUFFER_SIZE = 8 * 1024;

    private Utils() {};

    public static boolean isExternalStorageRemovable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return Environment.isExternalStorageRemovable();
        }
        return true;
    }

    public static File getExternalCacheDir(Context context) {
        if (hasExternalCacheDir()) {
            return context.getExternalCacheDir();
        }

        // Before Froyo we need to construct the external cache dir ourselves
        final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
        return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
    }

    public static boolean hasExternalCacheDir() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

}
请提供完整的需要翻译的内容,当前给出的内容不足以进行翻译。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在您的AndroidManifest.xml文件中

我通过阅读这段代码和Jake Wharton的DiskLruCache的javadoc文档找到了这种方法。


4
明白了,我需要在我的活动结束时调用 DiskLruCache 的 close() 方法。现在正常运行。 - Anuj
1
抱歉,我忘记了我使用了自己的Utils类。我会用正确的源代码更新答案。 - Platonius
1
我遇到了一个java.lang.IllegalStateException: edit didn't create file 1的错误,你有什么想法吗? - mipreamble
1
@Platonius 谢谢。这非常有帮助。在 put() 中,您在 editor.commit() 之前使用了 mDiskCache.flush()。难道不应该反过来吗?如果按照您的代码,最后一个条目将保持为脏数据,如果应用程序重新启动,则该缓存条目将不再可用。 - sajal
1
在你的 DiskLruImageCache.getDiskCacheDir() 方法中,将 Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED 替换为 Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) 是否更好?这是基于 http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache 的建议。 - Pang
显示剩余19条评论

9
您还可以使用SimpleDiskCache,它将DiskLruCache封装在更加开发者友好的界面中。

@Malachiasz 如果这是真的(事实并非如此),SimpleDiskCache 确实是无用的。 - fhucho

4

我基于@Platonius发布的这段好代码编写了一个库。它包括一些错误修复,例如在put()方法中经常出现的“无法删除文件”的IOException。它同时使用LRU和磁盘缓存:https://github.com/felipecsl/Android-ImageManager


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接