Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> android編程實現圖片庫的封裝方法

android編程實現圖片庫的封裝方法

編輯:Android開發實例

本文實例講述了android編程實現圖片庫的封裝方法。分享給大家供大家參考,具體如下:

大家在做安卓應用的時候 經常要從網絡中獲取圖片 都是通過URL去獲取 可是如果本地有圖片數據 從本地獲取數據不更加快一些 自己在工作中遇到這個問題 所以采用了一個URL和本地圖片的一個映射關系 先從本地區獲取 假如本地沒有再從網絡中獲取 本方法考慮到多線程問題 歡迎大家一起共同探討!

public class PictureLibrary {
 /*
  * 圖片庫的操作
  */
 File file;
 URL url;
 HttpURLConnection conn;
 InputStream is;
 FileOutputStream fos;
 private Lock lock = new ReentrantLock();
 private Condition downFile = lock.newCondition();
 // 通過URL將數據下載到本地操作
 private String toLocalFile(String strURL) {
  String fileName = Utils.getFileName(strURL);
  String path = Environment.getExternalStorageDirectory() + "/"
    + EcologicalTourism.FILE_PATH + "/images/" + fileName;
  return path;
 }
 // 通過URL將數據下載到本地臨時文件中
 private String toLocalFileTemp(String strURL) {
  String s = Utils.getFileName(strURL);
  String fileName = s+"temp";
  String path_url = Environment.getExternalStorageDirectory() + "/"
    + EcologicalTourism.FILE_PATH + "/tempimages/" + fileName;
  return path_url;
 }
 /*
  * 保存圖片到本地,並返回本地url(此函數是阻塞的)
  * main
  * @參數:strURL,參數為圖片的URL.返回值:該圖片在本地SD卡暫存的位置
  * 函數的工作是負責將圖片從互聯網上取得,存在本地存儲中,並返回本地存儲的文件路徑,供調用者直接使用。如果文件已經存在本地,直接返回
  * 如果文件未在本地,則直接從服務器下載,函數阻塞。
  */
 public String getReadSD(String strURL) {
  Log.i("test", "拿到網絡的地址是:" + strURL);
  String strLocalFile = toLocalFile(strURL); //k:把服務器URL轉換為本地URL
  String strLocalFileTemp = toLocalFileTemp(strURL); //k:把服務器URL轉換為本地臨時URL
  while (true) {
   File file = new File(strLocalFile);
   Log.i("test", "本地文件是:" + strLocalFile);
   File tfile = new File(strLocalFileTemp);
   Log.i("test", "臨時文件是:" + strLocalFileTemp);
   // 1上鎖
   lock.lock();
   if (file.exists()) {
    // 2if 本地文件存在
    // 解鎖
    // 返回本地路徑
    lock.unlock();
    Log.i("test", "返回本地路徑:" + file);
    return strLocalFile;
   } else if (tfile.exists()) {
    // if 對應的暫存文件存在
    // 解鎖
    lock.unlock();
    try {
     // 睡眠
     downFile.await();
    } catch (Exception e) {
      e.printStackTrace();
     Log.i("test", "e 出現了異常1" + e);
    }
   } else {
    try {
     // 創建對應的暫存文件
     tfile.createNewFile();
    } catch (IOException e) {
     Log.i("test", "e 出現了異常2" + e);
    }
    // 解鎖
    lock.unlock();
    // 下載文件內容到暫存文件中
    downURL2(strURL, strLocalFile);
    // 上鎖
    lock.lock();
    // 修改暫存文件名字為本地文件名
    tfile.renameTo(file);
    // 解鎖
    lock.unlock();
   }
  }
 }
 private void downURL2(String strURL, String strLocalFileTemp) {
  // TODO Auto-generated method stub
  URL url;
  try {
   url = new URL(strURL);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setConnectTimeout(5000);
   conn.setRequestMethod("GET");
   conn.setDoInput(true);
   if (conn.getResponseCode() == 200) {
     InputStream is = conn.getInputStream();
     FileOutputStream fos = new FileOutputStream(strLocalFileTemp);
     byte[] buffer = new byte[1024];
     int len = 0;
     while ((len = is.read(buffer)) != -1) {
       fos.write(buffer, 0, len);
     }
     is.close();
     fos.close();
     // 返回一個URI對象
   }
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 /*
  * 阻塞式下載url到文件 toFile中
  */
 private boolean downURL(String strURL, String toFile) {
  URL url;
  try {
   url = new URL(strURL);
   HttpURLConnection httpUrl = (HttpURLConnection) url
     .openConnection();
   httpUrl.setRequestMethod("GET");
   int fileSize = httpUrl.getContentLength();// 文件大小
   httpUrl.disconnect();// 關閉連接
   int threadSize = 6;// 默認設置6個線程
   threadSize = fileSize % threadSize == 0 ? threadSize
     : threadSize + 1;
   int currentSize = fileSize / threadSize; // 每條線程下載大小
   String dowloadir = Environment.getExternalStorageDirectory() + "/"
     + EcologicalTourism.FILE_PATH + "/images/";
   File dir = new File(dowloadir);
   if (!dir.exists()) {
    dir.mkdirs();
   }
   File file = new File(dir, toFile);
   RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
   randomFile.setLength(fileSize);// 指定 file 文件的大小
   for (int i = 0; i < threadSize; i++) {
    int startposition = i * currentSize;// 每條線程開始寫入文件的位置
    RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
    Log.i("syso", "toFile的內容是:" + toFile);
    threadFile.seek(startposition);
    new DownLoadThread(i, currentSize, threadFile, startposition,
      url).start();
   }
  } catch (Exception e) {
   e.printStackTrace();
   Log.i("syso", "download下載失敗" + e);
  }
  return true;
 }
 /**
  * 實現線程下載
  * 
  */
 private static class DownLoadThread extends Thread {
  @SuppressWarnings("unused")
  private int threadId;// 線程編號
  private int currentSize;// 每條線程的大小
  private RandomAccessFile threadFile; // 每條線程 要寫入文件類
  private int startposition;// 每條線程開始寫入文件的位置
  private URL url; //網絡地址
  public DownLoadThread(int threadId, int currentSize,
    RandomAccessFile threadFile, int startposition, URL url) {
   this.threadId = threadId;
   this.currentSize = currentSize;
   this.threadFile = threadFile;
   this.startposition = startposition;
   this.url = url;
  }
  public void run() {
   try {
    HttpURLConnection httpUrl = (HttpURLConnection) url
      .openConnection();
    httpUrl.setRequestMethod("GET");
    httpUrl.setRequestProperty("range", "bytes=" + startposition
      + "-");// 指定服務器的位置
    InputStream is = httpUrl.getInputStream();
    byte[] data = new byte[1024];
    int len = -1;
    int threadFileSize = 0;
    while ((threadFileSize < currentSize)
      && ((len = is.read(data)) != -1)) {
     threadFile.write(data, 0, len);
     threadFileSize += len;
    }
    httpUrl.disconnect();
    is.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 /**
 * 從本緩存中獲取圖片
 */
 public Bitmap getBitmapFromCache(String imageURL) {
 // String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1); 
  String bitmapName = Utils.getFileName(imageURL);
  File cacheDir = new File(Environment.getExternalStorageDirectory() + "/"
    + EcologicalTourism.FILE_PATH + "/images/");
  File[] cacheFiles = cacheDir.listFiles();
  int i = 0;
  if(null!=cacheFiles){
   for(; i<cacheFiles.length;i++){
    if(bitmapName.equals(cacheFiles[i].getName())){
     break;
    }
   }
   if(i < cacheFiles.length)
   {
    return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/"
      + EcologicalTourism.FILE_PATH + "/images/" + bitmapName);
   }
  }
  return null;
 }

希望本文所述對大家Android程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved