1、爲什麼要異步加載圖片?
2、緩存的實現(SoftReference)?
棧內存:存放對象的引用。堆內存:存放對象。引用指向對象,當對象的引用不再指向某個對象,或者對象無引用指向,垃圾回收器就會把他們回收。
SoftReference :軟引用,非完成的引用。當垃圾回收機制啓動時,首先判斷內存是否已滿,如果未滿,則不對軟引用做處理,但是,當內存已滿時,會把軟引用回收。
SoftReference<Object> sr=new SoftReference<Object>(new Object());
Object obj=sr.get();
3、異步加載圖片的方法?
- public class AsyncImageLoader {
- //key:圖片的URL value:SoftReference對象,該對象指向一個Drawable對象
- private HashMap<String, SoftReference<Drawable>> imageCache;
- public AsyncImageLoader() {
- imageCache = new HashMap<String, SoftReference<Drawable>>();
- }
- public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
- if (imageCache.containsKey(imageUrl)) { //首先判斷緩存中是否含有該圖片,存在的話獲取並返回
- SoftReference<Drawable> softReference = imageCache.get(imageUrl);
- Drawable drawable = softReference.get();
- if (drawable != null) {
- return drawable;
- }
- }
- final Handler handler = new Handler() { //不存在的話,在線程中加載,並通過Handler發送至UI線程
- public void handleMessage(Message message) {
- imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
- }
- };
- new Thread() {
- @Override
- public void run() {
- Drawable drawable = loadImageFromUrl(imageUrl);
- imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
- Message message = handler.obtainMessage(0, drawable);
- handler.sendMessage(message);
- }
- }.start();
- return null;
- }
- public static Drawable loadImageFromUrl(String url) { //通過圖片url獲取圖片資源
- URL m;
- InputStream i = null;
- try {
- m = new URL(url);
- i = (InputStream) m.getContent();
- } catch (MalformedURLException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- Drawable d = Drawable.createFromStream(i, "src");
- return d;
- }
- public interface ImageCallback { //自定義一個接口,
- public void imageLoaded(Drawable imageDrawable, String imageUrl);
- }
- }