android的缓存策略

 具体代码如下:

[java]  view plain  copy
  1. <span style="color:#333300;">package com.jingchen.tbviewer.utils;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.ObjectInputStream;  
  9. import java.io.ObjectOutputStream;  
  10. import java.io.StreamCorruptedException;  
  11. import java.nio.channels.FileChannel;  
  12. import java.util.ArrayList;  
  13. import java.util.List;  
  14. import android.content.Context;  
  15. import android.os.Environment;  
  16.   
  17. public class CacheUtils {  
  18.   
  19.     private static File CacheRoot;  
  20.   
  21.     /** 
  22.      * 存储Json文件 
  23.      *  
  24.      * @param context 
  25.      * @param json 
  26.      *            json字符串 
  27.      * @param fileName 
  28.      *            存储的文件名 
  29.      * @param append 
  30.      *            true 增加到文件末,false则覆盖掉原来的文件 
  31.      */  
  32.     public static void writeJson(Context c, String json, String fileName,  
  33.             boolean append) {  
  34.   
  35.         CacheRoot = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? c  
  36.                 .getExternalCacheDir() : c.getCacheDir();  
  37.         FileOutputStream fos = null;  
  38.         ObjectOutputStream os = null;  
  39.         try {  
  40.             File ff = new File(CacheRoot, fileName);  
  41.             boolean boo = ff.exists();  
  42.             fos = new FileOutputStream(ff, append);  
  43.             os = new ObjectOutputStream(fos);  
  44.             if (append && boo) {  
  45.                 FileChannel fc = fos.getChannel();  
  46.                 fc.truncate(fc.position() - 4);  
  47.   
  48.             }  
  49.   
  50.             os.writeObject(json);  
  51.   
  52.         } catch (FileNotFoundException e) {  
  53.             // TODO Auto-generated catch block  
  54.             e.printStackTrace();  
  55.         } catch (IOException e) {  
  56.             // TODO Auto-generated catch block  
  57.             e.printStackTrace();  
  58.         } finally {  
  59.   
  60.             if (fos != null) {  
  61.                 try {  
  62.                     fos.close();  
  63.                 } catch (IOException e) {  
  64.                     // TODO Auto-generated catch block  
  65.                     e.printStackTrace();  
  66.                 }  
  67.   
  68.             }  
  69.             if (os != null) {  
  70.   
  71.                 try {  
  72.                     os.close();  
  73.                 } catch (IOException e) {  
  74.                     // TODO Auto-generated catch block  
  75.                     e.printStackTrace();  
  76.                 }  
  77.             }  
  78.   
  79.         }  
  80.   
  81.     }  
  82.   
  83.     /** 
  84.      * 读取json数据 
  85.      *  
  86.      * @param c 
  87.      * @param fileName 
  88.      * @return 返回值为list 
  89.      */  
  90.   
  91.     @SuppressWarnings("resource")  
  92.     public static List<String> readJson(Context c, String fileName) {  
  93.   
  94.         CacheRoot = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? c  
  95.                 .getExternalCacheDir() : c.getCacheDir();  
  96.         FileInputStream fis = null;  
  97.         ObjectInputStream ois = null;  
  98.         List<String> result = new ArrayList<String>();  
  99.         File des = new File(CacheRoot, fileName);  
  100.         try {  
  101.             fis = new FileInputStream(des);  
  102.             ois = new ObjectInputStream(fis);  
  103.             while (fis.available() > 0)  
  104.                 result.add((String) ois.readObject());  
  105.   
  106.         } catch (FileNotFoundException e) {  
  107.             // TODO Auto-generated catch block  
  108.             e.printStackTrace();  
  109.         } catch (StreamCorruptedException e) {  
  110.             // TODO Auto-generated catch block  
  111.             e.printStackTrace();  
  112.         } catch (IOException e) {  
  113.             // TODO Auto-generated catch block  
  114.             e.printStackTrace();  
  115.         } catch (ClassNotFoundException e) {  
  116.             // TODO Auto-generated catch block  
  117.             e.printStackTrace();  
  118.         } finally {  
  119.             if (fis != null) {  
  120.                 try {  
  121.                     fis.close();  
  122.                 } catch (IOException e) {  
  123.                     // TODO Auto-generated catch block  
  124.                     e.printStackTrace();  
  125.                 }  
  126.             }  
  127.   
  128.             if (ois != null) {  
  129.                 try {  
  130.                     ois.close();  
  131.                 } catch (IOException e) {  
  132.                     // TODO Auto-generated catch block  
  133.                     e.printStackTrace();  
  134.                 }  
  135.             }  
  136.   
  137.         }  
  138.   
  139.         return result;  
  140.     }  
  141.   
  142. }</span><strong style="color: rgb(255, 0, 0);">  
  143. </strong>  




  1. 3.代码ImageManager.java 
    复制代码代码如下:

    /* 
    * 图片管理 
    * 异步获取图片,直接调用loadImage()函数,该函数自己判断是从缓存还是网络加载 
    * 同步获取图片,直接调用getBitmap()函数,该函数自己判断是从缓存还是网络加载 
    * 仅从本地获取图片,调用getBitmapFromNative() 
    * 仅从网络加载图片,调用getBitmapFromHttp() 

    */ 
    public class ImageManager implements IManager 

    private final static String TAG = "ImageManager"; 

    private ImageMemoryCache imageMemoryCache; //内存缓存 

    private ImageFileCache imageFileCache; //文件缓存 

    //正在下载的image列表 
    public static HashMap<String, Handler> ongoingTaskMap = new HashMap<String, Handler>(); 

    //等待下载的image列表 
    public static HashMap<String, Handler> waitingTaskMap = new HashMap<String, Handler>(); 

    //同时下载图片的线程个数 
    final static int MAX_DOWNLOAD_IMAGE_THREAD = 4; 

    private final Handler downloadStatusHandler = new Handler(){ 
    public void handleMessage(Message msg) 

    startDownloadNext(); 

    }; 

    public ImageManager() 

    imageMemoryCache = new ImageMemoryCache(); 
    imageFileCache = new ImageFileCache(); 


    /** 
    * 获取图片,多线程的入口 
    */ 
    public void loadBitmap(String url, Handler handler) 

    //先从内存缓存中获取,取到直接加载 
    Bitmap bitmap = getBitmapFromNative(url); 
    if (bitmap != null) 

    Logger.d(TAG, "loadBitmap:loaded from native"); 
    Message msg = Message.obtain(); 
    Bundle bundle = new Bundle(); 
    bundle.putString("url", url); 
    msg.obj = bitmap; 
    msg.setData(bundle); 
    handler.sendMessage(msg); 

    else 

    Logger.d(TAG, "loadBitmap:will load by network"); 
    downloadBmpOnNewThread(url, handler); 


    /** 
    * 新起线程下载图片 
    */ 
    private void downloadBmpOnNewThread(final String url, final Handler handler) 

    Logger.d(TAG, "ongoingTaskMap'size=" + ongoingTaskMap.size()); 

    if (ongoingTaskMap.size() >= MAX_DOWNLOAD_IMAGE_THREAD) 

    synchronized (waitingTaskMap) 

    waitingTaskMap.put(url, handler); 


    else 

    synchronized (ongoingTaskMap) 

    ongoingTaskMap.put(url, handler); 

    new Thread() 

    public void run() 

    Bitmap bmp = getBitmapFromHttp(url); 
    // 不论下载是否成功,都从下载队列中移除,再由业务逻辑判断是否重新下载 
    // 下载图片使用了httpClientRequest,本身已经带了重连机制 
    synchronized (ongoingTaskMap) 

    ongoingTaskMap.remove(url); 


    if(downloadStatusHandler != null) 

    downloadStatusHandler.sendEmptyMessage(0); 


    Message msg = Message.obtain(); 
    msg.obj = bmp; 
    Bundle bundle = new Bundle(); 
    bundle.putString("url", url); 
    msg.setData(bundle); 

    if(handler != null) 

    handler.sendMessage(msg); 


    }.start(); 


    /** 
    * 依次从内存,缓存文件,网络上加载单个bitmap,不考虑线程的问题 
    */ 
    public Bitmap getBitmap(String url) 

    // 从内存缓存中获取图片 
    Bitmap bitmap = imageMemoryCache.getBitmapFromMemory(url); 
    if (bitmap == null) 

    // 文件缓存中获取 
    bitmap = imageFileCache.getImageFromFile(url); 
    if (bitmap != null) 

    // 添加到内存缓存 
    imageMemoryCache.addBitmapToMemory(url, bitmap); 

    else 

    // 从网络获取 
    bitmap = getBitmapFromHttp(url); 


    return bitmap; 


    /** 
    * 从内存或者缓存文件中获取bitmap 
    */ 
    public Bitmap getBitmapFromNative(String url) 

    Bitmap bitmap = null; 
    bitmap = imageMemoryCache.getBitmapFromMemory(url); 

    if(bitmap == null) 

    bitmap = imageFileCache.getImageFromFile(url); 
    if(bitmap != null) 

    // 添加到内存缓存 
    imageMemoryCache.addBitmapToMemory(url, bitmap); 


    return bitmap; 


    /** 
    * 通过网络下载图片,与线程无关 
    */ 
    public Bitmap getBitmapFromHttp(String url) 

    Bitmap bmp = null; 

    try 

    byte[] tmpPicByte = getImageBytes(url); 

    if (tmpPicByte != null) 

    bmp = BitmapFactory.decodeByteArray(tmpPicByte, 0, 
    tmpPicByte.length); 

    tmpPicByte = null; 

    catch(Exception e) 

    e.printStackTrace(); 


    if(bmp != null) 

    // 添加到文件缓存 
    imageFileCache.saveBitmapToFile(bmp, url); 
    // 添加到内存缓存 
    imageMemoryCache.addBitmapToMemory(url, bmp); 

    return bmp; 


    /** 
    * 下载链接的图片资源 

    * @param url 

    * @return 图片 
    */ 
    public byte[] getImageBytes(String url) 

    byte[] pic = null; 
    if (url != null && !"".equals(url)) 

    Requester request = RequesterFactory.getRequester( 
    Requester.REQUEST_REMOTE, RequesterFactory.IMPL_HC); 
    // 执行请求 
    MyResponse myResponse = null; 
    MyRequest mMyRequest; 
    mMyRequest = new MyRequest(); 
    mMyRequest.setUrl(url); 
    mMyRequest.addHeader(HttpHeader.REQ.ACCEPT_ENCODING, "identity"); 
    InputStream is = null; 
    ByteArrayOutputStream baos = null; 
    try { 
    myResponse = request.execute(mMyRequest); 
    is = myResponse.getInputStream().getImpl(); 
    baos = new ByteArrayOutputStream(); 
    byte[] b = new byte[512]; 
    int len = 0; 
    while ((len = is.read(b)) != -1) 

    baos.write(b, 0, len); 
    baos.flush(); 

    pic = baos.toByteArray(); 
    Logger.d(TAG, "icon bytes.length=" + pic.length); 

    catch (Exception e3) 

    e3.printStackTrace(); 
    try 

    Logger.e(TAG, 
    "download shortcut icon faild and responsecode=" 
    + myResponse.getStatusCode()); 

    catch (Exception e4) 

    e4.printStackTrace(); 


    finally 

    try 

    if (is != null) 

    is.close(); 
    is = null; 


    catch (Exception e2) 

    e2.printStackTrace(); 

    try 

    if (baos != null) 

    baos.close(); 
    baos = null; 


    catch (Exception e2) 

    e2.printStackTrace(); 

    try 

    request.close(); 

    catch (Exception e1) 

    e1.printStackTrace(); 



    return pic; 


    /** 
    * 取出等待队列第一个任务,开始下载 
    */ 
    private void startDownloadNext() 

    synchronized(waitingTaskMap) 

    Logger.d(TAG, "begin start next"); 
    Iterator iter = waitingTaskMap.entrySet().iterator(); 

    while (iter.hasNext()) 


    Map.Entry entry = (Map.Entry) iter.next(); 
    Logger.d(TAG, "WaitingTaskMap isn't null,url=" + (String)entry.getKey()); 

    if(entry != null) 

    waitingTaskMap.remove(entry.getKey()); 
    downloadBmpOnNewThread((String)entry.getKey(), (Handler)entry.getValue()); 

    break; 




    public String startDownloadNext_ForUnitTest() 

    String urlString = null; 
    synchronized(waitingTaskMap) 

    Logger.d(TAG, "begin start next"); 
    Iterator iter = waitingTaskMap.entrySet().iterator(); 

    while (iter.hasNext()) 

    Map.Entry entry = (Map.Entry) iter.next(); 
    urlString = (String)entry.getKey(); 
    waitingTaskMap.remove(entry.getKey()); 
    break; 


    return urlString; 


    /** 
    * 图片变为圆角 
    * @param bitmap:传入的bitmap 
    * @param pixels:圆角的度数,值越大,圆角越大 
    * @return bitmap:加入圆角的bitmap 
    */ 
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) 

    if(bitmap == null) 
    return null; 
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(output); 
    final int color = 0xff424242; 
    final Paint paint = new Paint(); 
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 
    final RectF rectF = new RectF(rect); 
    final float roundPx = pixels; 
    paint.setAntiAlias(true); 
    canvas.drawARGB(0, 0, 0, 0); 
    paint.setColor(color); 
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 
    canvas.drawBitmap(bitmap, rect, rect, paint); 
    return output; 


    public byte managerId() 

    return IMAGE_ID; 







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值