LruCache与DiskLruCache结合,实现照片墙

在上一篇的文章中,讲解了Bitmap的高效加载,以及LruCache和DiskLruCache的基本用法。但是在实际的项目中,只使用内存缓存或者只使用磁盘缓存是有短板的。内存缓存速度快,但空间有限;磁盘缓存相对内存缓存来说,速度相对慢,但空间较充足。因此,如果将二者相结合到开发中,会有如虎添翼的效果。
下面还是以网络获取图片,并添加内存缓存和磁盘缓存为例,实现照片墙的效果。

首先,定义网络图片地址:

public class Images {
    public final static String[] imageThumbUrls = new String[] {
            "http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383166_3407.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383165_7197.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383150_8410.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383131_3736.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383130_5094.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383130_7393.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383129_8813.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383100_3554.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383093_7894.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383092_2432.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383092_3071.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383091_3119.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383059_6589.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383059_8814.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383059_2237.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383058_4330.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406383038_3602.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382942_3079.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382942_8125.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382942_4881.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382941_4559.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382941_3845.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382924_8955.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382923_2141.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382923_8437.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382922_6166.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382922_4843.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382905_5804.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382904_3362.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382904_2312.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382904_4960.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382900_2418.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382881_4490.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382881_5935.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382880_3865.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382880_4662.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382879_2553.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382862_5375.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382862_1748.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382861_7618.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382861_8606.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382861_8949.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382841_9821.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382840_6603.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382840_2405.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382840_6354.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382839_5779.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382810_7578.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382810_2436.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382809_3883.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382809_6269.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382808_4179.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382790_8326.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382789_7174.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382789_5170.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382789_4118.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382788_9532.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382767_3184.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382767_4772.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382766_4924.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382766_5762.jpg",
            "http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg"
    };
}

在activity_main.xml中,需要通过GridView控件以网格形式显示图片:

<GridView
        android:id="@+id/photo_wall"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="100dp"
        android:gravity="center"
        android:horizontalSpacing="2dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="2dp">
    </GridView>

另外,需要定义GridView中每张图片的布局,新建photo_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/photo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:scaleType="fitXY"/>

</LinearLayout>

接下来为GridView创建适配器PhotoAdapter

public class PhotoAdapter extends ArrayAdapter<String> {
    /*
    * 内存缓存
    */
    private LruCache<String, Bitmap> mMemoryCache;
    /*
    * 磁盘缓存
    */
    private DiskLruCache mDiskCache;
    private Context mContext;
    private GridView mGridView;
    /*
    * 存放图片下载队列
    */
    private Set<downBitmapTask> mHttpTask;
    /*
    * 图片item的默认高度
    */
    private int mHeight = 100;

    public PhotoAdapter(@NonNull Context context, @LayoutRes int resource, @IdRes int textViewResourceId, @NonNull String[] objects, GridView gridbiew) {
        super(context, resource, textViewResourceId, objects);
        this.mContext = context;
        this.mGridView = gridbiew;
        mHttpTask = new HashSet<downBitmapTask>();
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
        File file = getDiskCacheDir(mContext, "bitmap");
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            mDiskCache = DiskLruCache.open(file, getAppVersion(mContext), 1, 100 * 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        final String url = getItem(position);
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.photo_item, null);
        } else {
            view = convertView;
        }
        final ImageView imageView = view.findViewById(R.id.photo);
        if (imageView.getLayoutParams().height != mHeight) {
            imageView.getLayoutParams().height = mHeight;
        }
        imageView.setImageResource(R.mipmap.cat);
        imageView.setTag(url);
        loadBitmaps(imageView, url);
        return view;
    }

    /*
    * 加载bitmap,首先从内存缓存获取,
    * 如果当前没有缓存,则网络获取图片
    */
    private void loadBitmaps(ImageView imageView, String url) {
        Bitmap bitmap = getBitmapFormMemory(url);
        if (bitmap == null) {
            downBitmapTask task = new downBitmapTask();
            mHttpTask.add(task);
            task.execute(url);
        } else {
            imageView.setImageBitmap(bitmap);
        }
    }

    //写入缓存
    private void addBitmapToMemory(String key, Bitmap bitmap) {
        if (getBitmapFormMemory(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    //读取缓存
    private Bitmap getBitmapFormMemory(String key) {
        return mMemoryCache.get(key);
    }

    //异步网络获取图片
    class downBitmapTask extends AsyncTask<String, Void, Bitmap> {
        String imageUrl;

        @Override
        protected Bitmap doInBackground(String... strings) {
            imageUrl = strings[0];
            /*
            * 1、判断磁盘缓存是否存在,Y:从缓存获取
            * 2、N:从网络获取,并写入缓存
            */
            FileDescriptor filedes = null;
            FileInputStream fileis = null;
            final String key = hashKeyForDisk(imageUrl);
            try {
                DiskLruCache.Snapshot snapshot = mDiskCache.get(key);
                if (snapshot == null) {
                    DiskLruCache.Editor edit = mDiskCache.edit(key);
                    if (edit != null) {
                        OutputStream os = edit.newOutputStream(0);
                        if (downloadUrlToStream(imageUrl, os)) {
                            edit.commit();
                        } else {
                            edit.abort();
                        }
                    }
                    snapshot = mDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileis = (FileInputStream) snapshot.getInputStream(0);
                    filedes = fileis.getFD();
                }
                Bitmap bitmap = BitmapFactory.decodeFileDescriptor(filedes);
                if (bitmap != null) {
                    addBitmapToMemory(strings[0], bitmap);
                }
                return bitmap;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fileis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            // 根据Tag找到相应的ImageView控件,将下载好的图片显示出来
            ImageView imageview = mGridView.findViewWithTag(imageUrl);
            if (bitmap != null && imageview != null) {
                imageview.setImageBitmap(bitmap);
            }
            imageview.setImageBitmap(bitmap);
            mHttpTask.remove(this);
        }
    }

    /*
    * 网络获取图片,并写入输出流
    */
    private boolean downloadUrlToStream(String urlstring, OutputStream outputstream) {
        HttpURLConnection httpconnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlstring);
            httpconnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(httpconnection.getInputStream(), 8 * 1024);
            out = new BufferedOutputStream(outputstream, 8 * 1024);
            int b;
            if ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpconnection != null) {
                httpconnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
    * 获取当前存储路径
    */
    public File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
    * MD5转换图片url key
    */
    private String hashKeyForDisk(String key) {
        String cacheKey = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(key.getBytes());
            cacheKey = bytesToHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return cacheKey;
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        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 void setHeight(int height) {
        if (this.mHeight != height) {
            this.mHeight = height;
        }
        notifyDataSetChanged();
    }

    public void clearTask() {
        if (mHttpTask != null) {
            for (downBitmapTask task : mHttpTask) {
                task.cancel(false);
            }
        }
    }

    /**
     * 将缓存记录同步到journal文件中。
     */
    public void fluchCache() {
        if (mDiskCache != null) {
            try {
                mDiskCache.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前应用程序的版本号。
     */
    public int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /*
     * 得到图片字节流 数组大小
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();

    }
}

上面关于适配器adapter的代码里注释的都比较清楚了,这里就只讲讲具体实现的思路:
在构造方法中,进行相关的初始化,获取应用可用的最大内存,设置LruCache的最大缓存为最大内存的1/8;获取当前的存储路径,通过DiskLruCache的open方法创建磁盘缓存对象。

在getView方法中,首先为ImageView设置默认图片,添加唯一的Tag,以便后面能够准确的找到该View,避免在异步加载图片时出现乱序的情况。接着通过loadBitmaps方法加载图片,如果内存缓存存在获取对象,则直接从缓存里获取,反之,开启异步线程downBitmapTask。

downBitmapTask中,通过doInBackground方法开启后台线程,首先判断磁盘缓存是否存在,如果不存在则通过downloadUrlToStpianream获取网络图片并写入缓存,最后从缓存里获取bitmap对象交给ImageView显示。当然,最后也将其写入内存缓存里。

通过异步线程返回的bitmap对象,将在onPostExecute方法里被引用,该方法在主线程中执行,因此可以通过ImageView直接更新UI。

上面的适配器准备完成后,那么回到主Activity,

public class MainActivity extends AppCompatActivity {
    private GridView mGridView;
    private PhotoAdapter mAdapter;
    private final static int mWidth = 100;
    private final static int mMargin = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGridView = (GridView) findViewById(R.id.photo_wall);
        mAdapter = new PhotoAdapter(this,0,0,Images.imageThumbUrls,mGridView);
        mGridView.setAdapter(mAdapter);

        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int count = (int) Math.floor(mGridView.getWidth() / (mWidth + mMargin));
                        if (count > 0){
                            int width = (mGridView.getWidth() / count) - mMargin;
                            mAdapter.setHeight(width);
                            mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }
                }
        );
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAdapter.fluchCache();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 退出程序时结束所有的下载任务
        mAdapter.clearTask();
    }
}

在onCreat方法中,初始化PhotoAdapter对象,并绑定GridView,通过getViewTreeObserver()的方式监听View的布局事件,当布局完成以后,重新修改一下GridView中子View的高度,以保证子View的宽度和高度可以保持一致。

值得一提的是,关于缓存机制,涉及到文件的读写操作,因此应该添加对应的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

另外,在Android 6.0后,需要动态获取sd卡的读写权限:

private static final String[] PERMISSION_EXTERNAL_STORAGE = new String[] {
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
private static final int REQUEST_EXTERNAL_STORAGE = 100;

private void verifyStoragePermissions(Activity activity) {
        int permissionWrite = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(permissionWrite != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_EXTERNAL_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

好了,关于LruCache和DiskLruCache相结合的缓存机制就介绍到这里了,在实际的开发过程中,一般还需将Bitmap的高效加载也融入其中,这样即使在处理大量图片时,我们的应用也会保持流畅,具有良好的交互性。

猜你喜欢

转载自blog.csdn.net/Mr_azheng/article/details/79420945