private static Handler defineHandler(DisplayImageOptions options) {
   Handler handler = options.getHandler();
   if (options.isSyncLoading()) {
     handler = null;
   } else if (handler == null && Looper.myLooper() == Looper.getMainLooper()) {
     handler = new Handler();
   }
   return handler;
 }
 /** @return <b>true</b> - if task should be interrupted; <b>false</b> - otherwise */
 private boolean delayIfNeed() {
   if (options.shouldDelayBeforeLoading()) {
     log(LOG_DELAY_BEFORE_LOADING, options.getDelayBeforeLoading(), memoryCacheKey);
     try {
       Thread.sleep(options.getDelayBeforeLoading());
     } catch (InterruptedException e) {
       L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
       return true;
     }
     return isTaskNotActual();
   }
   return false;
 }
Exemplo n.º 3
0
  /**
   * 初始化UIL配置
   *
   * @param context
   */
  public void initImageLoader(Context context) {
    File file =
        new File(getApplicationContext().getExternalCacheDir() + "/logisticforUser", "images");

    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(context)
            .threadPoolSize(5)
            // 线程池内加载的数量
            .threadPriority(3)
            .denyCacheImageMultipleSizesInMemory()
            .memoryCache(new LruMemoryCache(10 * 1024 * 1024))
            .memoryCacheSize(10 * 1024 * 1024)
            .diskCache(new UnlimitedDiscCache(file))
            .diskCacheSize(100 * 1024 * 1024)
            .diskCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.FIFO)
            .diskCacheFileCount(1000)
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .imageDownloader(
                new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout
            // (5
            // s),
            // readTimeout
            // (30
            // s)超时时间
            // .writeDebugLogs() // Remove for release app
            .build(); // 开始构建

    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config);
  }
Exemplo n.º 4
0
 public static void initImageLoader(Context context) {
   // 配置图片缓存路径
   File cacheDir = StorageUtils.getOwnCacheDirectory(context, "IMG/cache");
   // 配置ImageLoaderConfiguration
   ImageLoaderConfiguration config =
       new ImageLoaderConfiguration.Builder(context)
           // max width, max,height,即保存的每个缓存文件的最大长宽
           // .memoryCacheExtraOptions(400, 400)
           // 线程池内加载的数量
           .threadPoolSize(3)
           // 线程优先级
           .threadPriority(Thread.NORM_PRIORITY)
           // 硬盘缓存50MB
           .discCacheSize(50 * 1024 * 1024)
           // 将保存的时候的URI名称用MD5
           .discCacheFileNameGenerator(new Md5FileNameGenerator())
           // 将保存的时候的URI名称用HASHCODE加密
           .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
           .tasksProcessingOrder(QueueProcessingType.LIFO)
           // 缓存的File数量
           .discCacheFileCount(100)
           // 自定义缓存路径
           .discCache(new UnlimitedDiscCache(cacheDir))
           // 设置图片显示配置
           .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
           // connectTimeout (5 s), readTimeout (30 s)超时时间
           .imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000))
           .build();
   ImageLoader.getInstance().init(config);
 }
  @Override
  public void onCreate() {
    super.onCreate();

    // force AsyncTask to be initialized in the main thread due to the bug:
    // http://stackoverflow.com/questions/4280330/onpostexecute-not-being-called-in-asynctask-handler-runtime-exception
    try {
      Class.forName("android.os.AsyncTask");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    // init image caching
    File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
    cacheDir.mkdirs(); // requires android.permission.WRITE_EXTERNAL_STORAGE

    try {
      ImageLoaderConfiguration config =
          new ImageLoaderConfiguration.Builder(getApplicationContext())
              .threadPoolSize(3)
              .threadPriority(Thread.NORM_PRIORITY - 2)
              .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
              .diskCache(
                  new LruDiscCache(cacheDir, new HashCodeFileNameGenerator(), 32 * 1024 * 1024))
              .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
              .build();

      ImageLoader.getInstance().init(config);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  private Bitmap decodeWithOOMHandling(URI imageUri) throws IOException {
    Bitmap result = null;
    ImageDecoder decoder = new ImageDecoder(imageUri, downloader, options);
    decoder.setLoggingEnabled(loggingEnabled);
    for (int attempt = 1; attempt <= ATTEMPT_COUNT_TO_DECODE_BITMAP; attempt++) {
      try {
        ViewScaleType viewScaleType = ViewScaleType.fromImageView(imageView);
        result = decoder.decode(targetSize, options.getImageScaleType(), viewScaleType);
      } catch (OutOfMemoryError e) {
        L.e(e);

        switch (attempt) {
          case 1:
            System.gc();
            break;
          case 2:
            configuration.memoryCache.clear();
            System.gc();
            break;
          case 3:
            throw e;
        }
        // Wait some time while GC is working
        SystemClock.sleep(attempt * 1000);
        continue;
      }
      break;
    }
    return result;
  }
 private void fireCancelEvent() {
   if (options.isSyncLoading() || isTaskInterrupted()) return;
   handler.post(
       new Runnable() {
         @Override
         public void run() {
           listener.onLoadingCancelled(uri, imageAware.getWrappedView());
         }
       });
 }
 private void downloadImage(File targetFile) throws IOException {
   InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
   try {
     OutputStream os = new BufferedOutputStream(new FileOutputStream(targetFile), BUFFER_SIZE);
     try {
       IoUtils.copyStream(is, os);
     } finally {
       IoUtils.closeSilently(os);
     }
   } finally {
     IoUtils.closeSilently(is);
   }
 }
  private Bitmap decodeImage(URI imageUri) throws IOException {
    Bitmap bmp = null;

    if (configuration.handleOutOfMemory) {
      bmp = decodeWithOOMHandling(imageUri);
    } else {
      ImageDecoder decoder = new ImageDecoder(imageUri, downloader, options);
      decoder.setLoggingEnabled(loggingEnabled);
      ViewScaleType viewScaleType = ViewScaleType.fromImageView(imageView);
      bmp = decoder.decode(targetSize, options.getImageScaleType(), viewScaleType);
    }
    return bmp;
  }
 private void fireFailEvent(final FailType failType, final Throwable failCause) {
   if (options.isSyncLoading() || isTaskInterrupted() || isTaskNotActual()) return;
   handler.post(
       new Runnable() {
         @Override
         public void run() {
           if (options.shouldShowImageOnFail()) {
             imageAware.setImageDrawable(options.getImageOnFail(configuration.resources));
           }
           listener.onLoadingFailed(
               uri, imageAware.getWrappedView(), new FailReason(failType, failCause));
         }
       });
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.category_grid);
    Dialoge.runDialog(5, this);
    Bundle bundle = getIntent().getExtras();
    // imageUrls = bundle.getStringArray(Extra.IMAGES);
    // ---imageUrls = JsonToElement.getImageUrlById();

    //	pCategories = new ArrayList<ModelWPCategory>();
    imageUrls = new String[Imageurl.newyearsvalues.size()];
    for (int i = 0; i < Imageurl.newyearsvalues.size(); i++) {
      /*ModelWPCategory modelWPCategory = new ModelWPCategory();
      modelWPCategory = wpCategories.get(i);*/
      //	categoryNames[i]= Imageurl.newyearsvalues.get(i);
      imageUrls[i] = Imageurl.newyearsvalues.get(i);
      ;
    }

    cacheDir = new File(Environment.getExternalStorageDirectory(), ConstantValues.CACHE_DIR); // --
    // Create configuration for ImageLoader
    config =
        new ImageLoaderConfiguration.Builder(this)
            .discCache(new UnlimitedDiscCache(cacheDir))
            .memoryCache(new UsingFreqLimitedMemoryCache(2000000))
            .denyCacheImageMultipleSizesInMemory()
            .threadPriority(Thread.MIN_PRIORITY + 2)
            .threadPoolSize(5)
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .build(); // --
    options =
        new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.stub_image)
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheInMemory()
            .cacheOnDisc()
            .build();

    imageLoader.init(config);
    gridView = (GridView) findViewById(R.id.gridview_category);
    gridView.setAdapter(new ImageAdapter());
    gridView.setOnItemClickListener(
        new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            startBasicGridActivity(position);
          }
        });
  }
  private Bitmap tryLoadBitmap() {
    DiscCacheAware discCache = configuration.discCache;
    File imageFile = discCache.get(uri);

    Bitmap bitmap = null;
    try {
      // Try to load image from disc cache
      if (imageFile.exists()) {
        log(LOG_LOAD_IMAGE_FROM_DISC_CACHE, memoryCacheKey);

        Bitmap b = decodeImage(imageFile.toURI());
        if (b != null) {
          return b;
        }
      }

      // Load image from Web
      log(LOG_LOAD_IMAGE_FROM_INTERNET, memoryCacheKey);

      URI imageUriForDecoding;
      if (options.isCacheOnDisc()) {
        log(LOG_CACHE_IMAGE_ON_DISC, memoryCacheKey);

        saveImageOnDisc(imageFile);
        discCache.put(uri, imageFile);
        imageUriForDecoding = imageFile.toURI();
      } else {
        imageUriForDecoding = new URI(uri);
      }

      bitmap = decodeImage(imageUriForDecoding);
      if (bitmap == null) {
        fireImageLoadingFailedEvent(FailReason.IO_ERROR);
      }
    } catch (IOException e) {
      L.e(e);
      fireImageLoadingFailedEvent(FailReason.IO_ERROR);
      if (imageFile.exists()) {
        imageFile.delete();
      }
    } catch (OutOfMemoryError e) {
      L.e(e);
      fireImageLoadingFailedEvent(FailReason.OUT_OF_MEMORY);
    } catch (Throwable e) {
      L.e(e);
      fireImageLoadingFailedEvent(FailReason.UNKNOWN);
    }
    return bitmap;
  }
  private Bitmap tryLoadBitmap() throws TaskCancelledException {
    File imageFile = getImageFileInDiscCache();

    Bitmap bitmap = null;
    try {
      String cacheFileUri = Scheme.FILE.wrap(imageFile.getAbsolutePath());
      if (imageFile.exists()) {
        log(LOG_LOAD_IMAGE_FROM_DISC_CACHE);
        loadedFrom = LoadedFrom.DISC_CACHE;

        checkTaskNotActual();
        bitmap = decodeImage(cacheFileUri);
      }
      if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
        log(LOG_LOAD_IMAGE_FROM_NETWORK);
        loadedFrom = LoadedFrom.NETWORK;

        String imageUriForDecoding =
            options.isCacheOnDisc() && tryCacheImageOnDisc(imageFile) ? cacheFileUri : uri;

        checkTaskNotActual();
        bitmap = decodeImage(imageUriForDecoding);

        if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
          fireFailEvent(FailType.DECODING_ERROR, null);
        }
      }
    } catch (IllegalStateException e) {
      fireFailEvent(FailType.NETWORK_DENIED, null);
    } catch (TaskCancelledException e) {
      throw e;
    } catch (IOException e) {
      L.e(e);
      fireFailEvent(FailType.IO_ERROR, e);
      if (imageFile.exists()) {
        imageFile.delete();
      }
    } catch (OutOfMemoryError e) {
      L.e(e);
      fireFailEvent(FailType.OUT_OF_MEMORY, e);
    } catch (Throwable e) {
      L.e(e);
      fireFailEvent(FailType.UNKNOWN, e);
    }
    return bitmap;
  }
 private void initEmptyFieldsWithDefaultValues()
 {
     if (taskExecutor == null)
     {
         taskExecutor = DefaultConfigurationFactory.createExecutor(threadPoolSize, threadPriority, tasksProcessingType);
     } else
     {
         customExecutor = true;
     }
     if (taskExecutorForCachedImages == null)
     {
         taskExecutorForCachedImages = DefaultConfigurationFactory.createExecutor(threadPoolSize, threadPriority, tasksProcessingType);
     } else
     {
         customExecutorForCachedImages = true;
     }
     if (diskCache == null)
     {
         if (diskCacheFileNameGenerator == null)
         {
             diskCacheFileNameGenerator = DefaultConfigurationFactory.createFileNameGenerator();
         }
         diskCache = DefaultConfigurationFactory.createDiskCache(context, diskCacheFileNameGenerator, diskCacheSize, diskCacheFileCount);
     }
     if (memoryCache == null)
     {
         memoryCache = DefaultConfigurationFactory.createMemoryCache(memoryCacheSize);
     }
     if (denyCacheImageMultipleSizesInMemory)
     {
         memoryCache = new FuzzyKeyMemoryCache(memoryCache, MemoryCacheUtils.createFuzzyKeyComparator());
     }
     if (downloader == null)
     {
         downloader = DefaultConfigurationFactory.createImageDownloader(context);
     }
     if (decoder == null)
     {
         decoder = DefaultConfigurationFactory.createImageDecoder(writeLogs);
     }
     if (defaultDisplayImageOptions == null)
     {
         defaultDisplayImageOptions = DisplayImageOptions.createSimple();
     }
 }
Exemplo n.º 15
0
  /** 初始化ImageLoader */
  public static void initImageLoader(Context context) {
    String filePath =
        Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + context.getPackageName()
            + "/cache/";

    File cacheDir = StorageUtils.getOwnCacheDirectory(context, filePath); // 获取到缓存的目录地址
    Log.d("cacheDir", cacheDir.getPath());
    // 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制),这个可以设定在APPLACATION里面,设置为全局的配置参数
    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(context)
            // .memoryCacheExtraOptions(480, 800) // max width, max
            // height,即保存的每个缓存文件的最大长宽
            // .discCacheExtraOptions(480, 800, CompressFormat.JPEG,
            // 75, null) // Can slow ImageLoader, use it carefully
            // (Better don't use it)设置缓存的详细信息,最好不要设置这个
            .threadPoolSize(3) // 线程池内加载的数量
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .memoryCache(new WeakMemoryCache())
            // .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024
            // * 1024)) // You can pass your own memory cache
            // implementation你可以通过自己的内存缓存实现
            .memoryCacheSize(2 * 1024 * 1024)
            // /.discCacheSize(50 * 1024 * 1024)
            .discCacheFileNameGenerator(new Md5FileNameGenerator()) // 将保存的时候的URI名称用MD5
            // 加密
            // .discCacheFileNameGenerator(new
            // HashCodeFileNameGenerator())//将保存的时候的URI名称用HASHCODE加密
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            // .discCacheFileCount(100) //缓存的File数量
            .discCache(new UnlimitedDiscCache(cacheDir)) // 自定义缓存路径
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .imageDownloader(
                new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout (5 s),
            // readTimeout(30)// 超时时间
            .writeDebugLogs() // Remove for release app
            .build();
    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config); // 全局初始化此配置
  }
 private void initEmptyFiledsWithDefaultValues() {
   if (discCache == null) {
     if (discCacheFileNameGenerator == null) {
       discCacheFileNameGenerator = DefaultConfigurationFactory.createFileNameGenerator();
     }
     discCache =
         DefaultConfigurationFactory.createDiscCache(
             context, discCacheFileNameGenerator, discCacheSize, discCacheFileCount);
   }
   if (memoryCache == null) {
     memoryCache =
         DefaultConfigurationFactory.createMemoryCache(
             memoryCacheSize, denyCacheImageMultipleSizesInMemory);
   }
   if (downloader == null) {
     downloader = DefaultConfigurationFactory.createImageDownloader(context);
   }
   if (defaultDisplayImageOptions == null) {
     defaultDisplayImageOptions = DisplayImageOptions.createSimple();
   }
 }
Exemplo n.º 17
0
  private void initImageLoader() {
    categoryLoadOption =
        new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.product_icon_default) // resource or drawable
            .showImageForEmptyUri(R.drawable.product_icon_default) // resource or drawable
            .showImageOnFail(R.drawable.product_icon_default) // resource or drawable
            .resetViewBeforeLoading(false) // default
            .delayBeforeLoading(500)
            .cacheInMemory(true) // default
            .cacheOnDisk(true) // default
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "imageloader/Cache");

    Util.sysLog(TAG, "image cache path:" + cacheDir.getAbsolutePath());
    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(this)
            .defaultDisplayImageOptions(categoryLoadOption)
            .memoryCacheExtraOptions(480, 800)
            .diskCacheExtraOptions(480, 800, null)
            .threadPoolSize(2)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
            .memoryCacheSize(2 * 1024 * 1024)
            .diskCacheFileNameGenerator(new Md5FileNameGenerator())
            .diskCacheSize(50 * 1024 * 1024)
            .diskCacheFileCount(100)
            .diskCache(new UnlimitedDiscCache(cacheDir))
            .tasksProcessingOrder(QueueProcessingType.FIFO)
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .writeDebugLogs()
            .build();

    ImageLoader.getInstance().init(config);
  }
Exemplo n.º 18
0
  /**
   * Adds load image task to execution pool. Image will be returned with {@link
   * ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)}
   * callback}.<br>
   * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method
   * call
   *
   * @param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
   * @param targetImageSize Minimal size for {@link Bitmap} which will be returned in {@linkplain
   *     ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)}
   *     callback}. Downloaded image will be decoded and scaled to {@link Bitmap} of the size which
   *     is <b>equal or larger</b> (usually a bit larger) than incoming minImageSize .
   * @param options {@linkplain DisplayImageOptions Display image options} for image displaying. If
   *     <b>null</b> - default display image options {@linkplain
   *     ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from
   *     configuration} will be used.<br>
   *     Incoming options should contain {@link FakeBitmapDisplayer} as displayer.
   * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener
   *     fires events on UI thread.
   * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called
   *     before
   */
  public void loadImage(
      String uri,
      ImageSize targetImageSize,
      DisplayImageOptions options,
      ImageLoadingListener listener) {
    checkConfiguration();

    if (targetImageSize == null) {
      targetImageSize =
          new ImageSize(
              configuration.maxImageWidthForMemoryCache,
              configuration.maxImageHeightForMemoryCache);
    }

    if (options == null) {
      options = configuration.defaultDisplayImageOptions;
    }

    DisplayImageOptions optionsWithFakeDisplayer;

    if (options.getDisplayer() instanceof FakeBitmapDisplayer) {
      optionsWithFakeDisplayer = options;

    } else {
      optionsWithFakeDisplayer =
          new DisplayImageOptions.Builder()
              .cloneFrom(options)
              .displayer(fakeBitmapDisplayer)
              .build();
    }

    ImageView fakeImage = new ImageView(configuration.context);
    fakeImage.setLayoutParams(
        new LayoutParams(targetImageSize.getWidth(), targetImageSize.getHeight()));
    fakeImage.setScaleType(ScaleType.CENTER_CROP);

    displayImage(uri, fakeImage, optionsWithFakeDisplayer, listener);
  }
Exemplo n.º 19
0
 @Override
 public void onCreate() {
   super.onCreate();
   application = this;
   WindowManager wm = (WindowManager) this.getSystemService(WINDOW_SERVICE);
   screenHeight = wm.getDefaultDisplay().getHeight();
   screenWidth = wm.getDefaultDisplay().getWidth();
   ImageLoaderConfiguration configuration =
       new ImageLoaderConfiguration.Builder(this)
           .memoryCacheExtraOptions(screenWidth, screenHeight) // 设置解析图片的大小,一般以手机屏幕大小为准
           .diskCacheExtraOptions(screenWidth, screenHeight, null) // 保存到磁盘使用的大小以及压缩方法,默认原图保存
           .threadPoolSize(3) // 线程池大小,不能太大,会出现OOM
           .threadPriority(Thread.NORM_PRIORITY - 1) // 设置线程的优先程度 5-1
           .tasksProcessingOrder(
               QueueProcessingType.FIFO) // 设置图片加载和显示队列处理的类型 默认为QueueProcessingType.
           //  FIFO注:如果设置了taskExecutor或者taskExecutorForCachedImages 此设置无效
           .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 设置内存缓存 默认为一个当前应用可用内存的1/8大小的
           .memoryCacheSize(2 * 1024 * 1014) // 设置内存缓存的最大大小 默认为一个当前应用可用内存的1/8
           .memoryCacheSizePercentage(13) // 设置内存缓存最大大小占当前应用可用内存的百分比 默认为一个当前应用可用内存的1/8
           .diskCache(
               new UnlimitedDiskCache(
                   StorageUtils.getCacheDirectory(
                       getApplicationContext()))) // 默认为StorageUtils.getCacheDirectory(getApplicationContext()),即/mnt/sdcard/android/data/包名/cache/
           .diskCacheSize(50 * 1024 * 1024) // 设置硬盘缓存的最大大小
           .diskCacheFileCount(100) // 设置硬盘缓存的文件的最多个数
           .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // 设置硬盘缓存文件名生成规范
           .imageDownloader(new BaseImageDownloader(this)) // 设置图片下载器
           .imageDecoder(DefaultConfigurationFactory.createImageDecoder(false)) // 设置图片的解析器
           .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // 设置默认的图片显示选项
           .denyCacheImageMultipleSizesInMemory() // 不缓存图片的多种尺寸在内存中
           .writeDebugLogs() // 打印调试Log,注意上线之前要去掉这句话
           .imageDownloader(
               new BaseImageDownloader(this, 5 * 1000, 30 * 1000)) // 图片下载器的设置  超时时间   读取时间
           .build();
   ImageLoader.getInstance().init(configuration); // 使用基本配置信息初始化ImageLoader
 }
Exemplo n.º 20
0
  @Override
  public void onCreate() {
    super.onCreate();
    FileUtils.getInstance(getApplicationContext());
    Log.v("aaaaaaaaa", "dddddddd");
    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(getApplicationContext())
            .memoryCacheExtraOptions(
                480, 800) // max width, max height锟斤拷锟斤拷锟斤拷锟斤拷锟矫匡拷锟斤拷锟斤拷锟斤拷募锟斤拷锟斤拷锟襟长匡拷
            .threadPoolSize(6) // 锟竭程筹拷锟节硷拷锟截碉拷锟斤拷锟斤拷
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .memoryCache(
                new UsingFreqLimitedMemoryCache(
                    2 * 1024
                        * 1024)) // You can pass your own memory cache
                                 // implementation/锟斤拷锟斤拷锟酵拷锟斤拷约锟斤拷锟斤拷诖婊猴拷锟绞碉拷锟�
            .memoryCacheSize(2 * 1024 * 1024)
            .discCacheSize(50 * 1024 * 1024)
            .discCacheFileNameGenerator(
                new Md5FileNameGenerator()) // 锟斤拷锟斤拷锟斤拷锟绞憋拷锟斤拷URI锟斤拷锟斤拷锟組D5 锟斤拷锟斤拷
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            .discCacheFileCount(100) // 锟斤拷锟斤拷锟斤拷募锟斤拷锟斤拷锟�
            // .discCache((DiskCache) new UnlimitedDiscCache(cacheDir))// 锟皆讹拷锟藉缓锟斤拷路锟斤拷
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .imageDownloader(
                new BaseImageDownloader(
                    getApplicationContext(),
                    5 * 1000,
                    30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)锟斤拷时时锟斤拷
            .writeDebugLogs() // Remove for release app
            .build(); // 锟斤拷始锟斤拷锟斤拷
    // Initialize ImageLoader with configuration.

    ImageLoader.getInstance().init(config); // 全锟街筹拷始锟斤拷锟斤拷锟斤拷锟斤拷
  }
Exemplo n.º 21
0
  private ImageLoaderConfiguration getDefaultConfig() throws IOException {
    int MAX_CACHE_MEMORY_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8);
    File cacheDir =
        StorageUtils.getOwnCacheDirectory(context, context.getPackageName() + "/cache/image/");

    LogUtil.i(TAG, "ImageLoader memory cache size = " + MAX_CACHE_MEMORY_SIZE / M + "M");
    LogUtil.i(TAG, "ImageLoader disk cache directory = " + cacheDir.getAbsolutePath());

    ImageLoaderConfiguration config =
        new ImageLoaderConfiguration.Builder(context)
            .threadPoolSize(3) // 线程池内加载的数量
            .threadPriority(Thread.NORM_PRIORITY - 2) // 降低线程的优先级,减小对UI主线程的影响
            .denyCacheImageMultipleSizesInMemory()
            .memoryCache(new LruMemoryCache(MAX_CACHE_MEMORY_SIZE))
            .discCache(new LruDiskCache(cacheDir, new Md5FileNameGenerator(), 0))
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .imageDownloader(
                new BaseImageDownloader(
                    context, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
            .writeDebugLogs()
            .build();

    return config;
  }
  @Override
  public void run() {
    if (waitIfPaused()) return;
    if (delayIfNeed()) return;

    ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
    log(LOG_START_DISPLAY_IMAGE_TASK);
    if (loadFromUriLock.isLocked()) {
      log(LOG_WAITING_FOR_IMAGE_LOADED);
    }

    loadFromUriLock.lock();
    Bitmap bmp;
    try {
      checkTaskNotActual();

      bmp = configuration.memoryCache.get(memoryCacheKey);
      if (bmp == null) {
        bmp = tryLoadBitmap();
        if (bmp == null) return; // listener callback already was fired

        checkTaskNotActual();
        checkTaskInterrupted();

        if (options.shouldPreProcess()) {
          log(LOG_PREPROCESS_IMAGE);
          bmp = options.getPreProcessor().process(bmp);
          if (bmp == null) {
            L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
          }
        }

        if (bmp != null && options.isCacheInMemory()) {
          log(LOG_CACHE_IMAGE_IN_MEMORY);
          configuration.memoryCache.put(memoryCacheKey, bmp);
        }
      } else {
        loadedFrom = LoadedFrom.MEMORY_CACHE;
        log(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING);
      }

      if (bmp != null && options.shouldPostProcess()) {
        log(LOG_POSTPROCESS_IMAGE);
        bmp = options.getPostProcessor().process(bmp);
        if (bmp == null) {
          L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);
        }
      }
      checkTaskNotActual();
      checkTaskInterrupted();
    } catch (TaskCancelledException e) {
      fireCancelEvent();
      return;
    } finally {
      loadFromUriLock.unlock();
    }

    DisplayBitmapTask displayBitmapTask =
        new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
    displayBitmapTask.setLoggingEnabled(writeLogs);
    if (options.isSyncLoading()) {
      displayBitmapTask.run();
    } else {
      handler.post(displayBitmapTask);
    }
  }
Exemplo n.º 23
0
  /**
   * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br>
   * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method
   * call
   *
   * @param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
   * @param imageView {@link ImageView} which should display image
   * @param options {@linkplain DisplayImageOptions Display image options} for image displaying. If
   *     <b>null</b> - default display image options {@linkplain
   *     ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from
   *     configuration} will be used.
   * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener
   *     fires events on UI thread.
   * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called
   *     before
   * @throws IllegalArgumentException if passed <b>imageView</b> is null
   */
  public void displayImage(
      String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) {
    checkConfiguration();

    if (imageView == null) {
      throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
    }

    if (listener == null) {
      listener = emptyListener;
    }

    if (options == null) {
      options = configuration.defaultDisplayImageOptions;
    }

    if (TextUtils.isEmpty(uri)) {
      engine.cancelDisplayTaskFor(imageView);
      listener.onLoadingStarted(uri, imageView);

      if (options.shouldShowImageResForEmptyUri()) {
        imageView.setImageResource(options.getImageResForEmptyUri());

      } else if (options.shouldShowImageForEmptyUri()) {
        imageView.setImageDrawable(options.getImageForEmptyUri());

      } else {
        imageView.setImageDrawable(null);
      }

      listener.onLoadingComplete(uri, imageView, null);
      return;
    }

    ImageSize targetSize =
        ImageSizeUtils.defineTargetSizeForView(
            imageView,
            configuration.maxImageWidthForMemoryCache,
            configuration.maxImageHeightForMemoryCache);
    String memoryCacheKey = MemoryCacheUtil.generateKey(uri, targetSize);
    engine.prepareDisplayTaskFor(imageView, memoryCacheKey);

    listener.onLoadingStarted(uri, imageView);
    Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);

    if (bmp != null && !bmp.isRecycled()) {
      if (configuration.writeLogs) {
        L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);
      }

      if (options.shouldPostProcess()) {
        ImageLoadingInfo imageLoadingInfo =
            new ImageLoadingInfo(
                uri,
                imageView,
                targetSize,
                memoryCacheKey,
                options,
                listener,
                engine.getLockForUri(uri));
        ProcessAndDisplayImageTask displayTask =
            new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo, options.getHandler());
        engine.submit(displayTask);

      } else {
        options.getDisplayer().display(bmp, imageView, LoadedFrom.MEMORY_CACHE);
        listener.onLoadingComplete(uri, imageView, bmp);
      }

    } else {
      if (options.shouldShowImageResOnLoading()) {
        imageView.setImageResource(options.getImageResOnLoading());

      } else if (options.shouldShowImageOnLoading()) {
        imageView.setImageDrawable(options.getImageOnLoading());

      } else {
        if (options.isResetViewBeforeLoading()) {
          imageView.setImageDrawable(null);
        }
      }

      ImageLoadingInfo imageLoadingInfo =
          new ImageLoadingInfo(
              uri,
              imageView,
              targetSize,
              memoryCacheKey,
              options,
              listener,
              engine.getLockForUri(uri));
      LoadAndDisplayImageTask displayTask =
          new LoadAndDisplayImageTask(engine, imageLoadingInfo, options.getHandler());
      engine.submit(displayTask);
    }
  }
Exemplo n.º 24
0
 public Builder cloneFrom(DisplayImageOptions paramDisplayImageOptions) {
   this.a = DisplayImageOptions.a(paramDisplayImageOptions);
   this.b = DisplayImageOptions.b(paramDisplayImageOptions);
   this.c = DisplayImageOptions.c(paramDisplayImageOptions);
   this.d = DisplayImageOptions.d(paramDisplayImageOptions);
   this.e = DisplayImageOptions.e(paramDisplayImageOptions);
   this.f = DisplayImageOptions.f(paramDisplayImageOptions);
   this.g = DisplayImageOptions.g(paramDisplayImageOptions);
   this.h = DisplayImageOptions.h(paramDisplayImageOptions);
   this.i = DisplayImageOptions.i(paramDisplayImageOptions);
   this.j = DisplayImageOptions.j(paramDisplayImageOptions);
   this.k = DisplayImageOptions.k(paramDisplayImageOptions);
   this.l = DisplayImageOptions.l(paramDisplayImageOptions);
   this.m = DisplayImageOptions.m(paramDisplayImageOptions);
   this.n = DisplayImageOptions.n(paramDisplayImageOptions);
   this.o = DisplayImageOptions.o(paramDisplayImageOptions);
   this.p = DisplayImageOptions.p(paramDisplayImageOptions);
   this.q = DisplayImageOptions.q(paramDisplayImageOptions);
   this.r = DisplayImageOptions.r(paramDisplayImageOptions);
   this.s = DisplayImageOptions.s(paramDisplayImageOptions);
   return this;
 }
  @Override
  public void run() {
    AtomicBoolean pause = engine.getPause();
    if (pause.get()) {
      synchronized (pause) {
        log(LOG_WAITING_FOR_RESUME, memoryCacheKey);
        try {
          pause.wait();
        } catch (InterruptedException e) {
          L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
          return;
        }
        log(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);
      }
    }
    if (checkTaskIsNotActual()) return;

    if (options.shouldDelayBeforeLoading()) {
      log(LOG_DELAY_BEFORE_LOADING, options.getDelayBeforeLoading(), memoryCacheKey);
      try {
        Thread.sleep(options.getDelayBeforeLoading());
      } catch (InterruptedException e) {
        L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
        return;
      }

      if (checkTaskIsNotActual()) return;
    }

    ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
    log(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);
    if (loadFromUriLock.isLocked()) {
      log(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);
    }

    loadFromUriLock.lock();
    Bitmap bmp;
    try {
      if (checkTaskIsNotActual()) return;

      bmp = configuration.memoryCache.get(memoryCacheKey);
      if (bmp == null) {
        bmp = tryLoadBitmap();
        if (bmp == null) return;

        if (checkTaskIsNotActual() || checkTaskIsInterrupted()) return;

        if (options.isCacheInMemory()) {
          if (options.shouldPreProcess()) {
            log(LOG_PREPROCESS_IMAGE, memoryCacheKey);
            bmp = options.getPreProcessor().process(bmp, imageView);
          }

          log(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);
          configuration.memoryCache.put(memoryCacheKey, bmp);
        }
      } else {
        log(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);
      }

      if (options.shouldPostProcess()) {
        log(LOG_POSTPROCESS_IMAGE, memoryCacheKey);
        bmp = options.getPostProcessor().process(bmp, imageView);
      }
    } finally {
      loadFromUriLock.unlock();
    }

    if (checkTaskIsNotActual() || checkTaskIsInterrupted()) return;

    DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine);
    displayBitmapTask.setLoggingEnabled(loggingEnabled);
    handler.post(displayBitmapTask);
  }