import java.lang.ref.SoftReference;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
HashMap<String, SoftReference<Drawable>> drawableMap = new HashMap<String, SoftReference<Drawable>>();
public AsyncImageLoader() {
//HashMap<String, SoftReference<Drawable>> drawableMap = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
if (drawableMap.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
//this is the new thread that download the image from url
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) {
return null;
// ...
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}
OK, My understanding is such:
1)Check to see if the image in the cache, if it is then return drawable;
2)If not, then create a new handler to send a message to UI thread with Drawable as object, and this handler won't send until the imageloaded callback function is called
3)create a new thread to initiate download image from url.
4) specifically the sequence for handler happens in this order A)Message message = handler.obtainMessage(0, drawable); B) public void handleMessage(Message message) { imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } C) handler.sendMessage(message);
The issue I have is Number 4, I am abit unclear, obtainmessage(0, drawable)? obtain from where? where's the source? How do I know where it come from, UI thread or others? So, once obtained that message, the message handler would do the callback. public void handleMessage(Message message) { imageCallback.imageLoaded((Drawable) message.obj, imageUrl); }
finally it send the message with drawable as payload. handler.sendMessage(message); but how do I know where its sending? Does it always have UI thread as final destination?
thanks