Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了来自android教程的DiskLruCache缺少很多方法.大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
以下是我关注的磁盘缓存教程.我已经将源代码下载到DiskLruCache,但是在这个例子中使用的方法都不存在于源代码中.

http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache

我需要自己实现这些方法,还是有一个在某处丢失的DiskLruCache版本?

解决方法

以下是DiskLruCache的完整实现.

首先从AOSP下载DiskLruCache.java.

这是我的DiskCache.java一个基本缓存操作的帮助类.

/**
 * Created by Babar on 12-Aug-15.
 */
public class DiskCache
{

    private Context context;

    private static DiskCache diskCache;

    public DiskLruCache mDiskLruCache;

    private final Object mDiskCacHelock = new Object();

    private BitmapProcessor bitmapProcessor;

    private static final int DISK_CACHE_INDEX = 0;

    public static Boolean mDiskCacheStarTing = true;

    private static final String DISK_CACHE_SUBDIR = "ooredoo_thumbnails";

    private static final int DISK_CACHE_SIZE = 1024 * 1024 * 100; // 100MB

    public static DiskCache geTinstance()
    {
        if(diskCache == null)
        {
            diskCache = new DiskCache();
        }

        return diskCache;
    }

    private DiskCache() {}

    public void requesTinit(Context context)
    {
        this.context = context;

        bitmapProcessor = new BitmapProcessor();

        new DiskCacheTask(this).execute(DiskCacheTask.INIT);
    }

    public void init() throws IOException {
        synchronized (mDiskCacHelock)
        {
            if(mDiskLruCache == null || mDiskLruCache.isClosed())
            {
                File cacheDir = FileUtils.getDiskCacheDir(context,DISK_CACHE_SUBDIR);

                if(!cacheDir.exists())
                {
                    cacheDir.mkdir();
                }

                if(FileUtils.getUsableSpace(cacheDir) > DISK_CACHE_SIZE)
                {
                    mDiskLruCache = DiskLruCache.open(cacheDir,1,DISK_CACHE_SIZE);
                }
                else
                {
                    Logger.print("InitDiskCache Failed: NOT enough space on disk");
                }
            }

            mDiskCacheStarTing = false; // Finished initialization
            mDiskCacHelock.notifyAll(); // Wake any waiTing threads
        }
    }


    public void addBitmapToDiskCache(final String key,final Bitmap value) {
        if (key == null || value == null) {
            return;
        }

        synchronized (mDiskCacHelock)
        {
            if (mDiskLruCache != null) {
                OutputStream out = null;

                String encryptedKey = CryptoutIls.encryptToMD5(key);

                Logger.print("addBitmapToDiskCache encryptToMD5: " + encryptedKey);

                try {
                    DiskLruCache.Snapshot snapshot = mDiskLruCache.get(encryptedKey);

                    if (snapshot == null) {
                        final DiskLruCache.Editor editor = mDiskLruCache.edit(encryptedKey);

                        if (editor != null) {
                            out = editor.newOutputStream(DISK_CACHE_INDEX);

                            value.compress(Bitmap.CompressFormat.JPEG,100,out);

                            editor.commit();
                            out.close();
                        }
                    } else {
                        snapshot.geTinputStream(DISK_CACHE_INDEX).close();
                    }
                } catch (IOException E) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException E) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    /**
     * Get from disk cache.
     *
     * @param key Unique identifier for which item to get
     * @return The bitmap if found in cache,null otherwise
     */
    public Bitmap getBitmapFromDiskCache(final String key)
    {
        Bitmap bitmap = null;

        String encryptedKey = CryptoutIls.encryptToMD5(key);

        Logger.print("getBitmapFromDiskCache encryptToMD5: " + encryptedKey);

        synchronized (mDiskCacHelock)
        {
            Logger.print("mDiskcachestarTing: "+mDiskCacheStarTing);
            // Wait while disk cache is started from BACkground thread
            while (mDiskCacheStarTing)
            {
                try
                {
                    mDiskCacHelock.wait();
                }
                catch (InterruptedException E)
                {
                    e.printStackTrace();
                }
            }

            if(mDiskLruCache != null)
            {
                InputStream inputStream = null;

                try
                {
                    final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(encryptedKey);

                    if(snapshot != null)
                    {
                        Logger.print("Disk cache hit");

                        inputStream = snapshot.geTinputStream(DISK_CACHE_INDEX);

                        if(inputStream != null)
                        {
                            FileDescriptor fd = ((FileInputStream) inputStream).getFD();

                            // Decode bitmap,but we don't want to sample so give
                            // max_value as the target dimensions

                            bitmap = bitmapProcessor.decodeSampledBitmapFromDescriptor(fd);
                        }
                    }
                }
                catch (IOException E)
                {
                    e.printStackTrace();
                }
                finally
                {
                    if(inputStream != null)
                    {
                        try
                        {
                            inputStream.close();
                        }
                        catch (IOException E)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }
            Logger.print("dCache getBitmapFromDiskCache synchronized completed");
        }

        Logger.print("dCache getBitmapFromDiskCache returning Bitmap");
        return bitmap;
    }

    public void requestFlush()
    {
        new DiskCacheTask(this).execute(DiskCacheTask.FLUSH);
    }

    /**
     * Flushes the disk cache associated with this ImageCache object. Note that this includes
     * disk access so this should not be executed on the main/UI thread.
     */
    public void flush()
    {
        synchronized (mDiskCacHelock)
        {
            if(mDiskLruCache != null)
            {
                try
                {
                    mDiskLruCache.flush();

                    Logger.print("flush: disk cache flushed");
                }
                catch (IOException E)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void requestClose()
    {
        new DiskCacheTask(this).execute(DiskCacheTask.CLOSE);
    }

    /**
     * Closes the disk cache associated with this ImageCache object. Note that this includes
     * disk access so this should not be executed on the main/UI thread.
     */
    public void close()
    {
        synchronized (mDiskCacHelock)
        {
            if(mDiskLruCache != null)
            {
                if(!mDiskLruCache.isClosed())
                {
                    try
                    {
                        mDiskLruCache.close();
                        mDiskLruCache = null;

                        Logger.print("disk cache closed");
                    }
                    catch (IOException E)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * Do not call this method unless you need to explicitly clear disk cache
     */
    public void requestTearDown()
    {
        new DiskCacheTask(this).execute(DiskCacheTask.TEAR_DOWN);
    }

    public final void tearDown()
    {
        synchronized (mDiskCacHelock)
        {
            mDiskCacheStarTing = true;

            if(mDiskLruCache != null && !mDiskLruCache.isClosed())
            {
                try
                {
                    mDiskLruCache.delete();

                    Logger.print("disk cache cleared");
                }
                catch (IOException E)
                {
                    e.printStackTrace();
                }

                mDiskLruCache = null;
            }
        }
    }
}

这是BitmapProcesser.java

/**
 * @author  Babar
 * @since 15-Jun-15.
 */
public class BitmapProcessor
{
    public Bitmap decodeSampledBitmapFromStream(InputStream inputStream,URL url,int reqWidth,int reqHeight) throws IOException {
        Bitmap bitmap;

        BitmapFactory.options options = new BitmapFactory.options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(inputStream,null,options);

        int width = options.outWidth;
        int height = options.outHeight;

        Logger.print("@Req Width: "+reqWidth);
        Logger.print("@Req Height: " + reqHeight);

        Logger.print("@Actual Width: "+width);
        Logger.print("@Actual Height: " + height);

        int sampleSize = calculateInSampleSize(options,reqWidth,reqHeight);

        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;

        inputStream = url.openStream();

        bitmap = BitmapFactory.decodeStream(inputStream,options);

        if(bitmap != null)
        {
            width = bitmap.getWidth();
            height = bitmap.getHeight();

            Logger.print("@inSample:"+sampleSizE);
            Logger.print("@modified Width: "+width);
            Logger.print("@modified Height: " + height);
        }

        return bitmap;
    }

    public Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fd)
    {
        /*final BitmapFactory.options options = new BitmapFactory.options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFileDescriptor(fd,options);

        options.inSampleSize = calculateInSampleSize(options,reqHeight);

        options.inJustDecodeBounds = false;*/

        return BitmapFactory.decodeFileDescriptor(fd);

    }

    public Bitmap decodeSampledBitmapFromFile(String pathName,int reqHeight) throws IOException {
        Bitmap bitmap;

        BitmapFactory.options options = new BitmapFactory.options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(pathName,reqHeight);

        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;

        bitmap = BitmapFactory.decodeFile(pathName,options);

        if(bitmap != null)
        {
            width = bitmap.getWidth();
            height = bitmap.getHeight();

            Logger.print("@inSample:"+sampleSizE);
            Logger.print("@modified Width: "+width);
            Logger.print("@modified Height: " + height);
        }

        return bitmap != null ? rotateBitmapIfNeeded(pathName,bitmap) : null;
    }

    public int calculateInSampleSize(BitmapFactory.options options,int requiredWidth,int requiredHeight)
    {
        final int width = options.outWidth;
        final int height = options.outHeight;

        int inSampleSize = 1;

        if(width > requiredWidth || height > requiredHeight)
        {
            final int halfWidth = width / 2;
            final int halfHeight = height / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfWidth / inSampleSizE) > requiredWidth
                                    &&
                    (halfHeight / inSampleSizE) > requiredHeight)
            {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public static Bitmap rotateBitmapIfNeeded(String pathName,Bitmap bitmap) throws IOException {
        ExifInterface exifInterface = new ExifInterface(pathName);

        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.oRIENTATION_NORMAL);

        Logger.logI("BITMAP_ORIENTATION: " + orientation,pathName);

        switch (orientation)
        {
            case ExifInterface.oRIENTATION_ROTATE_90:

                return rotateBitmap(bitmap,90);

            case ExifInterface.oRIENTATION_ROTATE_180:

                return rotateBitmap(bitmap,180);

            case ExifInterface.oRIENTATION_ROTATE_270:

                return rotateBitmap(bitmap,270);
        }

        return bitmap;
    }

    public Bitmap makeBitmapround(Bitmap srC)
    {
        int width = src.getWidth();
        int height = src.getHeight();

        Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);

       // Canvas canvas = new Canvas(bitmap);

        BitmapShader shader = new BitmapShader(src,Shader.TileMode.CLAMP,Shader.TileMode.CLAMp);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(shader);



        RectF rectF = new RectF(0.0f,0.0f,width,height);

        // rect contains the bounds of the shape
        // radius is the radius in pixels of the rounded corners
        // paint contains the shader that will texture the shape

        Canvas canvas = new Canvas(src);

        canvas.drawRoundRect(rectF,30,paint);

        return src;
    }

    public static Bitmap rotateBitmap(Bitmap bitmap,int degreE) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degreE);

        return Bitmap.createBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(),matrix,truE);
    }
}

这里是CryptoutIls.java

/**
 * @author Babar
 * @since 29-Jun-15.
 */
public class CryptoutIls
{
    private static final String MD5_ALGO = "MD5";


    public static String encryptToMD5(String text)
    {
        try
        {
            java.security.messageDigest md = java.security.messageDigest.geTinstance(MD5_ALGO);
            md.update(text.getBytes());

            byte[] bytes = md.digest();

            String hex = bytesToHexString(bytes);

            return hex;
        }
        catch (NoSuchAlgorithmException E)
        {
            e.printStackTrace();

            return String.valueOf(text.hashCode());
        }
    }

    private static String bytesToHexString(byte[] bytes)
    {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < bytes.length; i++)
        {
            String hex = Integer.toHexString(0xFF & bytes[i]);

            if(hex.length() == 1)
            {
                sb.append('0');
            }

            sb.append(heX);
        }

        return sb.toString();
    }

    public static String encodeToBase64(String str) {
        String tmp = "";
        if(isnotNullOrEmpty(str)) {
            try {
                tmp = new String(Base64.encode(str.getBytes(),Base64.DEFAULT)).trim();
            } catch(Throwable E) {
                e.printStackTrace();
            }
        }
        return tmp;
    }
}

这是DiskCacheTask.java

/**
 * Created by Babar on 12-Aug-15.
 */
public class DiskCacheTask extends BaseAsyncTask<Integer,Void,Void>
{
    private DiskCache diskCache;

    public static final int INIT = 1;

    public static final int FLUSH = 2;

    public static final int CLOSE = 3;

    public static final int TEAR_DOWN = 4;

    public static final int REMOVE = 5;

    public DiskCacheTask(DiskCache diskCachE)
    {
        this.diskCache = diskCache;
    }

    @Override
    protected Void doInBACkground(Integer... params)
    {
        switch (params[0])
        {
            case INIT:

                try
                {
                    diskCache.init();
                }
                catch (IOException E)
                {
                    e.printStackTrace();
                }

                break;

            case FLUSH:

                diskCache.flush();

                break;

            case CLOSE:

                diskCache.close();

                break;

            case TEAR_DOWN:

                diskCache.tearDown();

                break;

            case REMOVE:

                diskCache.remove();

                break;
        }

        return null;
    }
}

要初始化缓存,只需调用新的DiskCache().geTinstance().requesTinit();理想情况下,您的MainActivity的onCreate().另请注意,磁盘操作应该在单独的线程中完成,例如Handler,AsyncTask.所以当你想要从/从磁盘缓存中添加/获取位图时,从工作线程中执行此操作.

大佬总结

以上是大佬教程为你收集整理的来自android教程的DiskLruCache缺少很多方法.全部内容,希望文章能够帮你解决来自android教程的DiskLruCache缺少很多方法.所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。