2

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

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
    }
4

1 回答 1

3

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

于 2013-09-30T06:48:58.923 回答