天天看點

Android進階之緩存機制與實作

0 轉載部落格

Android 中的緩存機制與實作-本文版權歸煙台傑瑞教育科技有限公司和部落格園共有

1 問題描述

1.1 問題

  在正常情況下進入app首頁後,圖檔加載完成,接着退出app;然後斷開網絡,再進入app首頁,頁面顯示空白。為什麼?

1.1 問題

  Android開發本質上就是手機和網際網路中的web伺服器之間進行通信,就必然需要從服務端擷取資料,而反複通過網絡擷取資料是比較耗時的,特别是通路比較多的時候,會極大影響了性能;以及在斷網情況下Android擷取到的資料就為空。Android中可通過二級緩存來減少頻繁的網絡操作,減少流量、提升性能,緩存頁面的json資料。

2 二級緩存工作機制

  所謂二級緩存實際上并不複雜,當Android端需要獲得資料時比如擷取網絡中的圖檔,我們首先從記憶體中查找(按鍵查找),記憶體中沒有的再從磁盤檔案或sqlite中去查找,若磁盤中也沒有才通過網絡擷取;當獲得來自網絡的資料,就以key-value對的方式先緩存到記憶體(一級緩存),同時緩存到檔案或sqlite中(二級緩存)。注意:記憶體緩存會造成堆記憶體洩露,所有一級緩存通常要嚴格控制緩存的大小,一般控制在系統記憶體的1/4。

  了解了二級緩存大家可能會有個問題網絡中的資料是變化的,資料一旦放入緩存中,再取該資料就是從緩存中獲得,這樣豈不是不能展現資料的變化?我們在緩存資料時會設定有效時間,比如說30分鐘,若超過這個時間資料就失效并釋放空間,然後重新請求網絡中的資料。那麼30分鐘内咋辦?就下拉重新整理啦, 實際上這不是問題。

  

3 LruJsonCache介紹

3.1.1 LruJsonCache是一個為android制定的 輕量級的 開源緩存架構。輕量到隻有一個java檔案(由十幾個類精簡而來)。

3.1.2LruJsonCache可以緩存普通的字元串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java對象,和 byte資料。

3.1.3LruJsonCache特色主要是:

1️⃣輕,輕到隻有一個JAVA檔案。

2️⃣可配置,可以配置緩存路徑,緩存大小,緩存數量等。

3️⃣可以設定緩存逾時時間,緩存逾時自動失效,并被删除。

4️⃣支援多程序

3.1.4LruJsonCache在android中可以用在哪些場景

1️⃣替換SharePreference當做配置檔案

2️⃣可以緩存網絡請求資料,比如oschina的android用戶端可以緩存http請求的新聞内容,緩存時間假設為1個小時,逾時後自動失效,讓用戶端重新請求新的資料,減少用戶端流量,同時減少伺服器并發量。

4 LruJsonCache使用

public class NewsListActivity extends Activity {
  private List<News> list;
  private ListView listView;
  private LoadImageAdapter adapter;//擴充卡
  private LruJsonCache lruJsonCache;//緩存架構

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.load_img_listview_activity);

    //第1步:建立LruJsonCache元件
    lruJsonCache = LruJsonCache.get(this);

    initView();//初始化界面,代碼不貼了
}

public void loadData(){
   //第3步:從緩存中取資料
   String cacheData = lruJsonCache.getAsString("newsList");//從緩存中取資料

   if(cacheData! = null){//如果緩存中有,就不通路網絡
   List<News> newsList = gson.fromJson(cacheData, new TypeToken<List<News>>(){}.getType());//将json轉為List
      list.addAll(newsList);
      adapter.notifyDataSetChanged();
      return;
   }

   new Thread(new Runnable() {
     @Override
     public void run() {
       SystemClock.sleep();//模拟網絡耗時
       String json=request();//模拟從網絡中擷取json資料

       //第2步:設定緩存資料,有效時間設定為1小時
       lruJsonCache.put("newslist", json, **);

       List<News> newsList=gson.fromJson(json, new TypeToken<List<News>>(){}.getType());
       list.addAll(newsList);
       handler.sendEmptyMessage();
    }
  }).start();
}

    /**
     * 模拟網絡請求方法
     */
private String request(){
   News news=null;
   for(int i=;i<;i++){
       news=new News();
       news.setId(i);
       news.setImgUrl("course/img/face_"+i+".png");
       news.setTitle("新聞标題"+i);
       news.setSummary("測試"+i);
       list.add(news);
   }
   Gson gson=new Gson();
   return gson.toJson(list);    
}

private Handler handler=new Handler()
   @Override
   public void handleMessage(Message msg) {
       switch(msg.what){
           case :
             notify_layout.setVisibility(View.GONE);
             adapter.notifyDataSetChanged();
           break;
       }
   }
}
           

5 主要代碼解析

5.1 建立LruJsonCache元件

LruJsonCache lruJsonCache = LruJsonCache.get(context)
    LruJsonCache lruJsonCache = LruJsonCache.get(context,max_size,max_count)
    //max_size:設定限制緩存大小,預設為50M
    //max_count:設定緩存資料的數量,預設不限制 
           

5.2 設定緩存資料

//将資料同時上存入一級緩存(記憶體Map)和二級緩存(檔案)中
    lruJsonCache.put(key,data,time)
    acache.put(key,data)

    //Key:為存入緩存的資料設定唯一辨別,取資料時就根據key來獲得的
    //Data:要存入的資料,acache支援的資料類型如圖所示:
           
Android進階之緩存機制與實作

5.3 從緩存中取資料

提供一系列getAsXXX()方法,如圖所示

Android進階之緩存機制與實作

6 LruJsonCache代碼

package com.guesslive.caixiangji.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Json緩存工具
 * <p>
 * Created by chenliguan on 16/8/23.
 */
public class LruJsonCache {

    public static final int TIME_HOUR =  * ;
    public static final int TIME_DAY = TIME_HOUR * ;
    private static final int MAX_SIZE =  *  * ; // 50 mb
    private static final int MAX_COUNT = Integer.MAX_VALUE; // 不限制存放資料的數量
    private static Map<String, LruJsonCache> mInstanceMap = new HashMap<String, LruJsonCache>();
    private ACacheManager mCache;

    public static LruJsonCache get(Context ctx) {
        return get(ctx, "LruJsonCache");
    }

    public static LruJsonCache get(Context ctx, String cacheName) {
        File f = new File(ctx.getCacheDir(), cacheName);
        return get(f, MAX_SIZE, MAX_COUNT);
    }

    public static LruJsonCache get(File cacheDir) {
        return get(cacheDir, MAX_SIZE, MAX_COUNT);
    }

    public static LruJsonCache get(Context ctx, long max_zise, int max_count) {
        File f = new File(ctx.getCacheDir(), "LruJsonCache");
        return get(f, max_zise, max_count);
    }

    public static LruJsonCache get(File cacheDir, long max_zise, int max_count) {
        LruJsonCache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
        if (manager == null) {
            manager = new LruJsonCache(cacheDir, max_zise, max_count);
            mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
        }
        return manager;
    }

    private static String myPid() {
        return "_" + android.os.Process.myPid();
    }

    private LruJsonCache(File cacheDir, long max_size, int max_count) {
        if (!cacheDir.exists() && !cacheDir.mkdirs()) {
            throw new RuntimeException("can't make dirs in "
                    + cacheDir.getAbsolutePath());
        }
        mCache = new ACacheManager(cacheDir, max_size, max_count);
    }

    // =======================================
    // ============ String資料 讀寫 ==============
    // =======================================

    /**
     * 儲存 String資料 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的String資料
     */
    public void put(String key, String value) {
        File file = mCache.newFile(key);
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(file), );
            out.write(value);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mCache.put(file);
        }
    }

    /**
     * 儲存 String資料 到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的String資料
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, String value, int saveTime) {
        put(key, Utils.newStringWithDateInfo(saveTime, value));
    }

    /**
     * 讀取 String資料
     *
     * @param key
     * @return String 資料
     */
    public String getAsString(String key) {
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        boolean removeFile = false;
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(file));
            String readString = "";
            String currentLine;
            while ((currentLine = in.readLine()) != null) {
                readString += currentLine;
            }
            if (!Utils.isDue(readString)) {
                return Utils.clearDateInfo(readString);
            } else {
                removeFile = true;
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (removeFile)
                remove(key);
        }
    }

    // =======================================
    // ============= JSONObject 資料 讀寫 ==============
    // =======================================

    /**
     * 儲存 JSONObject資料 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的JSON資料
     */
    public void put(String key, JSONObject value) {
        put(key, value.toString());
    }

    /**
     * 儲存 JSONObject資料 到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的JSONObject資料
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, JSONObject value, int saveTime) {
        put(key, value.toString(), saveTime);
    }

    /**
     * 讀取JSONObject資料
     *
     * @param key
     * @return JSONObject資料
     */
    public JSONObject getAsJSONObject(String key) {
        String JSONString = getAsString(key);
        try {
            JSONObject obj = new JSONObject(JSONString);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // =======================================
    // ============ JSONArray 資料 讀寫 =============
    // =======================================

    /**
     * 儲存 JSONArray資料 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的JSONArray資料
     */
    public void put(String key, JSONArray value) {
        put(key, value.toString());
    }

    /**
     * 儲存 JSONArray資料 到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的JSONArray資料
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, JSONArray value, int saveTime) {
        put(key, value.toString(), saveTime);
    }

    /**
     * 讀取JSONArray資料
     *
     * @param key
     * @return JSONArray資料
     */
    public JSONArray getAsJSONArray(String key) {
        String JSONString = getAsString(key);
        try {
            JSONArray obj = new JSONArray(JSONString);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // =======================================
    // ============== byte 資料 讀寫 =============
    // =======================================

    /**
     * 儲存 byte資料 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的資料
     */
    public void put(String key, byte[] value) {
        File file = mCache.newFile(key);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mCache.put(file);
        }
    }

    /**
     * 儲存 byte資料 到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的資料
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, byte[] value, int saveTime) {
        put(key, Utils.newByteArrayWithDateInfo(saveTime, value));
    }

    /**
     * 擷取 byte 資料
     *
     * @param key
     * @return byte 資料
     */
    public byte[] getAsBinary(String key) {
        RandomAccessFile RAFile = null;
        boolean removeFile = false;
        try {
            File file = mCache.get(key);
            if (!file.exists())
                return null;
            RAFile = new RandomAccessFile(file, "r");
            byte[] byteArray = new byte[(int) RAFile.length()];
            RAFile.read(byteArray);
            if (!Utils.isDue(byteArray)) {
                return Utils.clearDateInfo(byteArray);
            } else {
                removeFile = true;
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (RAFile != null) {
                try {
                    RAFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (removeFile)
                remove(key);
        }
    }

    // =======================================
    // ============= 序列化 資料 讀寫 ===============
    // =======================================

    /**
     * 儲存 Serializable資料 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的value
     */
    public void put(String key, Serializable value) {
        put(key, value, -);
    }

    /**
     * 儲存 Serializable資料到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的value
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, Serializable value, int saveTime) {
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(value);
            byte[] data = baos.toByteArray();
            if (saveTime != -) {
                put(key, data, saveTime);
            } else {
                put(key, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 讀取 Serializable資料
     *
     * @param key
     * @return Serializable 資料
     */
    public Object getAsObject(String key) {
        byte[] data = getAsBinary(key);
        if (data != null) {
            ByteArrayInputStream bais = null;
            ObjectInputStream ois = null;
            try {
                bais = new ByteArrayInputStream(data);
                ois = new ObjectInputStream(bais);
                Object reObject = ois.readObject();
                return reObject;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if (bais != null)
                        bais.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (ois != null)
                        ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }

    // =======================================
    // ============== bitmap 資料 讀寫 =============
    // =======================================

    /**
     * 儲存 bitmap 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的bitmap資料
     */
    public void put(String key, Bitmap value) {
        put(key, Utils.Bitmap2Bytes(value));
    }

    /**
     * 儲存 bitmap 到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的 bitmap 資料
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, Bitmap value, int saveTime) {
        put(key, Utils.Bitmap2Bytes(value), saveTime);
    }

    /**
     * 讀取 bitmap 資料
     *
     * @param key
     * @return bitmap 資料
     */
    public Bitmap getAsBitmap(String key) {
        if (getAsBinary(key) == null) {
            return null;
        }
        return Utils.Bytes2Bimap(getAsBinary(key));
    }

    // =======================================
    // ============= drawable 資料 讀寫 =============
    // =======================================

    /**
     * 儲存 drawable 到 緩存中
     *
     * @param key   儲存的key
     * @param value 儲存的drawable資料
     */
    public void put(String key, Drawable value) {
        put(key, Utils.drawable2Bitmap(value));
    }

    /**
     * 儲存 drawable 到 緩存中
     *
     * @param key      儲存的key
     * @param value    儲存的 drawable 資料
     * @param saveTime 儲存的時間,機關:秒
     */
    public void put(String key, Drawable value, int saveTime) {
        put(key, Utils.drawable2Bitmap(value), saveTime);
    }

    /**
     * 讀取 Drawable 資料
     *
     * @param key
     * @return Drawable 資料
     */
    public Drawable getAsDrawable(String key) {
        if (getAsBinary(key) == null) {
            return null;
        }
        return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key)));
    }

    /**
     * 擷取緩存檔案
     *
     * @param key
     * @return value 緩存的檔案
     */
    public File file(String key) {
        File f = mCache.newFile(key);
        if (f.exists())
            return f;
        return null;
    }

    /**
     * 移除某個key
     *
     * @param key
     * @return 是否移除成功
     */
    public boolean remove(String key) {
        return mCache.remove(key);
    }

    /**
     * 清除所有資料
     */
    public void clear() {
        mCache.clear();
    }

    /**
     * @author 楊福海(michael) www.yangfuhai.com
     * @version 1.0
     * @title 緩存管理器
     */
    public class ACacheManager {
        private final AtomicLong cacheSize;
        private final AtomicInteger cacheCount;
        private final long sizeLimit;
        private final int countLimit;
        private final Map<File, Long> lastUsageDates = Collections
                .synchronizedMap(new HashMap<File, Long>());
        protected File cacheDir;

        private ACacheManager(File cacheDir, long sizeLimit, int countLimit) {
            this.cacheDir = cacheDir;
            this.sizeLimit = sizeLimit;
            this.countLimit = countLimit;
            cacheSize = new AtomicLong();
            cacheCount = new AtomicInteger();
            calculateCacheSizeAndCacheCount();
        }

        /**
         * 計算 cacheSize和cacheCount
         */
        private void calculateCacheSizeAndCacheCount() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int size = ;
                    int count = ;
                    File[] cachedFiles = cacheDir.listFiles();
                    if (cachedFiles != null) {
                        for (File cachedFile : cachedFiles) {
                            size += calculateSize(cachedFile);
                            count += ;
                            lastUsageDates.put(cachedFile,
                                    cachedFile.lastModified());
                        }
                        cacheSize.set(size);
                        cacheCount.set(count);
                    }
                }
            }).start();
        }

        private void put(File file) {
            int curCacheCount = cacheCount.get();
            while (curCacheCount +  > countLimit) {
                long freedSize = removeNext();
                cacheSize.addAndGet(-freedSize);

                curCacheCount = cacheCount.addAndGet(-);
            }
            cacheCount.addAndGet();

            long valueSize = calculateSize(file);
            long curCacheSize = cacheSize.get();
            while (curCacheSize + valueSize > sizeLimit) {
                long freedSize = removeNext();
                curCacheSize = cacheSize.addAndGet(-freedSize);
            }
            cacheSize.addAndGet(valueSize);

            Long currentTime = System.currentTimeMillis();
            file.setLastModified(currentTime);
            lastUsageDates.put(file, currentTime);
        }

        private File get(String key) {
            File file = newFile(key);
            Long currentTime = System.currentTimeMillis();
            file.setLastModified(currentTime);
            lastUsageDates.put(file, currentTime);

            return file;
        }

        private File newFile(String key) {
            return new File(cacheDir, key.hashCode() + "");
        }

        private boolean remove(String key) {
            File image = get(key);
            return image.delete();
        }

        private void clear() {
            lastUsageDates.clear();
            cacheSize.set();
            File[] files = cacheDir.listFiles();
            if (files != null) {
                for (File f : files) {
                    f.delete();
                }
            }
        }

        /**
         * 移除舊的檔案
         */
        private long removeNext() {
            if (lastUsageDates.isEmpty()) {
                return ;
            }

            Long oldestUsage = null;
            File mostLongUsedFile = null;
            Set<Map.Entry<File, Long>> entries = lastUsageDates.entrySet();
            synchronized (lastUsageDates) {
                for (Map.Entry<File, Long> entry : entries) {
                    if (mostLongUsedFile == null) {
                        mostLongUsedFile = entry.getKey();
                        oldestUsage = entry.getValue();
                    } else {
                        Long lastValueUsage = entry.getValue();
                        if (lastValueUsage < oldestUsage) {
                            oldestUsage = lastValueUsage;
                            mostLongUsedFile = entry.getKey();
                        }
                    }
                }
            }

            long fileSize = calculateSize(mostLongUsedFile);
            if (mostLongUsedFile.delete()) {
                lastUsageDates.remove(mostLongUsedFile);
            }
            return fileSize;
        }

        private long calculateSize(File file) {
            return file.length();
        }
    }

    /**
     * @author www.yangfuhai.com
     * @version 1.0
     * @title 時間計算工具類
     */
    private static class Utils {

        /**
         * 判斷緩存的String資料是否到期
         *
         * @param str
         * @return true:到期了 false:還沒有到期
         */
        private static boolean isDue(String str) {
            return isDue(str.getBytes());
        }

        /**
         * 判斷緩存的byte資料是否到期
         *
         * @param data
         * @return true:到期了 false:還沒有到期
         */
        private static boolean isDue(byte[] data) {
            String[] strs = getDateInfoFromDate(data);
            if (strs != null && strs.length == ) {
                String saveTimeStr = strs[];
                while (saveTimeStr.startsWith("0")) {
                    saveTimeStr = saveTimeStr
                            .substring(, saveTimeStr.length());
                }
                long saveTime = Long.valueOf(saveTimeStr);
                long deleteAfter = Long.valueOf(strs[]);
                if (System.currentTimeMillis() > saveTime + deleteAfter * ) {
                    return true;
                }
            }
            return false;
        }

        private static String newStringWithDateInfo(int second, String strInfo) {
            return createDateInfo(second) + strInfo;
        }

        private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) {
            byte[] data1 = createDateInfo(second).getBytes();
            byte[] retdata = new byte[data1.length + data2.length];
            System.arraycopy(data1, , retdata, , data1.length);
            System.arraycopy(data2, , retdata, data1.length, data2.length);
            return retdata;
        }

        private static String clearDateInfo(String strInfo) {
            if (strInfo != null && hasDateInfo(strInfo.getBytes())) {
                strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + ,
                        strInfo.length());
            }
            return strInfo;
        }

        private static byte[] clearDateInfo(byte[] data) {
            if (hasDateInfo(data)) {
                return copyOfRange(data, indexOf(data, mSeparator) + ,
                        data.length);
            }
            return data;
        }

        private static boolean hasDateInfo(byte[] data) {
            return data != null && data.length >  && data[] == '-'
                    && indexOf(data, mSeparator) > ;
        }

        private static String[] getDateInfoFromDate(byte[] data) {
            if (hasDateInfo(data)) {
                String saveDate = new String(copyOfRange(data, , ));
                String deleteAfter = new String(copyOfRange(data, ,
                        indexOf(data, mSeparator)));
                return new String[]{saveDate, deleteAfter};
            }
            return null;
        }

        private static int indexOf(byte[] data, char c) {
            for (int i = ; i < data.length; i++) {
                if (data[i] == c) {
                    return i;
                }
            }
            return -;
        }

        private static byte[] copyOfRange(byte[] original, int from, int to) {
            int newLength = to - from;
            if (newLength < )
                throw new IllegalArgumentException(from + " > " + to);
            byte[] copy = new byte[newLength];
            System.arraycopy(original, from, copy, ,
                    Math.min(original.length - from, newLength));
            return copy;
        }

        private static final char mSeparator = ' ';

        private static String createDateInfo(int second) {
            String currentTime = System.currentTimeMillis() + "";
            while (currentTime.length() < ) {
                currentTime = "0" + currentTime;
            }
            return currentTime + "-" + second + mSeparator;
        }

        /*
         * Bitmap → byte[]
         */
        private static byte[] Bitmap2Bytes(Bitmap bm) {
            if (bm == null) {
                return null;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, , baos);
            return baos.toByteArray();
        }

        /*
         * byte[] → Bitmap
         */
        private static Bitmap Bytes2Bimap(byte[] b) {
            if (b.length == ) {
                return null;
            }
            return BitmapFactory.decodeByteArray(b, , b.length);
        }

        /*
         * Drawable → Bitmap
         */
        private static Bitmap drawable2Bitmap(Drawable drawable) {
            if (drawable == null) {
                return null;
            }
            // 取 drawable 的長寬
            int w = drawable.getIntrinsicWidth();
            int h = drawable.getIntrinsicHeight();
            // 取 drawable 的顔色格式
            Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                    : Bitmap.Config.RGB_565;
            // 建立對應 bitmap
            Bitmap bitmap = Bitmap.createBitmap(w, h, config);
            // 建立對應 bitmap 的畫布
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(, , w, h);
            // 把 drawable 内容畫到畫布中
            drawable.draw(canvas);
            return bitmap;
        }

        /*
         * Bitmap → Drawable
         */
        @SuppressWarnings("deprecation")
        private static Drawable bitmap2Drawable(Bitmap bm) {
            if (bm == null) {
                return null;
            }
            return new BitmapDrawable(bm);
        }
    }
}
           

繼續閱讀