Ejemplo n.º 1
0
  /**
   * 执行网络请求加载图片
   *
   * @param url
   * @param requiredSize
   * @return
   */
  private Bitmap getBitmap(String url, int requiredSize, PhotoToLoad photoToLoad) {
    File f = fileCache.getFile(url);
    // 先从文件缓存中查找是否有
    Bitmap b = decodeFile(f, requiredSize);
    if (b != null) return b;

    // 最后从指定的url中下载图片
    try {
      Bitmap bitmap = null;
      URL imageUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setInstanceFollowRedirects(true);
      InputStream is = conn.getInputStream();
      OutputStream os = new FileOutputStream(f);
      //            CopyStream(is, os, conn.getContentLength(), photoToLoad);

      photoToLoad.totalSize = conn.getContentLength();
      int buffer_size = 1024;
      byte[] bytes = new byte[buffer_size];
      for (; ; ) {
        int count = is.read(bytes, 0, buffer_size);

        if (count == -1) {
          break;
        }
        os.write(bytes, 0, count);

        if (null != photoToLoad.onImageLoaderListener) { // 如果设置了图片加载监听,则回调
          Message msg = rHandler.obtainMessage();
          photoToLoad.currentSize += count;
          msg.arg1 = IMAGE_LOADER_PROCESS;
          msg.obj = photoToLoad;
          rHandler.sendMessage(msg);
        }
      }

      is.close();
      os.close();
      bitmap = decodeFile(f, requiredSize);
      return bitmap;
    } catch (Exception ex) {
      Logger.w(TAG, ex);
      return null;
    }
  }
Ejemplo n.º 2
0
    @Override
    public Object runInBackground() {
      PhotoToLoad photoToLoad = (PhotoToLoad) objs[0];
      int requiredSize = (Integer) objs[1];

      if (imageViewReused(photoToLoad)) { // 防止图片错位(如果加载的图片不是当前需要加载的图片,则不做任何处理)
        return null;
      }
      Bitmap bmp = getBitmap(photoToLoad.url, requiredSize, photoToLoad); // 网络加载图片
      memoryCache.put(photoToLoad.url, bmp);
      if (imageViewReused(photoToLoad)) { // 防止图片错位(如果加载的图片不是当前需要加载的图片,则不做任何处理)
        return null;
      }

      // 加载结束,更新UI
      Message msg = rHandler.obtainMessage();
      msg.arg1 = IMAGE_LOADER_FINISHED;
      photoToLoad.bitmap = bmp;
      msg.obj = photoToLoad;
      rHandler.sendMessage(msg);

      return null;
    }