Android高级 Glide分析


image.png

image.png
image.png

image.png

知识点1 把请求Builder加入到队列中,开启一个任务处理队列,用Handler处理结果

package com.example.glidelibrary.task;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;

import com.example.glidelibrary.RequestBuilder;
import com.example.glidelibrary.exception.GlideException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.LinkedBlockingQueue;


/**
 * 加载任务
 */

public class DispatcherTask extends Thread {
    private Handler handler;

    private LinkedBlockingQueue<RequestBuilder> blockingQueue;


    public DispatcherTask(LinkedBlockingQueue<RequestBuilder> blockingQueue) {
        this.blockingQueue = blockingQueue;
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void run() {
        super.run();

        //只要线程没有中断,一直轮训
        while (!isInterrupted()) {
            try {
                //从队列中获取请求对象
                RequestBuilder requestBuilder = blockingQueue.take();
                //设置占位符
                placeHolder(requestBuilder);
                //从网路加载图片
                Bitmap bitmap = loadFromNet(requestBuilder);
                //显示到控件
                showBitmap(requestBuilder, bitmap);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void showBitmap(final RequestBuilder requestBuilder, final Bitmap bitmap) {
        if (bitmap != null
                && requestBuilder.getImageView().get() != null
                && requestBuilder.getImageView().get().getTag() == requestBuilder.getMd5FileName()) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    requestBuilder.getImageView().get().setImageBitmap(bitmap);
                    if (requestBuilder.getRequestListener() != null) {
                        requestBuilder.getRequestListener().onResourceReady(bitmap);
                    }

                }
            });
        }
    }

    private Bitmap loadFromNet(RequestBuilder requestBuilder) {
        InputStream is = null;
        Bitmap bitmap = null;
        try {
            URL url = new URL(requestBuilder.getUrl());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            is = getInpuStream(connection);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            requestBuilder.getRequestListener().onLoadFailed(e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmap;
    }

    public InputStream getInpuStream(HttpURLConnection urlConnection) throws IOException {
        int code = urlConnection.getResponseCode();
        if (code == 302) {
            String location = urlConnection.getHeaderField("Location");
            return getInpuStream((HttpURLConnection) new URL(location).openConnection());
        } else if (urlConnection.getResponseCode() == 200) {
            return urlConnection.getInputStream();
        }
        return null;
    }

    private void placeHolder(final RequestBuilder requestBuilder) {
        if (requestBuilder.getPlaceHolderId() > 0 && requestBuilder.getImageView() != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    requestBuilder.getImageView().get().setImageResource(requestBuilder.getPlaceHolderId());
                }
            });
        }
    }
}

三级缓存

  • 首次从网络获取,并缓存下来
  • 从对象获取
  • 对象中没有从内存中获取
  • 内存中没有从磁盘上获取
  • 磁盘没有重新从网路获取

相关依赖库
compile 'com.jakewharton:disklrucache:2.0.2'
相关代码

package com.gameassist.plugin.mod.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.util.LruCache;

import com.jakewharton.disklrucache.DiskLruCache;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static android.os.Environment.isExternalStorageRemovable;

/**
 * Created by ljp on 2018/8/16.
 */

public class LruCacheUtils {

    private static final String TAG = "ggplugin";
    private static final int IO_BUFFER_SIZE = 4096;
    @SuppressLint("StaticFieldLeak")
    private volatile static LruCacheUtils lruCacheUtil;
    private Context context;

    private static final int MAX_SIZE = 10 * 1024 * 1024;//10MB
    private DiskLruCache diskLruCache;
    // 获取可用内存的最大值,使用内存超出这个值将抛出 OutOfMemory 异常。LruCache 通过构造函数传入缓存值,以 KB 为单位。
    private final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // 把最大可用内存的 1/8 作为缓存空间
    private final int cacheSize = maxMemory / 8;

    public static synchronized LruCacheUtils getInstance() {
        if (null == lruCacheUtil) {
            synchronized (ClientUtils.class) {
                if (lruCacheUtil == null) {
                    lruCacheUtil = new LruCacheUtils();
                }
            }
        }
        return lruCacheUtil;
    }


    private LruCache<String, Bitmap> mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };


    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key == null ? "" : key);
    }


    public static File getDiskCacheDir(Context context, String uniqueName) {
        final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !isExternalStorageRemovable()
                ? context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();
        return new File(cachePath + File.separator + uniqueName);
    }

    public static File getDiskFilesDir(Context context, String uniqueName) {
        final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !isExternalStorageRemovable()
                ? context.getExternalFilesDir(null).getPath() : context.getFilesDir().getPath();
        return new File(cachePath + File.separator + uniqueName);
    }


    public void initDiskLruCache(Context context) {
        this.context = context;
        if (diskLruCache == null || diskLruCache.isClosed()) {
            try {
                File cacheDir = getDiskFilesDir(context, "CacheDir");
                if (!cacheDir.exists()) {
                    cacheDir.mkdirs();
                }
                //初始化DiskLruCache
                diskLruCache = DiskLruCache.open(cacheDir, 1, 1, MAX_SIZE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * A hashing method that changes a string (like a URL) into a hash suitable for using as a
     * disk filename.
     */
    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(0xFF & aByte);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    boolean lruHttpBitmap(String url) {
        try {
            String key = hashKeyForDisk(url);
            //得到DiskLruCache.Editor
            DiskLruCache.Editor editor = diskLruCache.edit(key);
            if (editor != null) {
                OutputStream outputStream = editor.newOutputStream(0);
                if (downloadUrlToStream(url, outputStream)) {
//                if (HttpUtils.getInstance(context).networkHttpRequest(url, outputStream)) {
//                    publishProgress("");
                    //写入缓存
                    editor.commit();
                } else {
                    //写入失败
                    editor.abort();
                }

            }
            diskLruCache.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public void putDiskValue(String url, InputStream inputStream) {
        try {
            String key = hashKeyForDisk(url);
            //得到DiskLruCache.Editor
            DiskLruCache.Editor editor = diskLruCache.edit(key);
            if (editor != null) {
                OutputStream outputStream = editor.newOutputStream(0);
                byte[] buffer = new byte[1024];//out写的时候,每次写1024个字节,如果in有2048个字节数,则读2048/1024=2次
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
                editor.commit();
                outputStream.close();
            }
            inputStream.close();
            diskLruCache.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public Bitmap getDiskValue(String url) {
        if (diskLruCache != null) {
            try {
                DiskLruCache.Snapshot snapshot = diskLruCache.get(hashKeyForDisk(url));
                if (snapshot != null) {
                    return BitmapFactory.decodeStream(snapshot.getInputStream(0));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * Download a bitmap from a URL and write the content to an output stream.
     *
     * @param urlString The URL to fetch
     * @return true if successful, false otherwise
     */
    private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;

        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            if (urlConnection != null) {
//                InputStream inputStream = urlConnection.getInputStream();
                InputStream inputStream = getInpuStream(urlConnection);
                if (inputStream != null) {
                    in = new BufferedInputStream(inputStream);
                    out = new BufferedOutputStream(outputStream);
                    int b;
                    while ((b = in.read()) != -1) {
                        out.write(b);
                    }
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in downloadBitmap - " + e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException ignored) {
            }
        }
        return false;
    }


    public InputStream getInpuStream(HttpURLConnection urlConnection) {
        try {
            int code = urlConnection.getResponseCode();
            LogUtils.e("code" + code);
            if (code == 302) {
                String location = urlConnection.getHeaderField("Location");
                return getInpuStream((HttpURLConnection) new URL(location).openConnection());
            } else if (urlConnection.getResponseCode() == 200) {
                return urlConnection.getInputStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容