Android Message.sendToTarget()在没有设置getTarget()的情况下工作

时间:2013-09-30 06:07:40

标签: java android handler

我有以下代码可以使用,但我只是不明白这是如何工作的,开始参考以下链接

http://developer.android.com/reference/android/os/Message.html#sendToTarget%28%29

它清楚地说明sendToTarget()通过getTarget()向指定的Handler发送消息,或者它抛出NPE。在下面的代码中,我没有看到getTarget()的实现,但它的工作正常,请解释这是如何工作的,在这里查找queueThumbnail()函数..在注释中指定的确切位置我不理解它是如何工作的

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
    }

1 个答案:

答案 0 :(得分:3)

只看这里https://android.googlesource.com/platform/frameworks/base.git/+/6083d81ce4d67ec632962270fda64ebb9db0d5b1/core/java/android/os/Message.java,你会知道一切,顺便说一句,如果你正在扩展HandlerThread,你可能走错了路