gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:55:44 25 4
gpt4 key购买 nike

我有以下代码可以使用,但我只是不明白它是如何工作的,首先请引用以下链接

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
}

最佳答案

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

关于java - Android Message.sendToTarget() 在没有设置 getTarget() 的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19087444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com