Android开发之一种简单的异步加载图片方法

简介:

首先说明的是,该方法已经被我抛弃了。之前用它,发现加载速度不好。具体没怎么细心的看。

现在我用volley了。拿出来只是给大家批判的。

package com.souya.seller.util.ex;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import AXLib.Utility.Console;
import AXLib.Utility.HttpClient;
import AXLib.Utility.Queue;
import AXLib.Utility.RuntimeExceptionEx;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Video.Thumbnails;
import android.util.Log;
import android.widget.ImageView;

import com.souya.seller.app.SellerApplication;


public class AsyncImageLoader {
	private static boolean _D =  false;//AppConfig._D &&
	private static final String TAG = "AsyncImageLoader";
	public static String CachePath = null;
	private static String ThumbnailPath = null;
	private static boolean _isInit = false;
	private static Context _ctx;
	private static Bitmap _empty = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
	private static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
	private static Queue<Runnable> queue = new Queue<Runnable>();
	// 线程池:最大50条,每次执行:1条,空闲线程结束的超时时间:180秒
	private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 20, 300, TimeUnit.SECONDS, queue);
	public final static AsyncImageLoader Instance = new AsyncImageLoader();

	public static void Init(final Context context) {
		CachePath = SellerApplication.getInstance().mAppCacheDir + "";
		ThumbnailPath = CachePath + "/thumbnails";
		if (!new File(ThumbnailPath).exists())
			new File(ThumbnailPath).mkdirs();
		_ctx = context;
		_isInit = true;
	}

	public static Drawable loadDrawable(final Context context, final String url, final ImageCallback imageCallback) {
		if (!_isInit)
			Init(context);
		final String key = url;
		synchronized (imageCache) {
			if (imageCache.containsKey(key)) {
				SoftReference<Bitmap> softReference = imageCache.get(key);
				Bitmap bmp = softReference.get();
				if (bmp != null && !bmp.isRecycled()) {
					if (bmp == _empty) {
						bmp = bmp;
					} else
						return new BitmapDrawable(bmp);
				}
			} else {
				imageCache.put(key, new SoftReference<Bitmap>(_empty));
			}
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, url);
			}
		};

		// 用线程池来做下载图片的任务
		executor.execute(new Runnable() {
			@Override
			public void run() {
				Bitmap bmp = loadImage(url);
				if (bmp != null) {
					synchronized (imageCache) {
						if (imageCache.containsKey(key)) {
							imageCache.put(key, new SoftReference<Bitmap>(bmp));
							Message message = handler.obtainMessage(0, new BitmapDrawable(bmp));
							handler.sendMessage(message);
						} else {
							if (!bmp.isRecycled())
								bmp.recycle();
							bmp = null;
							System.gc();
						}
					}
				}
			}
		});
		return null;
	}

	public static Drawable loadDrawable(final Context context, final String url, final int width, final int height, final ImageCallback imageCallback) {
		if (!_isInit)
			Init(context);
		final String key = String.format("%s_%d_%d", url, width, height);
		if (imageCache.containsKey(key)) {
			SoftReference<Bitmap> softReference = imageCache.get(key);
			Bitmap bmp = softReference.get();
			if (bmp != null && !bmp.isRecycled()) {
				if (bmp == _empty) {
					bmp = bmp;
				} else
					return new BitmapDrawable(bmp);
			}

		} else {
			imageCache.put(key, new SoftReference<Bitmap>(_empty));
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, url);
			}
		};

		// 用线程池来做下载图片的任务
		executor.execute(new Runnable() {
			@Override
			public void run() {
				Bitmap bmp = loadImageAndScale(url, width, height);
				if (imageCache.containsKey(key)) {
					imageCache.put(key, new SoftReference<Bitmap>(bmp));
					Message message = handler.obtainMessage(0, new BitmapDrawable(bmp));
					handler.sendMessage(message);
				} else {
					if (!bmp.isRecycled())
						bmp.recycle();
					bmp = null;
					System.gc();
				}
			}
		});

		return null;
	}
 

	public static void releaseDrawable(String url, int width, int height) {
		log("releaseDrawable" + url);
		String key = String.format("%s_%d_%d", url, width, height);
		releaseDrawable(key);

	}

	public static void releaseDrawable(String url) {
		try {
			log("releaseDrawable" + url);
			String key = url;
			synchronized (imageCache) {
				if (imageCache.containsKey(key)) {
					SoftReference<Bitmap> softReference = imageCache.get(key);
					imageCache.remove(key);
					Bitmap bmp = softReference.get();
					if (bmp != null && bmp != _empty && !bmp.isRecycled()) {
						bmp.recycle();
						bmp = null;
					}
					System.gc();
				}
			}
		} catch (Exception e) {
			String stack = RuntimeExceptionEx.GetStackTraceString(e);

		}
	}

	private static HashMap<String, Object> _loadImageLocks = new HashMap<String, Object>();

	public static Bitmap loadImage(String url) {
		log("londImage:" + url);
		Object lockObj = null;
		synchronized (_loadImageLocks) {
			if (_loadImageLocks.containsKey(url))
				lockObj = _loadImageLocks.get(url);
			else {
				lockObj = new Object();
				_loadImageLocks.put(url, lockObj);
			}
		}
		synchronized (lockObj) {
			if (isLocalImage(url))
				return loadLocalImage(url);
			else {
				String localUrl = getCacheFileName(url);
				Bitmap bmp = null;
				if (new File(localUrl).exists())
					bmp = loadLocalImage(localUrl);
				try {
					if (bmp == null)
						bmp = loadHttpImage(url, 0, 0);
				} catch (Throwable e) {
					if (_D)
						throw RuntimeExceptionEx.Create(e);
				}
				return bmp;
			}
		}

	}

	public static Bitmap loadImage(String url, int width, int height) {
		log("londImage:" + url);
		Object lockObj = null;
		synchronized (_loadImageLocks) {
			if (_loadImageLocks.containsKey(url))
				lockObj = _loadImageLocks.get(url);
			else {
				lockObj = new Object();
				_loadImageLocks.put(url, lockObj);
			}
		}
		synchronized (lockObj) {
			if (isLocalImage(url))
				return loadLocalImage(url, width, height);
			else {
				String localUrl = getCacheFileName(url);
				Bitmap bmp = null;
				if (new File(localUrl).exists())
					bmp = loadLocalImage(localUrl, width, height);
				try {
					if (bmp == null)
						bmp = loadHttpImage(url, width, height);
				} catch (Throwable e) {
					if (_D)
						throw RuntimeExceptionEx.Create(e);
				}
				return bmp;
			}
		}

	}

	private static Bitmap loadLocalImageByVideo(String url) {
		log("loadLocalImageByVideo:" + url);
		if (!new File(url).exists())
			return null;
		Bitmap bmp = ThumbnailUtils.createVideoThumbnail(url, Thumbnails.MINI_KIND);
		return bmp;
	}

	private static Bitmap loadLocalImage(String url) {
		return loadLocalImage(url, 0);
	}

	private static Bitmap loadLocalImage(String url, int width, int height) {
		if (width == 0 && height == 0)
			return loadLocalImage(url);
		else
			return _loadLocalImage(url, width, height);
	}

	private static Bitmap _loadLocalImage(String url, int width, int height) {
		try {

			if (!new File(url).exists())
				return null;

			// 获取屏幕的宽和高
			/**
			 * 为了计算缩放的比例,我们需要获取整个图片的尺寸,而不是图片
			 * BitmapFactory.Options类中有一个布尔型变量inJustDecodeBounds,将其设置为true
			 * 这样,我们获取到的就是图片的尺寸,而不用加载图片了。 当我们设置这个值的时候,我们接着就可以从BitmapFactory.
			 * Options的outWidth和outHeight中获取到值
			 */
			BitmapFactory.Options op = new BitmapFactory.Options();
			op.inJustDecodeBounds = true;

			Uri uri = Uri.fromFile(new File(url));

			// 由于使用了MediaStore存储,这里根据URI获取输入流的形式
			Bitmap pic = BitmapFactory.decodeStream(_ctx.getContentResolver().openInputStream(uri), null, op);

			int wRatio = (int) Math.ceil(op.outWidth / (float) width); // 计算宽度比例
			int hRatio = (int) Math.ceil(op.outHeight / (float) height); // 计算高度比例
			if (pic != null && !pic.isRecycled())
				pic.recycle();
			/**
			 * 接下来,我们就需要判断是否需要缩放以及到底对宽还是高进行缩放。 如果高和宽不是全都超出了屏幕,那么无需缩放。
			 * 如果高和宽都超出了屏幕大小,则如何选择缩放呢》 这需要判断wRatio和hRatio的大小
			 * 大的一个将被缩放,因为缩放大的时,小的应该自动进行同比率缩放。 缩放使用的还是inSampleSize变量
			 */
			if (wRatio > 1 && hRatio > 1) {
				if (wRatio > hRatio) {
					op.inSampleSize = wRatio;
				} else {
					op.inSampleSize = hRatio;
				}
			}
			op.inJustDecodeBounds = false; // 注意这里,一定要设置为false,因为上面我们将其设置为true来获取图片尺寸了
			try {
				pic = BitmapFactory.decodeStream(_ctx.getContentResolver().openInputStream(uri), null, op);
			} catch (OutOfMemoryError e) {
				loadLocalImage(url, 1);
			}
			return pic;
		} catch (Throwable e) {
			throw RuntimeExceptionEx.Create(e);
		}
	}

	private static Bitmap loadLocalImage(String url, int inSampleSize) {
		log("loadLocalImage:" + url);
		if (!new File(url).exists())
			return null;
		if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
			return loadLocalImageByVideo(url);
		}
		BitmapFactory.Options opt = new BitmapFactory.Options();
		// opt.inPreferredConfig = Bitmap.Config.RGB_565;
		// opt.inPurgeable = true;
		// opt.inInputShareable = true;
		opt.inSampleSize = inSampleSize;
		// 获取资源图片
		InputStream is = null;
		try {
			is = new FileInputStream(url);
			if (is != null) {

				Bitmap map = BitmapFactory.decodeStream(is, null, opt);
				if (map == null)
					return null;
				int height = map.getHeight();
				int width = map.getWidth();

				if (width > 1920 || height > 1080) {
					if (inSampleSize == 0)
						inSampleSize = 2;
					else
						inSampleSize++;
					if (is != null) {
						try {
							is.close();
						} catch (Exception ex) {

						}
					}
					map.recycle();
					map = null;
					return loadLocalImage(url, inSampleSize);
				} else {
					return map;
				}
			}
		} catch (OutOfMemoryError e) {
			if (is != null) {
				try {
					is.close();
				} catch (Exception ex) {

				}
			}
			System.gc();
			if (inSampleSize < 50) {
				if (inSampleSize == 0)
					inSampleSize = 2;
				else
					inSampleSize++;
				return loadLocalImage(url, inSampleSize);
			} else
				return null;

		} catch (Throwable e) {
			String stack = RuntimeExceptionEx.GetStackTraceString(e);
			//CLLog.Error(e);
			//if (_D)
		    //	throw RuntimeExceptionEx.Create(e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {

				}
			}
			System.gc();

		}
		return null;
	}

	private static Bitmap loadHttpImage(String url, int width, int height) {
		log("loadHttpImage:" + url);
		String localUrl = getCacheFileName(url);
		try {
			HttpClient hc = new HttpClient();
			if (hc.downFile(url, localUrl))
				return loadLocalImage(localUrl, width, height);
			else
				return null;
		} catch (Exception e) {
			String stack = RuntimeExceptionEx.GetStackTraceString(e);
			//CLLog.Error(e);
			//if (_D)
			//	throw RuntimeExceptionEx.Create(e);
		}

		return null;
	}

	public static Bitmap loadImageAndScale(String url, int width, int height) {
		log("loadImageAndScale:" + url);
		String thumbnailUrl = getThumbnailFileName(url, width, height);
		Bitmap bmp = loadLocalImage(url, width, height);
		if (bmp == null) {
			try {
				bmp = loadImage(url, width, height);
			} catch (Exception e) {
				String stack = RuntimeExceptionEx.GetStackTraceString(e);
			}
			if (bmp != null) {
				Bitmap bmpThumbnail = ImageHelper.ScaleAndSave(bmp, thumbnailUrl, width, height, true, true);
				if (bmpThumbnail != bmp && !bmp.isRecycled())
					bmp.recycle();
				bmp = null;
				System.gc();
				bmp = bmpThumbnail;
			}
		}
		return bmp;
	}

	private static boolean isLocalImage(String url) {
		return new File(url).exists();
	}

	private static String getCacheFileName(String url) {
		if (isLocalImage(url))
			return url;
		String localUrl = null;
		if (url != null && url.length() != 0) {
			localUrl = CachePath + "/" + url.substring(url.lastIndexOf("/") + 1);
		}
		return localUrl;
	}

	private static String getThumbnailFileName(String url, int width, int height) {
		String thumbnailUrl = null;
		if (url != null && url.length() != 0) {
			thumbnailUrl = String.format("%s/%d_%d_%s", ThumbnailPath, width, height, url.substring(url.lastIndexOf("/") + 1));
		}
		return thumbnailUrl;
	}

	private static void log(String msg) {
		// Console.d("AsyncImageLoader", msg);
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}

}


相关文章
|
4天前
|
Java Android开发
android 下载图片的问题
android 下载图片的问题
11 3
|
5天前
|
Android开发
Android通过手势(多点)缩放和拖拽图片
Android通过手势(多点)缩放和拖拽图片
12 4
|
7天前
|
机器学习/深度学习 Java Shell
[RK3568][Android12.0]--- 系统自带预置第三方APK方法
[RK3568][Android12.0]--- 系统自带预置第三方APK方法
33 0
|
4天前
|
Java Android开发
Android开发--Intent-filter属性详解
Android开发--Intent-filter属性详解
|
4天前
|
物联网 Java 开发工具
安卓应用开发:打造未来移动生活
【5月更文挑战第10天】 随着科技的飞速发展,智能手机已成为我们日常生活中不可或缺的一部分。作为智能手机市场的两大巨头,安卓和iOS分别占据了一定的市场份额。在这篇文章中,我们将重点关注安卓应用开发,探讨如何利用先进的技术和创新思维,为用户打造更加便捷、智能的移动生活。文章将涵盖安卓应用开发的基本概念、关键技术、以及未来发展趋势等方面的内容。
|
6天前
|
Java API 开发工具
java与Android开发入门指南
java与Android开发入门指南
14 0
|
7天前
|
程序员 Android开发
Android亮度调节的几种实现方法
Android亮度调节的几种实现方法
9 0
|
7天前
|
Shell Android开发
Android Activity重写dump方法实现通过adb调试代码
Android Activity重写dump方法实现通过adb调试代码
13 0
|
7天前
|
Android开发
Android APP 隐藏系统软键盘的方法
Android APP 隐藏系统软键盘的方法
13 0
|
7天前
|
Android开发 Kotlin
Kotlin开发Android之基础问题记录
Kotlin开发Android之基础问题记录
17 1