gpt4 book ai didi

android - 如何从另一个线程(Android 处理程序)在 ImageView 中显示位图

转载 作者:行者123 更新时间:2023-11-29 15:45:16 26 4
gpt4 key购买 nike

我正在另一个线程中通过 TCP 从服务器下载图像,我想在 Activity 的 ImageView 中显示它。我创建了处理程序,但无法正常工作(不显示下载的图像)。怎么了?

编辑代码:

public class TcpClient extends Activity  {

ImageView imageView;

public static String aHost;
public String aSocketIn;

public static int aSocketInInt;

private Handler uiHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bundle_result);

imageView = (ImageView) findViewById(R.id.imageView);

Intent intent = getIntent();

aHost = intent.getStringExtra("addressIp");
aSocketIn = intent.getStringExtra("socketIn");

aSocketInInt = Integer.parseInt(aSocketIn);


uiHandler = new Handler();

ClientInThread clientInThread = new ClientInThread(aHost,aSocketInInt,uiHandler,imageView);
(new Thread(clientInThread)).start();

} }

class ClientInThread extends Thread implements Runnable {

public Bitmap bitmap = null;
public Handler handler;
String Host;
int SocketIn;
ImageView imageView;
ClientIn clientIn;

ClientInThread(String Host, int SocketIn, Handler handler, ImageView imageView) {
this.Host = Host;
this.SocketIn = SocketIn;
this.handler = handler;
this.imageView = imageView;
}

public void run() {
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});

try {
InetAddress serwerAddress = InetAddress.getByName(Host);
Socket socket = new Socket(serwerAddress, SocketIn);
clientIn = new ClientIn(socket);
bitmap = clientIn.Receive();

}
catch (Exception e) {
e.printStackTrace();
}
} }

最佳答案

您误用了处理程序。您应该像这样获取 UI 线程的处理程序,而不是使用处理程序的 handleMessage 方法:

     ...
private Handler uiHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bundle_result);
...
uiHandler = new Handler();
...
}

...

public void run() {
try {
InetAddress serwerAddress = InetAddress.getByName(Host);
Socket socket = new Socket(serwerAddress, SocketIn);
clientIn = new ClientIn(socket);
bitmap = clientIn.Receive();
} catch (Exception e) {
e.printStackTrace();
}
if (bitmap == null) {
// Downloading error
return;
}
// When a bitmap is downloaded you do:
uiHandler.post(new Runnable() {
imageView.setImageBitmap(bitmap);
});
...
}

如果您不限于使用第三方库您可以使用非常酷的库 UniversalImageLoader 来完成此类任务。看这里https://github.com/nostra13/Android-Universal-Image-Loader .

关于android - 如何从另一个线程(Android 处理程序)在 ImageView 中显示位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941876/

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