Android应用程序的新功能:需要一些帮助 我试图显示我从我的c ++套接字收到的图像。我能够从我的服务器套接字接收图像,它显示我收到的图像。但是之后仿真器力量关闭了,我不明白为什么。
Android代码
private class Connect extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params){
int imageSize=921600;
InputStream in;
mRun = true;
try{
port1 = Integer.parseInt(port);
client = new Socket(ip, port1);
try{
while(mRun){
in = client.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int remainingBytes = imageSize; //
while (remainingBytes > 0) {
int bytesRead = in.read(buffer);
if (bytesRead < 0) {
throw new IOException("Unexpected end of data");
}
baos.write(buffer, 0, bytesRead);
remainingBytes -= bytesRead;
}
in.close();
imageByte = baos.toByteArray();
baos.close();
int nrOfPixels = imageByte.length / 3; // Three bytes per pixel.
int pixels[] = new int[nrOfPixels];
for(int i = 0; i < nrOfPixels; i++) {
int r = imageByte[3*i];
int g = imageByte[3*i + 1];
int b = imageByte[3*i + 2];
if (r < 0)
r = r + 256;
if (g < 0)
g = g + 256;
if (b < 0)
b = b + 256;
pixels[i] = Color.rgb(b,g,r);
}
Bitmap bitmap = Bitmap.createBitmap(pixels, 640, 480,Bitmap.Config.ARGB_8888);
camera.setImageBitmap(bitmap);
camera.invalidate();
}
} catch (IOException e){}
}
catch (UnknownHostException e) {}
catch (IOException e){}
return null;
}
}
答案 0 :(得分:0)
模拟器力量在此之后关闭,我不知道为什么
因为doInBackground
方法在后台线程上运行,但您尝试在此处为doInBackground
的图像设置位图:
camera.setImageBitmap(bitmap);
camera.invalidate();
要从主UI更新ImageView位图,请使用onPostExecute为ImageView调用setImageBitmap
和invalidate
,因为当doInBackground
方法任务完成时,此方法在主UI线程上运行
或
使用runOnUiThread
方法从setImageBitmap
调用invalidate
和doInBackground
方法:
YourActivityName.this.runOnUiThread(new Runnable() {
@Override
public void run() {
camera.setImageBitmap(bitmap);
camera.invalidate();
}
});