Reputation: 1006
I have the following piece of code to work with but I just did not understand how this works, to start off refer the following link
http://developer.android.com/reference/android/os/Message.html#sendToTarget%28%29
It clearly states that sendToTarget() sends message to the specified Handler by getTarget() or it throws a NPE. In the following code, I dont see an implementation of getTarget() but its working fine, please explain how this works, look for queueThumbnail() function here..specified in comments exactly where Im not understanding how it works
public class ThumbnailDownloader<Token> extends HandlerThread {
private static final String TAG = "ThumbNailDownloader";
private static final int MESSAGE_DOWNLOAD = 0;
Handler mHandler;
Map <Token, String> requestMap = Collections.synchronizedMap(new HashMap<Token,String>());
public ThumbnailDownloader(Handler responseHandler)
{
super(TAG);
}
@SuppressLint("HandlerLeak")
@Override
protected void onLooperPrepared()
{
mHandler = new Handler(){
@Override
public void handleMessage(Message msg)
{
if(msg.what==MESSAGE_DOWNLOAD)
{
@SuppressWarnings("unchecked")
Token token = (Token)msg.obj;
Log.i(TAG, "Got a request for Url:"+requestMap.get(token));
handleRequest(token);
}
}
};
}
public void handleRequest(final Token token)
{
try
{
final String url = requestMap.get(token);
if(url == null) return;
byte[] bitmapBytes = new FlickrFetchr().getUrlBytes(url);
final Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
Log.i(TAG, "Bitmap Created");
mResponseHandler.post(new Runnable(){
public void run()
{
if(requestMap.get(token)!=url) return;
requestMap.remove(token);
mListener.onThumbnailDownloaded(token, bitmap);
}
});
}
catch(IOException ioe)
{
Log.e(TAG, "Error Downloading Image"+ioe);
}
}
public void queueThumbnail(Token token, String url)
{
Log.i(TAG, "Got an URL: "+url);
requestMap.put(token, url);
mHandler.obtainMessage(MESSAGE_DOWNLOAD, token).sendToTarget();
//some other class calls this function
//here the target is not set, but I see the request is handled well
//how is this possible? getTarget() is not set anywhere is here
}
Upvotes: 2
Views: 4172
Reputation: 24730
just look at here https://android.googlesource.com/platform/frameworks/base.git/+/6083d81ce4d67ec632962270fda64ebb9db0d5b1/core/java/android/os/Message.java, and you will know everything, btw if you are extending HandlerThread you are probably on the wrong path
Upvotes: 3