国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android中圖片的三級緩存機制

2019-12-12 05:35:32
字體:
來源:轉載
供稿:網友

我們不能每次加載圖片的時候都讓用戶從網絡上下載,這樣不僅浪費流量又會影響用戶體驗,所以Android中引入了圖片的緩存這一操作機制。

原理:

  首先根據圖片的網絡地址在網絡上下載圖片,將圖片先緩存到內存緩存中,緩存到強引用中 也就是LruCache中。如果強引用中空間不足,就會將較早存儲的圖片對象驅逐到軟引用(softReference)中存儲,然后將圖片緩存到文件(內部存儲外部存儲)中;讀取圖片的時候,先讀取內存緩存,判斷強引用中是否存在圖片,如果強引用中存在,則直接讀取,如果強引用中不存在,則判斷軟引用中是否存在,如果軟引用中存在,則將軟引用中的圖片添加到強引用中并且刪除軟引用中的數據,如果軟引用中不存在,則讀取文件存儲,如果文件存儲不存在,則網絡加載。

  下載: 網絡--內存--文件

  讀取: 內存--強引用--軟引用--文件--網絡

也就是這樣的一個過程,下面用一個簡單地demo來演示一下圖片你的三級緩存,此demo中只有一個界面,界面上一個ImageView用來顯示圖片,一個按鈕用來點擊的時候加載圖片。布局如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/iv_img"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@mipmap/ic_launcher"android:layout_centerInParent="true"/><Buttonandroid:id="@+id/btn_download"android:layout_below="@+id/iv_img"android:layout_centerHorizontal="true"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="加載圖片"/></RelativeLayout>

  因為要從網絡下載數據,還要存儲到本地sd卡中,所以不要忘了為程序添加網絡訪問的權限、網絡狀態訪問的權限和向外部存儲設備寫內容的權限:

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

  接著,創建一個 HttpUtils 工具類用于訪問網絡,代碼如下:

package com.yztc.lx.cashimg;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;/**網絡訪問工具類* Created by Lx on 2016/8/19.*/public class HttpUtils {/*** 判斷網絡連接是否通暢* @param mContext* @return*/public static boolean isNetConn(Context mContext) {ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo info = manager.getActiveNetworkInfo();if (info != null) {return info.isConnected();} else {return false;}}/*** 根據path下載網絡上的數據* @param path 路徑* @return 返回下載內容的byte數據形式*/public static byte[] getDateFromNet(String path) {ByteArrayOutputStream baos = new ByteArrayOutputStream();try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);conn.setDoInput(true);conn.connect();if (conn.getResponseCode()==200) {InputStream is = conn.getInputStream();byte b[] = new byte[1024];int len;while ((len=is.read(b))!=-1) {baos.write(b, 0, len);}return baos.toByteArray();}} catch (IOException e) {e.printStackTrace();}return baos.toByteArray();}}

  還有操作外部存儲的工具類:

package com.yztc.lx.cashimg;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/*** Created by Lx on 2016/8/20.*/public class ExternalStorageUtils {/*** 將傳遞過來的圖片byte數組存儲到sd卡中* @param imgName 圖片的名字* @param buff byte數組* @return 返回是否存儲成功*/public static boolean storeToSDRoot(String imgName, byte buff[]) {boolean b = false;String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();File file = new File(basePath, imgName);try {FileOutputStream fos = new FileOutputStream(file);fos.write(buff);fos.close();b = true;} catch (IOException e) {e.printStackTrace();}return b;}/*** 從本地內存中根據圖片名字獲取圖片* @param imgName 圖片名字* @return 返回圖片的Bitmap格式*/public static Bitmap getImgFromSDRoot(String imgName) {Bitmap bitmap = null;String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();File file = new File(basePath, imgName);try {FileInputStream fis = new FileInputStream(file);ByteArrayOutputStream baos = new ByteArrayOutputStream();byte b[] = new byte[1024];int len;while ((len = fis.read(b)) != -1) {baos.write(b, 0, len);}byte buff[] = baos.toByteArray();if (buff != null && buff.length != 0) {bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length);}} catch (IOException e) {e.printStackTrace();}return bitmap;}}

  本例中將圖片默認存在了sd卡根目錄中。

  然后是最主要的主函數了:

package com.yztc.lx.cashimg;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.util.LruCache;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.lang.ref.SoftReference;import java.util.LinkedHashMap;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button btn_download;private ImageView iv_img;private MyLruCache myLruCache;private LinkedHashMap<String, SoftReference<Bitmap>> cashMap = new LinkedHashMap<>();private static final String TAG = "MainActivity";private String imgPath = "http://www.3dmgame.com/UploadFiles/201212/Medium_20121217143424221.jpg";private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {Bitmap bitmap = (Bitmap) msg.obj;iv_img.setImageBitmap(bitmap);Toast.makeText(MainActivity.this, "從網絡上下載圖片", Toast.LENGTH_SHORT).show();}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();int totalMemory = (int) Runtime.getRuntime().maxMemory();int size = totalMemory / 8;myLruCache = new MyLruCache(size);btn_download.setOnClickListener(this);}private void initView() {btn_download = (Button) findViewById(R.id.btn_download);iv_img = (ImageView) findViewById(R.id.iv_img);}@Overridepublic void onClick(View v) {Bitmap b = getImgCache();if (b != null) {iv_img.setImageBitmap(b);} else {new Thread(new Runnable() {@Overridepublic void run() {if (HttpUtils.isNetConn(MainActivity.this)) {byte b[] = HttpUtils.getDateFromNet(imgPath);if (b != null && b.length != 0) {Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);Message msg = Message.obtain();msg.obj = bitmap;handler.sendMessage(msg);myLruCache.put(imgPath, bitmap);Log.d(TAG, "run: " + "緩存到強引用中成功");boolean bl = ExternalStorageUtils.storeToSDRoot("haha.jpg", b);if (bl) {Log.d(TAG, "run: " + "緩存到本地內存成功");} else {Log.d(TAG, "run: " + "緩存到本地內存失敗");}} else {Toast.makeText(MainActivity.this, "下載失敗!", Toast.LENGTH_SHORT).show();}} else {Toast.makeText(MainActivity.this, "請檢查你的網絡!", Toast.LENGTH_SHORT).show();}}}).start();}}/*** 從緩存中獲取圖片** @return 返回獲取到的Bitmap*/public Bitmap getImgCache() {Bitmap bitmap = myLruCache.get(imgPath);if (bitmap != null) {Log.d(TAG, "getImgCache: " + "從LruCache獲取圖片");} else {SoftReference<Bitmap> sr = cashMap.get(imgPath);if (sr != null) {bitmap = sr.get();myLruCache.put(imgPath, bitmap);cashMap.remove(imgPath);Log.d(TAG, "getImgCache: " + "從軟引用獲取圖片");} else {bitmap = ExternalStorageUtils.getImgFromSDRoot("haha.jpg");Log.d(TAG, "getImgCache: " + "從外部存儲獲取圖片");}}return bitmap;}/*** 自定義一個方法繼承系統的LruCache方法*/public class MyLruCache extends LruCache<String, Bitmap> {/*** 必須重寫的構造函數,定義強引用緩存區的大小* @param maxSize for caches that do not override {@link #sizeOf}, this is* the maximum number of entries in the cache. For all other caches,* this is the maximum sum of the sizes of the entries in this cache.*/public MyLruCache(int maxSize) {super(maxSize);}//返回每個圖片的大小@Overrideprotected int sizeOf(String key, Bitmap value) {//獲取當前變量每行的字節數和行高度(基本是固定寫法,記不住給我背!)return value.getRowBytes() * value.getHeight();}/*** 當LruCache中的數據被驅逐或是移除時回調的函數** @param evicted 當LruCache中的數據被驅逐用來給新的value倒出空間的時候變化* @param key 用來標示對象的鍵,一般put的時候傳入圖片的url地址* @param oldValue 之前存儲的舊的對象* @param newValue 存儲的新的對象*/@Overrideprotected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {if (evicted) {/*** 將舊的值存到軟引用中,因為強引用中可能有多個值被驅逐,* 所以創建一個LinkedHashMap<String, SoftReference<Bitmap>>來存儲軟引用* 基本也是固定寫法*/SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(oldValue);cashMap.put(key, softReference);}}}}

  基本的思路都在代碼注釋中寫的很詳細了,主要就是要自定義一個類,來繼承系統的LruCache,實現其中的兩個主要的方法sizeOf()和entryRemoved(),還有就是必須重寫它的構造函數。

以上所述是小編給大家介紹的Android中圖片的三級緩存機制的全部敘述,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的,在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东明县| 阿克陶县| 阜新市| 渭南市| 浦东新区| 阿拉善右旗| 临洮县| 柳州市| 翼城县| 汶上县| 信宜市| 上蔡县| 建阳市| 衡山县| 辽宁省| 夏河县| 洮南市| 西宁市| 无锡市| 太康县| 红桥区| 云浮市| 富宁县| 枝江市| 南靖县| 北海市| 理塘县| 德令哈市| 顺平县| 磐石市| 长春市| 平邑县| 怀集县| 崇义县| 河南省| 三穗县| 大同市| 长宁县| 兴宁市| 乌拉特中旗| 英超|